org.el (org-open-link-in-comment-or-property): Refactor into `org-open-at-point'
[org-mode.git] / lisp / org.el
blob64bbae4689d97752e4908139aa9a601e8ac03aae
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 (defvaralias 'org-activate-links 'org-highlight-links)
1730 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1731 "Types of links that should be highlighted in Org-mode files.
1733 This is a list of symbols, each one of them leading to the
1734 highlighting of a certain link type.
1736 You can still open links that are not highlighted.
1738 In principle, it does not hurt to turn on highlighting for all
1739 link types. There may be a small gain when turning off unused
1740 link types. The types are:
1742 bracket The recommended [[link][description]] or [[link]] links with hiding.
1743 angle Links in angular brackets that may contain whitespace like
1744 <bbdb:Carsten Dominik>.
1745 plain Plain links in normal text, no whitespace, like http://google.com.
1746 radio Text that is matched by a radio target, see manual for details.
1747 tag Tag settings in a headline (link to tag search).
1748 date Time stamps (link to calendar).
1749 footnote Footnote labels.
1751 If you set this variable during an Emacs session, use `org-mode-restart'
1752 in the Org buffer so that the change takes effect."
1753 :group 'org-link
1754 :group 'org-appearance
1755 :type '(set :greedy t
1756 (const :tag "Double bracket links" bracket)
1757 (const :tag "Angular bracket links" angle)
1758 (const :tag "Plain text links" plain)
1759 (const :tag "Radio target matches" radio)
1760 (const :tag "Tags" tag)
1761 (const :tag "Timestamps" date)
1762 (const :tag "Footnotes" footnote)))
1764 (defcustom org-make-link-description-function nil
1765 "Function to use for generating link descriptions from links.
1766 When nil, the link location will be used. This function must take
1767 two parameters: the first one is the link, the second one is the
1768 description generated by `org-insert-link'. The function should
1769 return the description to use."
1770 :group 'org-link
1771 :type '(choice (const nil) (function)))
1773 (defgroup org-link-store nil
1774 "Options concerning storing links in Org-mode."
1775 :tag "Org Store Link"
1776 :group 'org-link)
1778 (defcustom org-url-hexify-p t
1779 "When non-nil, hexify URL when creating a link."
1780 :type 'boolean
1781 :version "24.3"
1782 :group 'org-link-store)
1784 (defcustom org-email-link-description-format "Email %c: %.30s"
1785 "Format of the description part of a link to an email or usenet message.
1786 The following %-escapes will be replaced by corresponding information:
1788 %F full \"From\" field
1789 %f name, taken from \"From\" field, address if no name
1790 %T full \"To\" field
1791 %t first name in \"To\" field, address if no name
1792 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1793 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1794 %s subject
1795 %d date
1796 %m message-id.
1798 You may use normal field width specification between the % and the letter.
1799 This is for example useful to limit the length of the subject.
1801 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1802 :group 'org-link-store
1803 :type 'string)
1805 (defcustom org-from-is-user-regexp
1806 (let (r1 r2)
1807 (when (and user-mail-address (not (string= user-mail-address "")))
1808 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1809 (when (and user-full-name (not (string= user-full-name "")))
1810 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1811 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1812 "Regexp matched against the \"From:\" header of an email or usenet message.
1813 It should match if the message is from the user him/herself."
1814 :group 'org-link-store
1815 :type 'regexp)
1817 (defcustom org-context-in-file-links t
1818 "Non-nil means file links from `org-store-link' contain context.
1819 A search string will be added to the file name with :: as separator and
1820 used to find the context when the link is activated by the command
1821 `org-open-at-point'. When this option is t, the entire active region
1822 will be placed in the search string of the file link. If set to a
1823 positive integer, only the first n lines of context will be stored.
1825 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1826 negates this setting for the duration of the command."
1827 :group 'org-link-store
1828 :type '(choice boolean integer))
1830 (defcustom org-keep-stored-link-after-insertion nil
1831 "Non-nil means keep link in list for entire session.
1833 The command `org-store-link' adds a link pointing to the current
1834 location to an internal list. These links accumulate during a session.
1835 The command `org-insert-link' can be used to insert links into any
1836 Org-mode file (offering completion for all stored links). When this
1837 option is nil, every link which has been inserted once using \\[org-insert-link]
1838 will be removed from the list, to make completing the unused links
1839 more efficient."
1840 :group 'org-link-store
1841 :type 'boolean)
1843 (defgroup org-link-follow nil
1844 "Options concerning following links in Org-mode."
1845 :tag "Org Follow Link"
1846 :group 'org-link)
1848 (defcustom org-link-translation-function nil
1849 "Function to translate links with different syntax to Org syntax.
1850 This can be used to translate links created for example by the Planner
1851 or emacs-wiki packages to Org syntax.
1852 The function must accept two parameters, a TYPE containing the link
1853 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1854 which is everything after the link protocol. It should return a cons
1855 with possibly modified values of type and path.
1856 Org contains a function for this, so if you set this variable to
1857 `org-translate-link-from-planner', you should be able follow many
1858 links created by planner."
1859 :group 'org-link-follow
1860 :type '(choice (const nil) (function)))
1862 (defcustom org-follow-link-hook nil
1863 "Hook that is run after a link has been followed."
1864 :group 'org-link-follow
1865 :type 'hook)
1867 (defcustom org-tab-follows-link nil
1868 "Non-nil means on links TAB will follow the link.
1869 Needs to be set before org.el is loaded.
1870 This really should not be used, it does not make sense, and the
1871 implementation is bad."
1872 :group 'org-link-follow
1873 :type 'boolean)
1875 (defcustom org-return-follows-link nil
1876 "Non-nil means on links RET will follow the link.
1877 In tables, the special behavior of RET has precedence."
1878 :group 'org-link-follow
1879 :type 'boolean)
1881 (defcustom org-mouse-1-follows-link
1882 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1883 "Non-nil means mouse-1 on a link will follow the link.
1884 A longer mouse click will still set point. Does not work on XEmacs.
1885 Needs to be set before org.el is loaded."
1886 :group 'org-link-follow
1887 :version "24.4"
1888 :package-version '(Org . "8.3")
1889 :type '(choice
1890 (const :tag "A double click follows the link" double)
1891 (const :tag "Unconditionally follow the link with mouse-1" t)
1892 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1894 (defcustom org-mark-ring-length 4
1895 "Number of different positions to be recorded in the ring.
1896 Changing this requires a restart of Emacs to work correctly."
1897 :group 'org-link-follow
1898 :type 'integer)
1900 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1901 "Non-nil means internal links in Org files must exactly match a headline.
1902 When nil, the link search tries to match a phrase with all words
1903 in the search text."
1904 :group 'org-link-follow
1905 :version "24.1"
1906 :type '(choice
1907 (const :tag "Use fuzzy text search" nil)
1908 (const :tag "Match only exact headline" t)
1909 (const :tag "Match exact headline or query to create it"
1910 query-to-create)))
1912 (defcustom org-link-frame-setup
1913 '((vm . vm-visit-folder-other-frame)
1914 (vm-imap . vm-visit-imap-folder-other-frame)
1915 (gnus . org-gnus-no-new-news)
1916 (file . find-file-other-window)
1917 (wl . wl-other-frame))
1918 "Setup the frame configuration for following links.
1919 When following a link with Emacs, it may often be useful to display
1920 this link in another window or frame. This variable can be used to
1921 set this up for the different types of links.
1922 For VM, use any of
1923 `vm-visit-folder'
1924 `vm-visit-folder-other-window'
1925 `vm-visit-folder-other-frame'
1926 For Gnus, use any of
1927 `gnus'
1928 `gnus-other-frame'
1929 `org-gnus-no-new-news'
1930 For FILE, use any of
1931 `find-file'
1932 `find-file-other-window'
1933 `find-file-other-frame'
1934 For Wanderlust use any of
1935 `wl'
1936 `wl-other-frame'
1937 For the calendar, use the variable `calendar-setup'.
1938 For BBDB, it is currently only possible to display the matches in
1939 another window."
1940 :group 'org-link-follow
1941 :type '(list
1942 (cons (const vm)
1943 (choice
1944 (const vm-visit-folder)
1945 (const vm-visit-folder-other-window)
1946 (const vm-visit-folder-other-frame)))
1947 (cons (const vm-imap)
1948 (choice
1949 (const vm-visit-imap-folder)
1950 (const vm-visit-imap-folder-other-window)
1951 (const vm-visit-imap-folder-other-frame)))
1952 (cons (const gnus)
1953 (choice
1954 (const gnus)
1955 (const gnus-other-frame)
1956 (const org-gnus-no-new-news)))
1957 (cons (const file)
1958 (choice
1959 (const find-file)
1960 (const find-file-other-window)
1961 (const find-file-other-frame)))
1962 (cons (const wl)
1963 (choice
1964 (const wl)
1965 (const wl-other-frame)))))
1967 (defcustom org-display-internal-link-with-indirect-buffer nil
1968 "Non-nil means use indirect buffer to display infile links.
1969 Activating internal links (from one location in a file to another location
1970 in the same file) normally just jumps to the location. When the link is
1971 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1972 is displayed in
1973 another window. When this option is set, the other window actually displays
1974 an indirect buffer clone of the current buffer, to avoid any visibility
1975 changes to the current buffer."
1976 :group 'org-link-follow
1977 :type 'boolean)
1979 (defcustom org-open-non-existing-files nil
1980 "Non-nil means `org-open-file' will open non-existing files.
1981 When nil, an error will be generated.
1982 This variable applies only to external applications because they
1983 might choke on non-existing files. If the link is to a file that
1984 will be opened in Emacs, the variable is ignored."
1985 :group 'org-link-follow
1986 :type 'boolean)
1988 (defcustom org-open-directory-means-index-dot-org nil
1989 "Non-nil means a link to a directory really means to index.org.
1990 When nil, following a directory link will run dired or open a finder/explorer
1991 window on that directory."
1992 :group 'org-link-follow
1993 :type 'boolean)
1995 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1996 "Non-nil means ask for confirmation before executing shell links.
1997 Shell links can be dangerous: just think about a link
1999 [[shell:rm -rf ~/*][Google Search]]
2001 This link would show up in your Org-mode document as \"Google Search\",
2002 but really it would remove your entire home directory.
2003 Therefore we advise against setting this variable to nil.
2004 Just change it to `y-or-n-p' if you want to confirm with a
2005 single keystroke rather than having to type \"yes\"."
2006 :group 'org-link-follow
2007 :type '(choice
2008 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2009 (const :tag "with y-or-n (faster)" y-or-n-p)
2010 (const :tag "no confirmation (dangerous)" nil)))
2011 (put 'org-confirm-shell-link-function
2012 'safe-local-variable
2013 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2015 (defcustom org-confirm-shell-link-not-regexp ""
2016 "A regexp to skip confirmation for shell links."
2017 :group 'org-link-follow
2018 :version "24.1"
2019 :type 'regexp)
2021 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2022 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2023 Elisp links can be dangerous: just think about a link
2025 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2027 This link would show up in your Org-mode document as \"Google Search\",
2028 but really it would remove your entire home directory.
2029 Therefore we advise against setting this variable to nil.
2030 Just change it to `y-or-n-p' if you want to confirm with a
2031 single keystroke rather than having to type \"yes\"."
2032 :group 'org-link-follow
2033 :type '(choice
2034 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2035 (const :tag "with y-or-n (faster)" y-or-n-p)
2036 (const :tag "no confirmation (dangerous)" nil)))
2037 (put 'org-confirm-shell-link-function
2038 'safe-local-variable
2039 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2041 (defcustom org-confirm-elisp-link-not-regexp ""
2042 "A regexp to skip confirmation for Elisp links."
2043 :group 'org-link-follow
2044 :version "24.1"
2045 :type 'regexp)
2047 (defconst org-file-apps-defaults-gnu
2048 '((remote . emacs)
2049 (system . mailcap)
2050 (t . mailcap))
2051 "Default file applications on a UNIX or GNU/Linux system.
2052 See `org-file-apps'.")
2054 (defconst org-file-apps-defaults-macosx
2055 '((remote . emacs)
2056 (t . "open %s")
2057 (system . "open %s")
2058 ("ps.gz" . "gv %s")
2059 ("eps.gz" . "gv %s")
2060 ("dvi" . "xdvi %s")
2061 ("fig" . "xfig %s"))
2062 "Default file applications on a MacOS X system.
2063 The system \"open\" is known as a default, but we use X11 applications
2064 for some files for which the OS does not have a good default.
2065 See `org-file-apps'.")
2067 (defconst org-file-apps-defaults-windowsnt
2068 (list
2069 '(remote . emacs)
2070 (cons t
2071 (list (if (featurep 'xemacs)
2072 'mswindows-shell-execute
2073 'w32-shell-execute)
2074 "open" 'file))
2075 (cons 'system
2076 (list (if (featurep 'xemacs)
2077 'mswindows-shell-execute
2078 'w32-shell-execute)
2079 "open" 'file)))
2080 "Default file applications on a Windows NT system.
2081 The system \"open\" is used for most files.
2082 See `org-file-apps'.")
2084 (defcustom org-file-apps
2085 '((auto-mode . emacs)
2086 ("\\.mm\\'" . default)
2087 ("\\.x?html?\\'" . default)
2088 ("\\.pdf\\'" . default))
2089 "External applications for opening `file:path' items in a document.
2090 Org-mode uses system defaults for different file types, but
2091 you can use this variable to set the application for a given file
2092 extension. The entries in this list are cons cells where the car identifies
2093 files and the cdr the corresponding command. Possible values for the
2094 file identifier are
2095 \"string\" A string as a file identifier can be interpreted in different
2096 ways, depending on its contents:
2098 - Alphanumeric characters only:
2099 Match links with this file extension.
2100 Example: (\"pdf\" . \"evince %s\")
2101 to open PDFs with evince.
2103 - Regular expression: Match links where the
2104 filename matches the regexp. If you want to
2105 use groups here, use shy groups.
2107 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2108 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2109 to open *.html and *.xhtml with firefox.
2111 - Regular expression which contains (non-shy) groups:
2112 Match links where the whole link, including \"::\", and
2113 anything after that, matches the regexp.
2114 In a custom command string, %1, %2, etc. are replaced with
2115 the parts of the link that were matched by the groups.
2116 For backwards compatibility, if a command string is given
2117 that does not use any of the group matches, this case is
2118 handled identically to the second one (i.e. match against
2119 file name only).
2120 In a custom lisp form, you can access the group matches with
2121 (match-string n link).
2123 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2124 to open [[file:document.pdf::5]] with evince at page 5.
2126 `directory' Matches a directory
2127 `remote' Matches a remote file, accessible through tramp or efs.
2128 Remote files most likely should be visited through Emacs
2129 because external applications cannot handle such paths.
2130 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2131 so all files Emacs knows how to handle. Using this with
2132 command `emacs' will open most files in Emacs. Beware that this
2133 will also open html files inside Emacs, unless you add
2134 (\"html\" . default) to the list as well.
2135 t Default for files not matched by any of the other options.
2136 `system' The system command to open files, like `open' on Windows
2137 and Mac OS X, and mailcap under GNU/Linux. This is the command
2138 that will be selected if you call `C-c C-o' with a double
2139 \\[universal-argument] \\[universal-argument] prefix.
2141 Possible values for the command are:
2142 `emacs' The file will be visited by the current Emacs process.
2143 `default' Use the default application for this file type, which is the
2144 association for t in the list, most likely in the system-specific
2145 part.
2146 This can be used to overrule an unwanted setting in the
2147 system-specific variable.
2148 `system' Use the system command for opening files, like \"open\".
2149 This command is specified by the entry whose car is `system'.
2150 Most likely, the system-specific version of this variable
2151 does define this command, but you can overrule/replace it
2152 here.
2153 string A command to be executed by a shell; %s will be replaced
2154 by the path to the file.
2155 sexp A Lisp form which will be evaluated. The file path will
2156 be available in the Lisp variable `file'.
2157 For more examples, see the system specific constants
2158 `org-file-apps-defaults-macosx'
2159 `org-file-apps-defaults-windowsnt'
2160 `org-file-apps-defaults-gnu'."
2161 :group 'org-link-follow
2162 :type '(repeat
2163 (cons (choice :value ""
2164 (string :tag "Extension")
2165 (const :tag "System command to open files" system)
2166 (const :tag "Default for unrecognized files" t)
2167 (const :tag "Remote file" remote)
2168 (const :tag "Links to a directory" directory)
2169 (const :tag "Any files that have Emacs modes"
2170 auto-mode))
2171 (choice :value ""
2172 (const :tag "Visit with Emacs" emacs)
2173 (const :tag "Use default" default)
2174 (const :tag "Use the system command" system)
2175 (string :tag "Command")
2176 (sexp :tag "Lisp form")))))
2178 (defcustom org-doi-server-url "http://dx.doi.org/"
2179 "The URL of the DOI server."
2180 :type 'string
2181 :version "24.3"
2182 :group 'org-link-follow)
2184 (defgroup org-refile nil
2185 "Options concerning refiling entries in Org-mode."
2186 :tag "Org Refile"
2187 :group 'org)
2189 (defcustom org-directory "~/org"
2190 "Directory with org files.
2191 This is just a default location to look for Org files. There is no need
2192 at all to put your files into this directory. It is only used in the
2193 following situations:
2195 1. When a capture template specifies a target file that is not an
2196 absolute path. The path will then be interpreted relative to
2197 `org-directory'
2198 2. When a capture note is filed away in an interactive way (when exiting the
2199 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2200 with `org-directory' as the default path."
2201 :group 'org-refile
2202 :group 'org-capture
2203 :type 'directory)
2205 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2206 "Default target for storing notes.
2207 Used as a fall back file for org-capture.el, for templates that
2208 do not specify a target file."
2209 :group 'org-refile
2210 :group 'org-capture
2211 :type '(choice
2212 (const :tag "Default from remember-data-file" nil)
2213 file))
2215 (defcustom org-goto-interface 'outline
2216 "The default interface to be used for `org-goto'.
2217 Allowed values are:
2218 outline The interface shows an outline of the relevant file
2219 and the correct heading is found by moving through
2220 the outline or by searching with incremental search.
2221 outline-path-completion Headlines in the current buffer are offered via
2222 completion. This is the interface also used by
2223 the refile command."
2224 :group 'org-refile
2225 :type '(choice
2226 (const :tag "Outline" outline)
2227 (const :tag "Outline-path-completion" outline-path-completion)))
2229 (defcustom org-goto-max-level 5
2230 "Maximum target level when running `org-goto' with refile interface."
2231 :group 'org-refile
2232 :type 'integer)
2234 (defcustom org-reverse-note-order nil
2235 "Non-nil means store new notes at the beginning of a file or entry.
2236 When nil, new notes will be filed to the end of a file or entry.
2237 This can also be a list with cons cells of regular expressions that
2238 are matched against file names, and values."
2239 :group 'org-capture
2240 :group 'org-refile
2241 :type '(choice
2242 (const :tag "Reverse always" t)
2243 (const :tag "Reverse never" nil)
2244 (repeat :tag "By file name regexp"
2245 (cons regexp boolean))))
2247 (defcustom org-log-refile nil
2248 "Information to record when a task is refiled.
2250 Possible values are:
2252 nil Don't add anything
2253 time Add a time stamp to the task
2254 note Prompt for a note and add it with template `org-log-note-headings'
2256 This option can also be set with on a per-file-basis with
2258 #+STARTUP: nologrefile
2259 #+STARTUP: logrefile
2260 #+STARTUP: lognoterefile
2262 You can have local logging settings for a subtree by setting the LOGGING
2263 property to one or more of these keywords.
2265 When bulk-refiling from the agenda, the value `note' is forbidden and
2266 will temporarily be changed to `time'."
2267 :group 'org-refile
2268 :group 'org-progress
2269 :version "24.1"
2270 :type '(choice
2271 (const :tag "No logging" nil)
2272 (const :tag "Record timestamp" time)
2273 (const :tag "Record timestamp with note." note)))
2275 (defcustom org-refile-targets nil
2276 "Targets for refiling entries with \\[org-refile].
2277 This is a list of cons cells. Each cell contains:
2278 - a specification of the files to be considered, either a list of files,
2279 or a symbol whose function or variable value will be used to retrieve
2280 a file name or a list of file names. If you use `org-agenda-files' for
2281 that, all agenda files will be scanned for targets. Nil means consider
2282 headings in the current buffer.
2283 - A specification of how to find candidate refile targets. This may be
2284 any of:
2285 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2286 This tag has to be present in all target headlines, inheritance will
2287 not be considered.
2288 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2289 todo keyword.
2290 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2291 headlines that are refiling targets.
2292 - a cons cell (:level . N). Any headline of level N is considered a target.
2293 Note that, when `org-odd-levels-only' is set, level corresponds to
2294 order in hierarchy, not to the number of stars.
2295 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2296 Note that, when `org-odd-levels-only' is set, level corresponds to
2297 order in hierarchy, not to the number of stars.
2299 Each element of this list generates a set of possible targets.
2300 The union of these sets is presented (with completion) to
2301 the user by `org-refile'.
2303 You can set the variable `org-refile-target-verify-function' to a function
2304 to verify each headline found by the simple criteria above.
2306 When this variable is nil, all top-level headlines in the current buffer
2307 are used, equivalent to the value `((nil . (:level . 1))'."
2308 :group 'org-refile
2309 :type '(repeat
2310 (cons
2311 (choice :value org-agenda-files
2312 (const :tag "All agenda files" org-agenda-files)
2313 (const :tag "Current buffer" nil)
2314 (function) (variable) (file))
2315 (choice :tag "Identify target headline by"
2316 (cons :tag "Specific tag" (const :value :tag) (string))
2317 (cons :tag "TODO keyword" (const :value :todo) (string))
2318 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2319 (cons :tag "Level number" (const :value :level) (integer))
2320 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2322 (defcustom org-refile-target-verify-function nil
2323 "Function to verify if the headline at point should be a refile target.
2324 The function will be called without arguments, with point at the
2325 beginning of the headline. It should return t and leave point
2326 where it is if the headline is a valid target for refiling.
2328 If the target should not be selected, the function must return nil.
2329 In addition to this, it may move point to a place from where the search
2330 should be continued. For example, the function may decide that the entire
2331 subtree of the current entry should be excluded and move point to the end
2332 of the subtree."
2333 :group 'org-refile
2334 :type '(choice
2335 (const nil)
2336 (function)))
2338 (defcustom org-refile-use-cache nil
2339 "Non-nil means cache refile targets to speed up the process.
2340 The cache for a particular file will be updated automatically when
2341 the buffer has been killed, or when any of the marker used for flagging
2342 refile targets no longer points at a live buffer.
2343 If you have added new entries to a buffer that might themselves be targets,
2344 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2345 find that easier, `C-u C-u C-u C-c C-w'."
2346 :group 'org-refile
2347 :version "24.1"
2348 :type 'boolean)
2350 (defcustom org-refile-use-outline-path nil
2351 "Non-nil means provide refile targets as paths.
2352 So a level 3 headline will be available as level1/level2/level3.
2354 When the value is `file', also include the file name (without directory)
2355 into the path. In this case, you can also stop the completion after
2356 the file name, to get entries inserted as top level in the file.
2358 When `full-file-path', include the full file path."
2359 :group 'org-refile
2360 :type '(choice
2361 (const :tag "Not" nil)
2362 (const :tag "Yes" t)
2363 (const :tag "Start with file name" file)
2364 (const :tag "Start with full file path" full-file-path)))
2366 (defcustom org-outline-path-complete-in-steps t
2367 "Non-nil means complete the outline path in hierarchical steps.
2368 When Org-mode uses the refile interface to select an outline path
2369 \(see variable `org-refile-use-outline-path'), the completion of
2370 the path can be done is a single go, or if can be done in steps down
2371 the headline hierarchy. Going in steps is probably the best if you
2372 do not use a special completion package like `ido' or `icicles'.
2373 However, when using these packages, going in one step can be very
2374 fast, while still showing the whole path to the entry."
2375 :group 'org-refile
2376 :type 'boolean)
2378 (defcustom org-refile-allow-creating-parent-nodes nil
2379 "Non-nil means allow to create new nodes as refile targets.
2380 New nodes are then created by adding \"/new node name\" to the completion
2381 of an existing node. When the value of this variable is `confirm',
2382 new node creation must be confirmed by the user (recommended).
2383 When nil, the completion must match an existing entry.
2385 Note that, if the new heading is not seen by the criteria
2386 listed in `org-refile-targets', multiple instances of the same
2387 heading would be created by trying again to file under the new
2388 heading."
2389 :group 'org-refile
2390 :type '(choice
2391 (const :tag "Never" nil)
2392 (const :tag "Always" t)
2393 (const :tag "Prompt for confirmation" confirm)))
2395 (defcustom org-refile-active-region-within-subtree nil
2396 "Non-nil means also refile active region within a subtree.
2398 By default `org-refile' doesn't allow refiling regions if they
2399 don't contain a set of subtrees, but it might be convenient to
2400 do so sometimes: in that case, the first line of the region is
2401 converted to a headline before refiling."
2402 :group 'org-refile
2403 :version "24.1"
2404 :type 'boolean)
2406 (defgroup org-todo nil
2407 "Options concerning TODO items in Org-mode."
2408 :tag "Org TODO"
2409 :group 'org)
2411 (defgroup org-progress nil
2412 "Options concerning Progress logging in Org-mode."
2413 :tag "Org Progress"
2414 :group 'org-time)
2416 (defvar org-todo-interpretation-widgets
2417 '((:tag "Sequence (cycling hits every state)" sequence)
2418 (:tag "Type (cycling directly to DONE)" type))
2419 "The available interpretation symbols for customizing `org-todo-keywords'.
2420 Interested libraries should add to this list.")
2422 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2423 "List of TODO entry keyword sequences and their interpretation.
2424 \\<org-mode-map>This is a list of sequences.
2426 Each sequence starts with a symbol, either `sequence' or `type',
2427 indicating if the keywords should be interpreted as a sequence of
2428 action steps, or as different types of TODO items. The first
2429 keywords are states requiring action - these states will select a headline
2430 for inclusion into the global TODO list Org-mode produces. If one of
2431 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2432 signify that no further action is necessary. If \"|\" is not found,
2433 the last keyword is treated as the only DONE state of the sequence.
2435 The command \\[org-todo] cycles an entry through these states, and one
2436 additional state where no keyword is present. For details about this
2437 cycling, see the manual.
2439 TODO keywords and interpretation can also be set on a per-file basis with
2440 the special #+SEQ_TODO and #+TYP_TODO lines.
2442 Each keyword can optionally specify a character for fast state selection
2443 \(in combination with the variable `org-use-fast-todo-selection')
2444 and specifiers for state change logging, using the same syntax that
2445 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2446 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2447 indicates to record a time stamp each time this state is selected.
2449 Each keyword may also specify if a timestamp or a note should be
2450 recorded when entering or leaving the state, by adding additional
2451 characters in the parenthesis after the keyword. This looks like this:
2452 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2453 record only the time of the state change. With X and Y being either
2454 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2455 Y when leaving the state if and only if the *target* state does not
2456 define X. You may omit any of the fast-selection key or X or /Y,
2457 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2459 For backward compatibility, this variable may also be just a list
2460 of keywords. In this case the interpretation (sequence or type) will be
2461 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2462 :group 'org-todo
2463 :group 'org-keywords
2464 :type '(choice
2465 (repeat :tag "Old syntax, just keywords"
2466 (string :tag "Keyword"))
2467 (repeat :tag "New syntax"
2468 (cons
2469 (choice
2470 :tag "Interpretation"
2471 ;;Quick and dirty way to see
2472 ;;`org-todo-interpretations'. This takes the
2473 ;;place of item arguments
2474 :convert-widget
2475 (lambda (widget)
2476 (widget-put widget
2477 :args (mapcar
2478 #'(lambda (x)
2479 (widget-convert
2480 (cons 'const x)))
2481 org-todo-interpretation-widgets))
2482 widget))
2483 (repeat
2484 (string :tag "Keyword"))))))
2486 (defvar org-todo-keywords-1 nil
2487 "All TODO and DONE keywords active in a buffer.")
2488 (make-variable-buffer-local 'org-todo-keywords-1)
2489 (defvar org-todo-keywords-for-agenda nil)
2490 (defvar org-done-keywords-for-agenda nil)
2491 (defvar org-todo-keyword-alist-for-agenda nil)
2492 (defvar org-tag-alist-for-agenda nil
2493 "Alist of all tags from all agenda files.")
2494 (defvar org-tag-groups-alist-for-agenda nil
2495 "Alist of all groups tags from all current agenda files.")
2496 (defvar org-tag-groups-alist nil)
2497 (make-variable-buffer-local 'org-tag-groups-alist)
2498 (defvar org-agenda-contributing-files nil)
2499 (defvar org-not-done-keywords nil)
2500 (make-variable-buffer-local 'org-not-done-keywords)
2501 (defvar org-done-keywords nil)
2502 (make-variable-buffer-local 'org-done-keywords)
2503 (defvar org-todo-heads nil)
2504 (make-variable-buffer-local 'org-todo-heads)
2505 (defvar org-todo-sets nil)
2506 (make-variable-buffer-local 'org-todo-sets)
2507 (defvar org-todo-log-states nil)
2508 (make-variable-buffer-local 'org-todo-log-states)
2509 (defvar org-todo-kwd-alist nil)
2510 (make-variable-buffer-local 'org-todo-kwd-alist)
2511 (defvar org-todo-key-alist nil)
2512 (make-variable-buffer-local 'org-todo-key-alist)
2513 (defvar org-todo-key-trigger nil)
2514 (make-variable-buffer-local 'org-todo-key-trigger)
2516 (defcustom org-todo-interpretation 'sequence
2517 "Controls how TODO keywords are interpreted.
2518 This variable is in principle obsolete and is only used for
2519 backward compatibility, if the interpretation of todo keywords is
2520 not given already in `org-todo-keywords'. See that variable for
2521 more information."
2522 :group 'org-todo
2523 :group 'org-keywords
2524 :type '(choice (const sequence)
2525 (const type)))
2527 (defcustom org-use-fast-todo-selection t
2528 "Non-nil means use the fast todo selection scheme with C-c C-t.
2529 This variable describes if and under what circumstances the cycling
2530 mechanism for TODO keywords will be replaced by a single-key, direct
2531 selection scheme.
2533 When nil, fast selection is never used.
2535 When the symbol `prefix', it will be used when `org-todo' is called
2536 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2537 `C-u t' in an agenda buffer.
2539 When t, fast selection is used by default. In this case, the prefix
2540 argument forces cycling instead.
2542 In all cases, the special interface is only used if access keys have
2543 actually been assigned by the user, i.e. if keywords in the configuration
2544 are followed by a letter in parenthesis, like TODO(t)."
2545 :group 'org-todo
2546 :type '(choice
2547 (const :tag "Never" nil)
2548 (const :tag "By default" t)
2549 (const :tag "Only with C-u C-c C-t" prefix)))
2551 (defcustom org-provide-todo-statistics t
2552 "Non-nil means update todo statistics after insert and toggle.
2553 ALL-HEADLINES means update todo statistics by including headlines
2554 with no TODO keyword as well, counting them as not done.
2555 A list of TODO keywords means the same, but skip keywords that are
2556 not in this list.
2557 When set to a list of two lists, the first list contains keywords
2558 to consider as TODO keywords, the second list contains keywords
2559 to consider as DONE keywords.
2561 When this is set, todo statistics is updated in the parent of the
2562 current entry each time a todo state is changed."
2563 :group 'org-todo
2564 :type '(choice
2565 (const :tag "Yes, only for TODO entries" t)
2566 (const :tag "Yes, including all entries" all-headlines)
2567 (repeat :tag "Yes, for TODOs in this list"
2568 (string :tag "TODO keyword"))
2569 (list :tag "Yes, for TODOs and DONEs in these lists"
2570 (repeat (string :tag "TODO keyword"))
2571 (repeat (string :tag "DONE keyword")))
2572 (other :tag "No TODO statistics" nil)))
2574 (defcustom org-hierarchical-todo-statistics t
2575 "Non-nil means TODO statistics covers just direct children.
2576 When nil, all entries in the subtree are considered.
2577 This has only an effect if `org-provide-todo-statistics' is set.
2578 To set this to nil for only a single subtree, use a COOKIE_DATA
2579 property and include the word \"recursive\" into the value."
2580 :group 'org-todo
2581 :type 'boolean)
2583 (defcustom org-after-todo-state-change-hook nil
2584 "Hook which is run after the state of a TODO item was changed.
2585 The new state (a string with a TODO keyword, or nil) is available in the
2586 Lisp variable `org-state'."
2587 :group 'org-todo
2588 :type 'hook)
2590 (defvar org-blocker-hook nil
2591 "Hook for functions that are allowed to block a state change.
2593 Functions in this hook should not modify the buffer.
2594 Each function gets as its single argument a property list,
2595 see `org-trigger-hook' for more information about this list.
2597 If any of the functions in this hook returns nil, the state change
2598 is blocked.")
2600 (defvar org-trigger-hook nil
2601 "Hook for functions that are triggered by a state change.
2603 Each function gets as its single argument a property list with at
2604 least the following elements:
2606 (:type type-of-change :position pos-at-entry-start
2607 :from old-state :to new-state)
2609 Depending on the type, more properties may be present.
2611 This mechanism is currently implemented for:
2613 TODO state changes
2614 ------------------
2615 :type todo-state-change
2616 :from previous state (keyword as a string), or nil, or a symbol
2617 'todo' or 'done', to indicate the general type of state.
2618 :to new state, like in :from")
2620 (defcustom org-enforce-todo-dependencies nil
2621 "Non-nil means undone TODO entries will block switching the parent to DONE.
2622 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2623 be blocked if any prior sibling is not yet done.
2624 Finally, if the parent is blocked because of ordered siblings of its own,
2625 the child will also be blocked."
2626 :set (lambda (var val)
2627 (set var val)
2628 (if val
2629 (add-hook 'org-blocker-hook
2630 'org-block-todo-from-children-or-siblings-or-parent)
2631 (remove-hook 'org-blocker-hook
2632 'org-block-todo-from-children-or-siblings-or-parent)))
2633 :group 'org-todo
2634 :type 'boolean)
2636 (defcustom org-enforce-todo-checkbox-dependencies nil
2637 "Non-nil means unchecked boxes will block switching the parent to DONE.
2638 When this is nil, checkboxes have no influence on switching TODO states.
2639 When non-nil, you first need to check off all check boxes before the TODO
2640 entry can be switched to DONE.
2641 This variable needs to be set before org.el is loaded, and you need to
2642 restart Emacs after a change to make the change effective. The only way
2643 to change is while Emacs is running is through the customize interface."
2644 :set (lambda (var val)
2645 (set var val)
2646 (if val
2647 (add-hook 'org-blocker-hook
2648 'org-block-todo-from-checkboxes)
2649 (remove-hook 'org-blocker-hook
2650 'org-block-todo-from-checkboxes)))
2651 :group 'org-todo
2652 :type 'boolean)
2654 (defcustom org-treat-insert-todo-heading-as-state-change nil
2655 "Non-nil means inserting a TODO heading is treated as state change.
2656 So when the command \\[org-insert-todo-heading] is used, state change
2657 logging will apply if appropriate. When nil, the new TODO item will
2658 be inserted directly, and no logging will take place."
2659 :group 'org-todo
2660 :type 'boolean)
2662 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2663 "Non-nil means switching TODO states with S-cursor counts as state change.
2664 This is the default behavior. However, setting this to nil allows a
2665 convenient way to select a TODO state and bypass any logging associated
2666 with that."
2667 :group 'org-todo
2668 :type 'boolean)
2670 (defcustom org-todo-state-tags-triggers nil
2671 "Tag changes that should be triggered by TODO state changes.
2672 This is a list. Each entry is
2674 (state-change (tag . flag) .......)
2676 State-change can be a string with a state, and empty string to indicate the
2677 state that has no TODO keyword, or it can be one of the symbols `todo'
2678 or `done', meaning any not-done or done state, respectively."
2679 :group 'org-todo
2680 :group 'org-tags
2681 :type '(repeat
2682 (cons (choice :tag "When changing to"
2683 (const :tag "Not-done state" todo)
2684 (const :tag "Done state" done)
2685 (string :tag "State"))
2686 (repeat
2687 (cons :tag "Tag action"
2688 (string :tag "Tag")
2689 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2691 (defcustom org-log-done nil
2692 "Information to record when a task moves to the DONE state.
2694 Possible values are:
2696 nil Don't add anything, just change the keyword
2697 time Add a time stamp to the task
2698 note Prompt for a note and add it with template `org-log-note-headings'
2700 This option can also be set with on a per-file-basis with
2702 #+STARTUP: nologdone
2703 #+STARTUP: logdone
2704 #+STARTUP: lognotedone
2706 You can have local logging settings for a subtree by setting the LOGGING
2707 property to one or more of these keywords."
2708 :group 'org-todo
2709 :group 'org-progress
2710 :type '(choice
2711 (const :tag "No logging" nil)
2712 (const :tag "Record CLOSED timestamp" time)
2713 (const :tag "Record CLOSED timestamp with note." note)))
2715 ;; Normalize old uses of org-log-done.
2716 (cond
2717 ((eq org-log-done t) (setq org-log-done 'time))
2718 ((and (listp org-log-done) (memq 'done org-log-done))
2719 (setq org-log-done 'note)))
2721 (defcustom org-log-reschedule nil
2722 "Information to record when the scheduling date of a tasks is modified.
2724 Possible values are:
2726 nil Don't add anything, just change the date
2727 time Add a time stamp to the task
2728 note Prompt for a note and add it with template `org-log-note-headings'
2730 This option can also be set with on a per-file-basis with
2732 #+STARTUP: nologreschedule
2733 #+STARTUP: logreschedule
2734 #+STARTUP: lognotereschedule"
2735 :group 'org-todo
2736 :group 'org-progress
2737 :type '(choice
2738 (const :tag "No logging" nil)
2739 (const :tag "Record timestamp" time)
2740 (const :tag "Record timestamp with note." note)))
2742 (defcustom org-log-redeadline nil
2743 "Information to record when the deadline date of a tasks is modified.
2745 Possible values are:
2747 nil Don't add anything, just change the date
2748 time Add a time stamp to the task
2749 note Prompt for a note and add it with template `org-log-note-headings'
2751 This option can also be set with on a per-file-basis with
2753 #+STARTUP: nologredeadline
2754 #+STARTUP: logredeadline
2755 #+STARTUP: lognoteredeadline
2757 You can have local logging settings for a subtree by setting the LOGGING
2758 property to one or more of these keywords."
2759 :group 'org-todo
2760 :group 'org-progress
2761 :type '(choice
2762 (const :tag "No logging" nil)
2763 (const :tag "Record timestamp" time)
2764 (const :tag "Record timestamp with note." note)))
2766 (defcustom org-log-note-clock-out nil
2767 "Non-nil means record a note when clocking out of an item.
2768 This can also be configured on a per-file basis by adding one of
2769 the following lines anywhere in the buffer:
2771 #+STARTUP: lognoteclock-out
2772 #+STARTUP: nolognoteclock-out"
2773 :group 'org-todo
2774 :group 'org-progress
2775 :type 'boolean)
2777 (defcustom org-log-done-with-time t
2778 "Non-nil means the CLOSED time stamp will contain date and time.
2779 When nil, only the date will be recorded."
2780 :group 'org-progress
2781 :type 'boolean)
2783 (defcustom org-log-note-headings
2784 '((done . "CLOSING NOTE %t")
2785 (state . "State %-12s from %-12S %t")
2786 (note . "Note taken on %t")
2787 (reschedule . "Rescheduled from %S on %t")
2788 (delschedule . "Not scheduled, was %S on %t")
2789 (redeadline . "New deadline from %S on %t")
2790 (deldeadline . "Removed deadline, was %S on %t")
2791 (refile . "Refiled on %t")
2792 (clock-out . ""))
2793 "Headings for notes added to entries.
2794 The value is an alist, with the car being a symbol indicating the note
2795 context, and the cdr is the heading to be used. The heading may also be the
2796 empty string.
2797 %t in the heading will be replaced by a time stamp.
2798 %T will be an active time stamp instead the default inactive one
2799 %d will be replaced by a short-format time stamp.
2800 %D will be replaced by an active short-format time stamp.
2801 %s will be replaced by the new TODO state, in double quotes.
2802 %S will be replaced by the old TODO state, in double quotes.
2803 %u will be replaced by the user name.
2804 %U will be replaced by the full user name.
2806 In fact, it is not a good idea to change the `state' entry, because
2807 agenda log mode depends on the format of these entries."
2808 :group 'org-todo
2809 :group 'org-progress
2810 :type '(list :greedy t
2811 (cons (const :tag "Heading when closing an item" done) string)
2812 (cons (const :tag
2813 "Heading when changing todo state (todo sequence only)"
2814 state) string)
2815 (cons (const :tag "Heading when just taking a note" note) string)
2816 (cons (const :tag "Heading when rescheduling" reschedule) string)
2817 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2818 (cons (const :tag "Heading when changing deadline" redeadline) string)
2819 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2820 (cons (const :tag "Heading when refiling" refile) string)
2821 (cons (const :tag "Heading when clocking out" clock-out) string)))
2823 (unless (assq 'note org-log-note-headings)
2824 (push '(note . "%t") org-log-note-headings))
2826 (defcustom org-log-into-drawer nil
2827 "Non-nil means insert state change notes and time stamps into a drawer.
2828 When nil, state changes notes will be inserted after the headline and
2829 any scheduling and clock lines, but not inside a drawer.
2831 The value of this variable should be the name of the drawer to use.
2832 LOGBOOK is proposed as the default drawer for this purpose, you can
2833 also set this to a string to define the drawer of your choice.
2835 A value of t is also allowed, representing \"LOGBOOK\".
2837 A value of t or nil can also be set with on a per-file-basis with
2839 #+STARTUP: logdrawer
2840 #+STARTUP: nologdrawer
2842 If this variable is set, `org-log-state-notes-insert-after-drawers'
2843 will be ignored.
2845 You can set the property LOG_INTO_DRAWER to overrule this setting for
2846 a subtree."
2847 :group 'org-todo
2848 :group 'org-progress
2849 :type '(choice
2850 (const :tag "Not into a drawer" nil)
2851 (const :tag "LOGBOOK" t)
2852 (string :tag "Other")))
2854 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2856 (defun org-log-into-drawer ()
2857 "Return the value of `org-log-into-drawer', but let properties overrule.
2858 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2859 used instead of the default value."
2860 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2861 (cond
2862 ((not p) org-log-into-drawer)
2863 ((equal p "nil") nil)
2864 ((equal p "t") "LOGBOOK")
2865 (t p))))
2867 (defcustom org-log-state-notes-insert-after-drawers nil
2868 "Non-nil means insert state change notes after any drawers in entry.
2869 Only the drawers that *immediately* follow the headline and the
2870 deadline/scheduled line are skipped.
2871 When nil, insert notes right after the heading and perhaps the line
2872 with deadline/scheduling if present.
2874 This variable will have no effect if `org-log-into-drawer' is
2875 set."
2876 :group 'org-todo
2877 :group 'org-progress
2878 :type 'boolean)
2880 (defcustom org-log-states-order-reversed t
2881 "Non-nil means the latest state note will be directly after heading.
2882 When nil, the state change notes will be ordered according to time.
2884 This option can also be set with on a per-file-basis with
2886 #+STARTUP: logstatesreversed
2887 #+STARTUP: nologstatesreversed"
2888 :group 'org-todo
2889 :group 'org-progress
2890 :type 'boolean)
2892 (defcustom org-todo-repeat-to-state nil
2893 "The TODO state to which a repeater should return the repeating task.
2894 By default this is the first task in a TODO sequence, or the previous state
2895 in a TODO_TYP set. But you can specify another task here.
2896 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2897 :group 'org-todo
2898 :version "24.1"
2899 :type '(choice (const :tag "Head of sequence" nil)
2900 (string :tag "Specific state")))
2902 (defcustom org-log-repeat 'time
2903 "Non-nil means record moving through the DONE state when triggering repeat.
2904 An auto-repeating task is immediately switched back to TODO when
2905 marked DONE. If you are not logging state changes (by adding \"@\"
2906 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2907 record a closing note, there will be no record of the task moving
2908 through DONE. This variable forces taking a note anyway.
2910 nil Don't force a record
2911 time Record a time stamp
2912 note Prompt for a note and add it with template `org-log-note-headings'
2914 This option can also be set with on a per-file-basis with
2916 #+STARTUP: nologrepeat
2917 #+STARTUP: logrepeat
2918 #+STARTUP: lognoterepeat
2920 You can have local logging settings for a subtree by setting the LOGGING
2921 property to one or more of these keywords."
2922 :group 'org-todo
2923 :group 'org-progress
2924 :type '(choice
2925 (const :tag "Don't force a record" nil)
2926 (const :tag "Force recording the DONE state" time)
2927 (const :tag "Force recording a note with the DONE state" note)))
2930 (defgroup org-priorities nil
2931 "Priorities in Org-mode."
2932 :tag "Org Priorities"
2933 :group 'org-todo)
2935 (defcustom org-enable-priority-commands t
2936 "Non-nil means priority commands are active.
2937 When nil, these commands will be disabled, so that you never accidentally
2938 set a priority."
2939 :group 'org-priorities
2940 :type 'boolean)
2942 (defcustom org-highest-priority ?A
2943 "The highest priority of TODO items. A character like ?A, ?B etc.
2944 Must have a smaller ASCII number than `org-lowest-priority'."
2945 :group 'org-priorities
2946 :type 'character)
2948 (defcustom org-lowest-priority ?C
2949 "The lowest priority of TODO items. A character like ?A, ?B etc.
2950 Must have a larger ASCII number than `org-highest-priority'."
2951 :group 'org-priorities
2952 :type 'character)
2954 (defcustom org-default-priority ?B
2955 "The default priority of TODO items.
2956 This is the priority an item gets if no explicit priority is given.
2957 When starting to cycle on an empty priority the first step in the cycle
2958 depends on `org-priority-start-cycle-with-default'. The resulting first
2959 step priority must not exceed the range from `org-highest-priority' to
2960 `org-lowest-priority' which means that `org-default-priority' has to be
2961 in this range exclusive or inclusive the range boundaries. Else the
2962 first step refuses to set the default and the second will fall back
2963 to (depending on the command used) the highest or lowest priority."
2964 :group 'org-priorities
2965 :type 'character)
2967 (defcustom org-priority-start-cycle-with-default t
2968 "Non-nil means start with default priority when starting to cycle.
2969 When this is nil, the first step in the cycle will be (depending on the
2970 command used) one higher or lower than the default priority.
2971 See also `org-default-priority'."
2972 :group 'org-priorities
2973 :type 'boolean)
2975 (defcustom org-get-priority-function nil
2976 "Function to extract the priority from a string.
2977 The string is normally the headline. If this is nil Org computes the
2978 priority from the priority cookie like [#A] in the headline. It returns
2979 an integer, increasing by 1000 for each priority level.
2980 The user can set a different function here, which should take a string
2981 as an argument and return the numeric priority."
2982 :group 'org-priorities
2983 :version "24.1"
2984 :type '(choice
2985 (const nil)
2986 (function)))
2988 (defgroup org-time nil
2989 "Options concerning time stamps and deadlines in Org-mode."
2990 :tag "Org Time"
2991 :group 'org)
2993 (defcustom org-insert-labeled-timestamps-at-point nil
2994 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2995 When nil, these labeled time stamps are forces into the second line of an
2996 entry, just after the headline. When scheduling from the global TODO list,
2997 the time stamp will always be forced into the second line."
2998 :group 'org-time
2999 :type 'boolean)
3001 (defcustom org-time-stamp-rounding-minutes '(0 5)
3002 "Number of minutes to round time stamps to.
3003 These are two values, the first applies when first creating a time stamp.
3004 The second applies when changing it with the commands `S-up' and `S-down'.
3005 When changing the time stamp, this means that it will change in steps
3006 of N minutes, as given by the second value.
3008 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3009 numbers should be factors of 60, so for example 5, 10, 15.
3011 When this is larger than 1, you can still force an exact time stamp by using
3012 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3013 and by using a prefix arg to `S-up/down' to specify the exact number
3014 of minutes to shift."
3015 :group 'org-time
3016 :get #'(lambda (var) ; Make sure both elements are there
3017 (if (integerp (default-value var))
3018 (list (default-value var) 5)
3019 (default-value var)))
3020 :type '(list
3021 (integer :tag "when inserting times")
3022 (integer :tag "when modifying times")))
3024 ;; Normalize old customizations of this variable.
3025 (when (integerp org-time-stamp-rounding-minutes)
3026 (setq org-time-stamp-rounding-minutes
3027 (list org-time-stamp-rounding-minutes
3028 org-time-stamp-rounding-minutes)))
3030 (defcustom org-display-custom-times nil
3031 "Non-nil means overlay custom formats over all time stamps.
3032 The formats are defined through the variable `org-time-stamp-custom-formats'.
3033 To turn this on on a per-file basis, insert anywhere in the file:
3034 #+STARTUP: customtime"
3035 :group 'org-time
3036 :set 'set-default
3037 :type 'sexp)
3038 (make-variable-buffer-local 'org-display-custom-times)
3040 (defcustom org-time-stamp-custom-formats
3041 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3042 "Custom formats for time stamps. See `format-time-string' for the syntax.
3043 These are overlaid over the default ISO format if the variable
3044 `org-display-custom-times' is set. Time like %H:%M should be at the
3045 end of the second format. The custom formats are also honored by export
3046 commands, if custom time display is turned on at the time of export."
3047 :group 'org-time
3048 :type 'sexp)
3050 (defun org-time-stamp-format (&optional long inactive)
3051 "Get the right format for a time string."
3052 (let ((f (if long (cdr org-time-stamp-formats)
3053 (car org-time-stamp-formats))))
3054 (if inactive
3055 (concat "[" (substring f 1 -1) "]")
3056 f)))
3058 (defcustom org-time-clocksum-format
3059 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3060 "The format string used when creating CLOCKSUM lines.
3061 This is also used when Org mode generates a time duration.
3063 The value can be a single format string containing two
3064 %-sequences, which will be filled with the number of hours and
3065 minutes in that order.
3067 Alternatively, the value can be a plist associating any of the
3068 keys :years, :months, :weeks, :days, :hours or :minutes with
3069 format strings. The time duration is formatted using only the
3070 time components that are needed and concatenating the results.
3071 If a time unit in absent, it falls back to the next smallest
3072 unit.
3074 The keys :require-years, :require-months, :require-days,
3075 :require-weeks, :require-hours, :require-minutes are also
3076 meaningful. A non-nil value for these keys indicates that the
3077 corresponding time component should always be included, even if
3078 its value is 0.
3081 For example,
3083 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3084 :require-minutes t)
3086 means durations longer than a day will be expressed in days,
3087 hours and minutes, and durations less than a day will always be
3088 expressed in hours and minutes (even for durations less than an
3089 hour).
3091 The value
3093 \(:days \"%dd\" :minutes \"%dm\")
3095 means durations longer than a day will be expressed in days and
3096 minutes, and durations less than a day will be expressed entirely
3097 in minutes (even for durations longer than an hour)."
3098 :group 'org-time
3099 :group 'org-clock
3100 :version "24.4"
3101 :package-version '(Org . "8.0")
3102 :type '(choice (string :tag "Format string")
3103 (set :tag "Plist"
3104 (group :inline t (const :tag "Years" :years)
3105 (string :tag "Format string"))
3106 (group :inline t
3107 (const :tag "Always show years" :require-years)
3108 (const t))
3109 (group :inline t (const :tag "Months" :months)
3110 (string :tag "Format string"))
3111 (group :inline t
3112 (const :tag "Always show months" :require-months)
3113 (const t))
3114 (group :inline t (const :tag "Weeks" :weeks)
3115 (string :tag "Format string"))
3116 (group :inline t
3117 (const :tag "Always show weeks" :require-weeks)
3118 (const t))
3119 (group :inline t (const :tag "Days" :days)
3120 (string :tag "Format string"))
3121 (group :inline t
3122 (const :tag "Always show days" :require-days)
3123 (const t))
3124 (group :inline t (const :tag "Hours" :hours)
3125 (string :tag "Format string"))
3126 (group :inline t
3127 (const :tag "Always show hours" :require-hours)
3128 (const t))
3129 (group :inline t (const :tag "Minutes" :minutes)
3130 (string :tag "Format string"))
3131 (group :inline t
3132 (const :tag "Always show minutes" :require-minutes)
3133 (const t)))))
3135 (defcustom org-time-clocksum-use-fractional nil
3136 "When non-nil, \\[org-clock-display] uses fractional times.
3137 See `org-time-clocksum-format' for more on time clock formats."
3138 :group 'org-time
3139 :group 'org-clock
3140 :version "24.3"
3141 :type 'boolean)
3143 (defcustom org-time-clocksum-use-effort-durations nil
3144 "When non-nil, \\[org-clock-display] uses effort durations.
3145 E.g. by default, one day is considered to be a 8 hours effort,
3146 so a task that has been clocked for 16 hours will be displayed
3147 as during 2 days in the clock display or in the clocktable.
3149 See `org-effort-durations' on how to set effort durations
3150 and `org-time-clocksum-format' for more on time clock formats."
3151 :group 'org-time
3152 :group 'org-clock
3153 :version "24.4"
3154 :package-version '(Org . "8.0")
3155 :type 'boolean)
3157 (defcustom org-time-clocksum-fractional-format "%.2f"
3158 "The format string used when creating CLOCKSUM lines,
3159 or when Org mode generates a time duration, if
3160 `org-time-clocksum-use-fractional' is enabled.
3162 The value can be a single format string containing one
3163 %-sequence, which will be filled with the number of hours as
3164 a float.
3166 Alternatively, the value can be a plist associating any of the
3167 keys :years, :months, :weeks, :days, :hours or :minutes with
3168 a format string. The time duration is formatted using the
3169 largest time unit which gives a non-zero integer part. If all
3170 specified formats have zero integer part, the smallest time unit
3171 is used."
3172 :group 'org-time
3173 :type '(choice (string :tag "Format string")
3174 (set (group :inline t (const :tag "Years" :years)
3175 (string :tag "Format string"))
3176 (group :inline t (const :tag "Months" :months)
3177 (string :tag "Format string"))
3178 (group :inline t (const :tag "Weeks" :weeks)
3179 (string :tag "Format string"))
3180 (group :inline t (const :tag "Days" :days)
3181 (string :tag "Format string"))
3182 (group :inline t (const :tag "Hours" :hours)
3183 (string :tag "Format string"))
3184 (group :inline t (const :tag "Minutes" :minutes)
3185 (string :tag "Format string")))))
3187 (defcustom org-deadline-warning-days 14
3188 "Number of days before expiration during which a deadline becomes active.
3189 This variable governs the display in sparse trees and in the agenda.
3190 When 0 or negative, it means use this number (the absolute value of it)
3191 even if a deadline has a different individual lead time specified.
3193 Custom commands can set this variable in the options section."
3194 :group 'org-time
3195 :group 'org-agenda-daily/weekly
3196 :type 'integer)
3198 (defcustom org-scheduled-delay-days 0
3199 "Number of days before a scheduled item becomes active.
3200 This variable governs the display in sparse trees and in the agenda.
3201 The default value (i.e. 0) means: don't delay scheduled item.
3202 When negative, it means use this number (the absolute value of it)
3203 even if a scheduled item has a different individual delay time
3204 specified.
3206 Custom commands can set this variable in the options section."
3207 :group 'org-time
3208 :group 'org-agenda-daily/weekly
3209 :version "24.4"
3210 :package-version '(Org . "8.0")
3211 :type 'integer)
3213 (defcustom org-read-date-prefer-future t
3214 "Non-nil means assume future for incomplete date input from user.
3215 This affects the following situations:
3216 1. The user gives a month but not a year.
3217 For example, if it is April and you enter \"feb 2\", this will be read
3218 as Feb 2, *next* year. \"May 5\", however, will be this year.
3219 2. The user gives a day, but no month.
3220 For example, if today is the 15th, and you enter \"3\", Org-mode will
3221 read this as the third of *next* month. However, if you enter \"17\",
3222 it will be considered as *this* month.
3224 If you set this variable to the symbol `time', then also the following
3225 will work:
3227 3. If the user gives a time.
3228 If the time is before now, it will be interpreted as tomorrow.
3230 Currently none of this works for ISO week specifications.
3232 When this option is nil, the current day, month and year will always be
3233 used as defaults.
3235 See also `org-agenda-jump-prefer-future'."
3236 :group 'org-time
3237 :type '(choice
3238 (const :tag "Never" nil)
3239 (const :tag "Check month and day" t)
3240 (const :tag "Check month, day, and time" time)))
3242 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3243 "Should the agenda jump command prefer the future for incomplete dates?
3244 The default is to do the same as configured in `org-read-date-prefer-future'.
3245 But you can also set a deviating value here.
3246 This may t or nil, or the symbol `org-read-date-prefer-future'."
3247 :group 'org-agenda
3248 :group 'org-time
3249 :version "24.1"
3250 :type '(choice
3251 (const :tag "Use org-read-date-prefer-future"
3252 org-read-date-prefer-future)
3253 (const :tag "Never" nil)
3254 (const :tag "Always" t)))
3256 (defcustom org-read-date-force-compatible-dates t
3257 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3259 Depending on the system Emacs is running on, certain dates cannot
3260 be represented with the type used internally to represent time.
3261 Dates between 1970-1-1 and 2038-1-1 can always be represented
3262 correctly. Some systems allow for earlier dates, some for later,
3263 some for both. One way to find out it to insert any date into an
3264 Org buffer, putting the cursor on the year and hitting S-up and
3265 S-down to test the range.
3267 When this variable is set to t, the date/time prompt will not let
3268 you specify dates outside the 1970-2037 range, so it is certain that
3269 these dates will work in whatever version of Emacs you are
3270 running, and also that you can move a file from one Emacs implementation
3271 to another. WHenever Org is forcing the year for you, it will display
3272 a message and beep.
3274 When this variable is nil, Org will check if the date is
3275 representable in the specific Emacs implementation you are using.
3276 If not, it will force a year, usually the current year, and beep
3277 to remind you. Currently this setting is not recommended because
3278 the likelihood that you will open your Org files in an Emacs that
3279 has limited date range is not negligible.
3281 A workaround for this problem is to use diary sexp dates for time
3282 stamps outside of this range."
3283 :group 'org-time
3284 :version "24.1"
3285 :type 'boolean)
3287 (defcustom org-read-date-display-live t
3288 "Non-nil means display current interpretation of date prompt live.
3289 This display will be in an overlay, in the minibuffer."
3290 :group 'org-time
3291 :type 'boolean)
3293 (defcustom org-read-date-popup-calendar t
3294 "Non-nil means pop up a calendar when prompting for a date.
3295 In the calendar, the date can be selected with mouse-1. However, the
3296 minibuffer will also be active, and you can simply enter the date as well.
3297 When nil, only the minibuffer will be available."
3298 :group 'org-time
3299 :type 'boolean)
3300 (org-defvaralias 'org-popup-calendar-for-date-prompt
3301 'org-read-date-popup-calendar)
3303 (make-obsolete-variable
3304 'org-read-date-minibuffer-setup-hook
3305 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3306 (defcustom org-read-date-minibuffer-setup-hook nil
3307 "Hook to be used to set up keys for the date/time interface.
3308 Add key definitions to `minibuffer-local-map', which will be a
3309 temporary copy.
3311 WARNING: This option is obsolete, you should use
3312 `org-read-date-minibuffer-local-map' to set up keys."
3313 :group 'org-time
3314 :type 'hook)
3316 (defcustom org-extend-today-until 0
3317 "The hour when your day really ends. Must be an integer.
3318 This has influence for the following applications:
3319 - When switching the agenda to \"today\". It it is still earlier than
3320 the time given here, the day recognized as TODAY is actually yesterday.
3321 - When a date is read from the user and it is still before the time given
3322 here, the current date and time will be assumed to be yesterday, 23:59.
3323 Also, timestamps inserted in capture templates follow this rule.
3325 IMPORTANT: This is a feature whose implementation is and likely will
3326 remain incomplete. Really, it is only here because past midnight seems to
3327 be the favorite working time of John Wiegley :-)"
3328 :group 'org-time
3329 :type 'integer)
3331 (defcustom org-use-effective-time nil
3332 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3333 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3334 \"effective time\" of any timestamps between midnight and 8am will be
3335 23:59 of the previous day."
3336 :group 'org-time
3337 :version "24.1"
3338 :type 'boolean)
3340 (defcustom org-use-last-clock-out-time-as-effective-time nil
3341 "When non-nil, use the last clock out time for `org-todo'.
3342 Note that this option has precedence over the combined use of
3343 `org-use-effective-time' and `org-extend-today-until'."
3344 :group 'org-time
3345 :version "24.4"
3346 :package-version '(Org . "8.0")
3347 :type 'boolean)
3349 (defcustom org-edit-timestamp-down-means-later nil
3350 "Non-nil means S-down will increase the time in a time stamp.
3351 When nil, S-up will increase."
3352 :group 'org-time
3353 :type 'boolean)
3355 (defcustom org-calendar-follow-timestamp-change t
3356 "Non-nil means make the calendar window follow timestamp changes.
3357 When a timestamp is modified and the calendar window is visible, it will be
3358 moved to the new date."
3359 :group 'org-time
3360 :type 'boolean)
3362 (defgroup org-tags nil
3363 "Options concerning tags in Org-mode."
3364 :tag "Org Tags"
3365 :group 'org)
3367 (defcustom org-tag-alist nil
3368 "List of tags allowed in Org-mode files.
3369 When this list is nil, Org-mode will base TAG input on what is already in the
3370 buffer.
3371 The value of this variable is an alist, the car of each entry must be a
3372 keyword as a string, the cdr may be a character that is used to select
3373 that tag through the fast-tag-selection interface.
3374 See the manual for details."
3375 :group 'org-tags
3376 :type '(repeat
3377 (choice
3378 (cons (string :tag "Tag name")
3379 (character :tag "Access char"))
3380 (list :tag "Start radio group"
3381 (const :startgroup)
3382 (option (string :tag "Group description")))
3383 (list :tag "Group tags delimiter"
3384 (const :grouptags))
3385 (list :tag "End radio group"
3386 (const :endgroup)
3387 (option (string :tag "Group description")))
3388 (const :tag "New line" (:newline)))))
3390 (defcustom org-tag-persistent-alist nil
3391 "List of tags that will always appear in all Org-mode files.
3392 This is in addition to any in buffer settings or customizations
3393 of `org-tag-alist'.
3394 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3395 The value of this variable is an alist, the car of each entry must be a
3396 keyword as a string, the cdr may be a character that is used to select
3397 that tag through the fast-tag-selection interface.
3398 See the manual for details.
3399 To disable these tags on a per-file basis, insert anywhere in the file:
3400 #+STARTUP: noptag"
3401 :group 'org-tags
3402 :type '(repeat
3403 (choice
3404 (cons (string :tag "Tag name")
3405 (character :tag "Access char"))
3406 (const :tag "Start radio group" (:startgroup))
3407 (const :tag "Group tags delimiter" (:grouptags))
3408 (const :tag "End radio group" (:endgroup))
3409 (const :tag "New line" (:newline)))))
3411 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3412 "If non-nil, always offer completion for all tags of all agenda files.
3413 Instead of customizing this variable directly, you might want to
3414 set it locally for capture buffers, because there no list of
3415 tags in that file can be created dynamically (there are none).
3417 (add-hook 'org-capture-mode-hook
3418 (lambda ()
3419 (set (make-local-variable
3420 'org-complete-tags-always-offer-all-agenda-tags)
3421 t)))"
3422 :group 'org-tags
3423 :version "24.1"
3424 :type 'boolean)
3426 (defvar org-file-tags nil
3427 "List of tags that can be inherited by all entries in the file.
3428 The tags will be inherited if the variable `org-use-tag-inheritance'
3429 says they should be.
3430 This variable is populated from #+FILETAGS lines.")
3432 (defcustom org-use-fast-tag-selection 'auto
3433 "Non-nil means use fast tag selection scheme.
3434 This is a special interface to select and deselect tags with single keys.
3435 When nil, fast selection is never used.
3436 When the symbol `auto', fast selection is used if and only if selection
3437 characters for tags have been configured, either through the variable
3438 `org-tag-alist' or through a #+TAGS line in the buffer.
3439 When t, fast selection is always used and selection keys are assigned
3440 automatically if necessary."
3441 :group 'org-tags
3442 :type '(choice
3443 (const :tag "Always" t)
3444 (const :tag "Never" nil)
3445 (const :tag "When selection characters are configured" auto)))
3447 (defcustom org-fast-tag-selection-single-key nil
3448 "Non-nil means fast tag selection exits after first change.
3449 When nil, you have to press RET to exit it.
3450 During fast tag selection, you can toggle this flag with `C-c'.
3451 This variable can also have the value `expert'. In this case, the window
3452 displaying the tags menu is not even shown, until you press C-c again."
3453 :group 'org-tags
3454 :type '(choice
3455 (const :tag "No" nil)
3456 (const :tag "Yes" t)
3457 (const :tag "Expert" expert)))
3459 (defvar org-fast-tag-selection-include-todo nil
3460 "Non-nil means fast tags selection interface will also offer TODO states.
3461 This is an undocumented feature, you should not rely on it.")
3463 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3464 "The column to which tags should be indented in a headline.
3465 If this number is positive, it specifies the column. If it is negative,
3466 it means that the tags should be flushright to that column. For example,
3467 -80 works well for a normal 80 character screen.
3468 When 0, place tags directly after headline text, with only one space in
3469 between."
3470 :group 'org-tags
3471 :type 'integer)
3473 (defcustom org-auto-align-tags t
3474 "Non-nil keeps tags aligned when modifying headlines.
3475 Some operations (i.e. demoting) change the length of a headline and
3476 therefore shift the tags around. With this option turned on, after
3477 each such operation the tags are again aligned to `org-tags-column'."
3478 :group 'org-tags
3479 :type 'boolean)
3481 (defcustom org-use-tag-inheritance t
3482 "Non-nil means tags in levels apply also for sublevels.
3483 When nil, only the tags directly given in a specific line apply there.
3484 This may also be a list of tags that should be inherited, or a regexp that
3485 matches tags that should be inherited. Additional control is possible
3486 with the variable `org-tags-exclude-from-inheritance' which gives an
3487 explicit list of tags to be excluded from inheritance, even if the value of
3488 `org-use-tag-inheritance' would select it for inheritance.
3490 If this option is t, a match early-on in a tree can lead to a large
3491 number of matches in the subtree when constructing the agenda or creating
3492 a sparse tree. If you only want to see the first match in a tree during
3493 a search, check out the variable `org-tags-match-list-sublevels'."
3494 :group 'org-tags
3495 :type '(choice
3496 (const :tag "Not" nil)
3497 (const :tag "Always" t)
3498 (repeat :tag "Specific tags" (string :tag "Tag"))
3499 (regexp :tag "Tags matched by regexp")))
3501 (defcustom org-tags-exclude-from-inheritance nil
3502 "List of tags that should never be inherited.
3503 This is a way to exclude a few tags from inheritance. For way to do
3504 the opposite, to actively allow inheritance for selected tags,
3505 see the variable `org-use-tag-inheritance'."
3506 :group 'org-tags
3507 :type '(repeat (string :tag "Tag")))
3509 (defun org-tag-inherit-p (tag)
3510 "Check if TAG is one that should be inherited."
3511 (cond
3512 ((member tag org-tags-exclude-from-inheritance) nil)
3513 ((eq org-use-tag-inheritance t) t)
3514 ((not org-use-tag-inheritance) nil)
3515 ((stringp org-use-tag-inheritance)
3516 (string-match org-use-tag-inheritance tag))
3517 ((listp org-use-tag-inheritance)
3518 (member tag org-use-tag-inheritance))
3519 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3521 (defcustom org-tags-match-list-sublevels t
3522 "Non-nil means list also sublevels of headlines matching a search.
3523 This variable applies to tags/property searches, and also to stuck
3524 projects because this search is based on a tags match as well.
3526 When set to the symbol `indented', sublevels are indented with
3527 leading dots.
3529 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3530 the sublevels of a headline matching a tag search often also match
3531 the same search. Listing all of them can create very long lists.
3532 Setting this variable to nil causes subtrees of a match to be skipped.
3534 This variable is semi-obsolete and probably should always be true. It
3535 is better to limit inheritance to certain tags using the variables
3536 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3537 :group 'org-tags
3538 :type '(choice
3539 (const :tag "No, don't list them" nil)
3540 (const :tag "Yes, do list them" t)
3541 (const :tag "List them, indented with leading dots" indented)))
3543 (defcustom org-tags-sort-function nil
3544 "When set, tags are sorted using this function as a comparator."
3545 :group 'org-tags
3546 :type '(choice
3547 (const :tag "No sorting" nil)
3548 (const :tag "Alphabetical" string<)
3549 (const :tag "Reverse alphabetical" string>)
3550 (function :tag "Custom function" nil)))
3552 (defvar org-tags-history nil
3553 "History of minibuffer reads for tags.")
3554 (defvar org-last-tags-completion-table nil
3555 "The last used completion table for tags.")
3556 (defvar org-after-tags-change-hook nil
3557 "Hook that is run after the tags in a line have changed.")
3559 (defgroup org-properties nil
3560 "Options concerning properties in Org-mode."
3561 :tag "Org Properties"
3562 :group 'org)
3564 (defcustom org-property-format "%-10s %s"
3565 "How property key/value pairs should be formatted by `indent-line'.
3566 When `indent-line' hits a property definition, it will format the line
3567 according to this format, mainly to make sure that the values are
3568 lined-up with respect to each other."
3569 :group 'org-properties
3570 :type 'string)
3572 (defcustom org-properties-postprocess-alist nil
3573 "Alist of properties and functions to adjust inserted values.
3574 Elements of this alist must be of the form
3576 ([string] [function])
3578 where [string] must be a property name and [function] must be a
3579 lambda expression: this lambda expression must take one argument,
3580 the value to adjust, and return the new value as a string.
3582 For example, this element will allow the property \"Remaining\"
3583 to be updated wrt the relation between the \"Effort\" property
3584 and the clock summary:
3586 ((\"Remaining\" (lambda(value)
3587 (let ((clocksum (org-clock-sum-current-item))
3588 (effort (org-duration-string-to-minutes
3589 (org-entry-get (point) \"Effort\"))))
3590 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3591 :group 'org-properties
3592 :version "24.1"
3593 :type '(alist :key-type (string :tag "Property")
3594 :value-type (function :tag "Function")))
3596 (defcustom org-use-property-inheritance nil
3597 "Non-nil means properties apply also for sublevels.
3599 This setting is chiefly used during property searches. Turning it on can
3600 cause significant overhead when doing a search, which is why it is not
3601 on by default.
3603 When nil, only the properties directly given in the current entry count.
3604 When t, every property is inherited. The value may also be a list of
3605 properties that should have inheritance, or a regular expression matching
3606 properties that should be inherited.
3608 However, note that some special properties use inheritance under special
3609 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3610 and the properties ending in \"_ALL\" when they are used as descriptor
3611 for valid values of a property.
3613 Note for programmers:
3614 When querying an entry with `org-entry-get', you can control if inheritance
3615 should be used. By default, `org-entry-get' looks only at the local
3616 properties. You can request inheritance by setting the inherit argument
3617 to t (to force inheritance) or to `selective' (to respect the setting
3618 in this variable)."
3619 :group 'org-properties
3620 :type '(choice
3621 (const :tag "Not" nil)
3622 (const :tag "Always" t)
3623 (repeat :tag "Specific properties" (string :tag "Property"))
3624 (regexp :tag "Properties matched by regexp")))
3626 (defun org-property-inherit-p (property)
3627 "Check if PROPERTY is one that should be inherited."
3628 (cond
3629 ((eq org-use-property-inheritance t) t)
3630 ((not org-use-property-inheritance) nil)
3631 ((stringp org-use-property-inheritance)
3632 (string-match org-use-property-inheritance property))
3633 ((listp org-use-property-inheritance)
3634 (member property org-use-property-inheritance))
3635 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3637 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3638 "The default column format, if no other format has been defined.
3639 This variable can be set on the per-file basis by inserting a line
3641 #+COLUMNS: %25ITEM ....."
3642 :group 'org-properties
3643 :type 'string)
3645 (defcustom org-columns-ellipses ".."
3646 "The ellipses to be used when a field in column view is truncated.
3647 When this is the empty string, as many characters as possible are shown,
3648 but then there will be no visual indication that the field has been truncated.
3649 When this is a string of length N, the last N characters of a truncated
3650 field are replaced by this string. If the column is narrower than the
3651 ellipses string, only part of the ellipses string will be shown."
3652 :group 'org-properties
3653 :type 'string)
3655 (defcustom org-columns-modify-value-for-display-function nil
3656 "Function that modifies values for display in column view.
3657 For example, it can be used to cut out a certain part from a time stamp.
3658 The function must take 2 arguments:
3660 column-title The title of the column (*not* the property name)
3661 value The value that should be modified.
3663 The function should return the value that should be displayed,
3664 or nil if the normal value should be used."
3665 :group 'org-properties
3666 :type '(choice (const nil) (function)))
3668 (defconst org-global-properties-fixed
3669 '(("VISIBILITY_ALL" . "folded children content all")
3670 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3671 "List of property/value pairs that can be inherited by any entry.
3673 These are fixed values, for the preset properties. The user variable
3674 that can be used to add to this list is `org-global-properties'.
3676 The entries in this list are cons cells where the car is a property
3677 name and cdr is a string with the value. If the value represents
3678 multiple items like an \"_ALL\" property, separate the items by
3679 spaces.")
3681 (defcustom org-global-properties nil
3682 "List of property/value pairs that can be inherited by any entry.
3684 This list will be combined with the constant `org-global-properties-fixed'.
3686 The entries in this list are cons cells where the car is a property
3687 name and cdr is a string with the value.
3689 You can set buffer-local values for the same purpose in the variable
3690 `org-file-properties' this by adding lines like
3692 #+PROPERTY: NAME VALUE"
3693 :group 'org-properties
3694 :type '(repeat
3695 (cons (string :tag "Property")
3696 (string :tag "Value"))))
3698 (defvar org-file-properties nil
3699 "List of property/value pairs that can be inherited by any entry.
3700 Valid for the current buffer.
3701 This variable is populated from #+PROPERTY lines.")
3702 (make-variable-buffer-local 'org-file-properties)
3704 (defgroup org-agenda nil
3705 "Options concerning agenda views in Org-mode."
3706 :tag "Org Agenda"
3707 :group 'org)
3709 (defvar org-category nil
3710 "Variable used by org files to set a category for agenda display.
3711 Such files should use a file variable to set it, for example
3713 # -*- mode: org; org-category: \"ELisp\"
3715 or contain a special line
3717 #+CATEGORY: ELisp
3719 If the file does not specify a category, then file's base name
3720 is used instead.")
3721 (make-variable-buffer-local 'org-category)
3722 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3724 (defcustom org-agenda-files nil
3725 "The files to be used for agenda display.
3726 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3727 \\[org-remove-file]. You can also use customize to edit the list.
3729 If an entry is a directory, all files in that directory that are matched by
3730 `org-agenda-file-regexp' will be part of the file list.
3732 If the value of the variable is not a list but a single file name, then
3733 the list of agenda files is actually stored and maintained in that file, one
3734 agenda file per line. In this file paths can be given relative to
3735 `org-directory'. Tilde expansion and environment variable substitution
3736 are also made."
3737 :group 'org-agenda
3738 :type '(choice
3739 (repeat :tag "List of files and directories" file)
3740 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3742 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3743 "Regular expression to match files for `org-agenda-files'.
3744 If any element in the list in that variable contains a directory instead
3745 of a normal file, all files in that directory that are matched by this
3746 regular expression will be included."
3747 :group 'org-agenda
3748 :type 'regexp)
3750 (defcustom org-agenda-text-search-extra-files nil
3751 "List of extra files to be searched by text search commands.
3752 These files will be searched in addition to the agenda files by the
3753 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3754 Note that these files will only be searched for text search commands,
3755 not for the other agenda views like todo lists, tag searches or the weekly
3756 agenda. This variable is intended to list notes and possibly archive files
3757 that should also be searched by these two commands.
3758 In fact, if the first element in the list is the symbol `agenda-archives',
3759 then all archive files of all agenda files will be added to the search
3760 scope."
3761 :group 'org-agenda
3762 :type '(set :greedy t
3763 (const :tag "Agenda Archives" agenda-archives)
3764 (repeat :inline t (file))))
3766 (org-defvaralias 'org-agenda-multi-occur-extra-files
3767 'org-agenda-text-search-extra-files)
3769 (defcustom org-agenda-skip-unavailable-files nil
3770 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3771 A nil value means to remove them, after a query, from the list."
3772 :group 'org-agenda
3773 :type 'boolean)
3775 (defcustom org-calendar-to-agenda-key [?c]
3776 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3777 The command `org-calendar-goto-agenda' will be bound to this key. The
3778 default is the character `c' because then `c' can be used to switch back and
3779 forth between agenda and calendar."
3780 :group 'org-agenda
3781 :type 'sexp)
3783 (defcustom org-calendar-insert-diary-entry-key [?i]
3784 "The key to be installed in `calendar-mode-map' for adding diary entries.
3785 This option is irrelevant until `org-agenda-diary-file' has been configured
3786 to point to an Org-mode file. When that is the case, the command
3787 `org-agenda-diary-entry' will be bound to the key given here, by default
3788 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3789 if you want to continue doing this, you need to change this to a different
3790 key."
3791 :group 'org-agenda
3792 :type 'sexp)
3794 (defcustom org-agenda-diary-file 'diary-file
3795 "File to which to add new entries with the `i' key in agenda and calendar.
3796 When this is the symbol `diary-file', the functionality in the Emacs
3797 calendar will be used to add entries to the `diary-file'. But when this
3798 points to a file, `org-agenda-diary-entry' will be used instead."
3799 :group 'org-agenda
3800 :type '(choice
3801 (const :tag "The standard Emacs diary file" diary-file)
3802 (file :tag "Special Org file diary entries")))
3804 (eval-after-load "calendar"
3805 '(progn
3806 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3807 'org-calendar-goto-agenda)
3808 (add-hook 'calendar-mode-hook
3809 (lambda ()
3810 (unless (eq org-agenda-diary-file 'diary-file)
3811 (define-key calendar-mode-map
3812 org-calendar-insert-diary-entry-key
3813 'org-agenda-diary-entry))))))
3815 (defgroup org-latex nil
3816 "Options for embedding LaTeX code into Org-mode."
3817 :tag "Org LaTeX"
3818 :group 'org)
3820 (defcustom org-format-latex-options
3821 '(:foreground default :background default :scale 1.0
3822 :html-foreground "Black" :html-background "Transparent"
3823 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3824 "Options for creating images from LaTeX fragments.
3825 This is a property list with the following properties:
3826 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3827 `default' means use the foreground of the default face.
3828 `auto' means use the foreground from the text face.
3829 :background the background color, or \"Transparent\".
3830 `default' means use the background of the default face.
3831 `auto' means use the background from the text face.
3832 :scale a scaling factor for the size of the images, to get more pixels
3833 :html-foreground, :html-background, :html-scale
3834 the same numbers for HTML export.
3835 :matchers a list indicating which matchers should be used to
3836 find LaTeX fragments. Valid members of this list are:
3837 \"begin\" find environments
3838 \"$1\" find single characters surrounded by $.$
3839 \"$\" find math expressions surrounded by $...$
3840 \"$$\" find math expressions surrounded by $$....$$
3841 \"\\(\" find math expressions surrounded by \\(...\\)
3842 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3843 :group 'org-latex
3844 :type 'plist)
3846 (defcustom org-format-latex-signal-error t
3847 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3848 When nil, just push out a message."
3849 :group 'org-latex
3850 :version "24.1"
3851 :type 'boolean)
3853 (defcustom org-latex-to-mathml-jar-file nil
3854 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3855 Use this to specify additional executable file say a jar file.
3857 When using MathToWeb as the converter, specify the full-path to
3858 your mathtoweb.jar file."
3859 :group 'org-latex
3860 :version "24.1"
3861 :type '(choice
3862 (const :tag "None" nil)
3863 (file :tag "JAR file" :must-match t)))
3865 (defcustom org-latex-to-mathml-convert-command nil
3866 "Command to convert LaTeX fragments to MathML.
3867 Replace format-specifiers in the command as noted below and use
3868 `shell-command' to convert LaTeX to MathML.
3869 %j: Executable file in fully expanded form as specified by
3870 `org-latex-to-mathml-jar-file'.
3871 %I: Input LaTeX file in fully expanded form
3872 %o: Output MathML file
3873 This command is used by `org-create-math-formula'.
3875 When using MathToWeb as the converter, set this to
3876 \"java -jar %j -unicode -force -df %o %I\"."
3877 :group 'org-latex
3878 :version "24.1"
3879 :type '(choice
3880 (const :tag "None" nil)
3881 (string :tag "\nShell command")))
3883 (defcustom org-latex-create-formula-image-program 'dvipng
3884 "Program to convert LaTeX fragments with.
3886 dvipng Process the LaTeX fragments to dvi file, then convert
3887 dvi files to png files using dvipng.
3888 This will also include processing of non-math environments.
3889 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3890 to convert pdf files to png files"
3891 :group 'org-latex
3892 :version "24.1"
3893 :type '(choice
3894 (const :tag "dvipng" dvipng)
3895 (const :tag "imagemagick" imagemagick)))
3897 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3898 "Path to store latex preview images.
3899 A relative path here creates many directories relative to the
3900 processed org files paths. An absolute path puts all preview
3901 images at the same place."
3902 :group 'org-latex
3903 :version "24.3"
3904 :type 'string)
3906 (defun org-format-latex-mathml-available-p ()
3907 "Return t if `org-latex-to-mathml-convert-command' is usable."
3908 (save-match-data
3909 (when (and (boundp 'org-latex-to-mathml-convert-command)
3910 org-latex-to-mathml-convert-command)
3911 (let ((executable (car (split-string
3912 org-latex-to-mathml-convert-command))))
3913 (when (executable-find executable)
3914 (if (string-match
3915 "%j" org-latex-to-mathml-convert-command)
3916 (file-readable-p org-latex-to-mathml-jar-file)
3917 t))))))
3919 (defcustom org-format-latex-header "\\documentclass{article}
3920 \\usepackage[usenames]{color}
3921 \[PACKAGES]
3922 \[DEFAULT-PACKAGES]
3923 \\pagestyle{empty} % do not remove
3924 % The settings below are copied from fullpage.sty
3925 \\setlength{\\textwidth}{\\paperwidth}
3926 \\addtolength{\\textwidth}{-3cm}
3927 \\setlength{\\oddsidemargin}{1.5cm}
3928 \\addtolength{\\oddsidemargin}{-2.54cm}
3929 \\setlength{\\evensidemargin}{\\oddsidemargin}
3930 \\setlength{\\textheight}{\\paperheight}
3931 \\addtolength{\\textheight}{-\\headheight}
3932 \\addtolength{\\textheight}{-\\headsep}
3933 \\addtolength{\\textheight}{-\\footskip}
3934 \\addtolength{\\textheight}{-3cm}
3935 \\setlength{\\topmargin}{1.5cm}
3936 \\addtolength{\\topmargin}{-2.54cm}"
3937 "The document header used for processing LaTeX fragments.
3938 It is imperative that this header make sure that no page number
3939 appears on the page. The package defined in the variables
3940 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3941 will either replace the placeholder \"[PACKAGES]\" in this
3942 header, or they will be appended."
3943 :group 'org-latex
3944 :type 'string)
3946 (defun org-set-packages-alist (var val)
3947 "Set the packages alist and make sure it has 3 elements per entry."
3948 (set var (mapcar (lambda (x)
3949 (if (and (consp x) (= (length x) 2))
3950 (list (car x) (nth 1 x) t)
3952 val)))
3954 (defun org-get-packages-alist (var)
3955 "Get the packages alist and make sure it has 3 elements per entry."
3956 (mapcar (lambda (x)
3957 (if (and (consp x) (= (length x) 2))
3958 (list (car x) (nth 1 x) t)
3960 (default-value var)))
3962 (defcustom org-latex-default-packages-alist
3963 '(("AUTO" "inputenc" t)
3964 ("T1" "fontenc" t)
3965 ("" "fixltx2e" nil)
3966 ("" "graphicx" t)
3967 ("" "longtable" nil)
3968 ("" "float" nil)
3969 ("" "wrapfig" nil)
3970 ("" "rotating" nil)
3971 ("normalem" "ulem" t)
3972 ("" "amsmath" t)
3973 ("" "textcomp" t)
3974 ("" "marvosym" t)
3975 ("" "wasysym" t)
3976 ("" "amssymb" t)
3977 ("" "hyperref" nil)
3978 "\\tolerance=1000")
3979 "Alist of default packages to be inserted in the header.
3981 Change this only if one of the packages here causes an
3982 incompatibility with another package you are using.
3984 The packages in this list are needed by one part or another of
3985 Org mode to function properly:
3987 - inputenc, fontenc: for basic font and character selection
3988 - fixltx2e: Important patches of LaTeX itself
3989 - graphicx: for including images
3990 - longtable: For multipage tables
3991 - float, wrapfig: for figure placement
3992 - rotating: for sideways figures and tables
3993 - ulem: for underline and strike-through
3994 - amsmath: for subscript and superscript and math environments
3995 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3996 for interpreting the entities in `org-entities'. You can skip
3997 some of these packages if you don't use any of their symbols.
3998 - hyperref: for cross references
4000 Therefore you should not modify this variable unless you know
4001 what you are doing. The one reason to change it anyway is that
4002 you might be loading some other package that conflicts with one
4003 of the default packages. Each element is either a cell or
4004 a string.
4006 A cell is of the format:
4008 \( \"options\" \"package\" SNIPPET-FLAG).
4010 If SNIPPET-FLAG is non-nil, the package also needs to be included
4011 when compiling LaTeX snippets into images for inclusion into
4012 non-LaTeX output.
4014 A string will be inserted as-is in the header of the document."
4015 :group 'org-latex
4016 :group 'org-export-latex
4017 :set 'org-set-packages-alist
4018 :get 'org-get-packages-alist
4019 :version "24.1"
4020 :type '(repeat
4021 (choice
4022 (list :tag "options/package pair"
4023 (string :tag "options")
4024 (string :tag "package")
4025 (boolean :tag "Snippet"))
4026 (string :tag "A line of LaTeX"))))
4028 (defcustom org-latex-packages-alist nil
4029 "Alist of packages to be inserted in every LaTeX header.
4031 These will be inserted after `org-latex-default-packages-alist'.
4032 Each element is either a cell or a string.
4034 A cell is of the format:
4036 \(\"options\" \"package\" SNIPPET-FLAG)
4038 SNIPPET-FLAG, when non-nil, indicates that this package is also
4039 needed when turning LaTeX snippets into images for inclusion into
4040 non-LaTeX output.
4042 A string will be inserted as-is in the header of the document.
4044 Make sure that you only list packages here which:
4046 - you want in every file;
4047 - do not conflict with the setup in `org-format-latex-header';
4048 - do not conflict with the default packages in
4049 `org-latex-default-packages-alist'."
4050 :group 'org-latex
4051 :group 'org-export-latex
4052 :set 'org-set-packages-alist
4053 :get 'org-get-packages-alist
4054 :type '(repeat
4055 (choice
4056 (list :tag "options/package pair"
4057 (string :tag "options")
4058 (string :tag "package")
4059 (boolean :tag "Snippet"))
4060 (string :tag "A line of LaTeX"))))
4062 (defgroup org-appearance nil
4063 "Settings for Org-mode appearance."
4064 :tag "Org Appearance"
4065 :group 'org)
4067 (defcustom org-level-color-stars-only nil
4068 "Non-nil means fontify only the stars in each headline.
4069 When nil, the entire headline is fontified.
4070 Changing it requires restart of `font-lock-mode' to become effective
4071 also in regions already fontified."
4072 :group 'org-appearance
4073 :type 'boolean)
4075 (defcustom org-hide-leading-stars nil
4076 "Non-nil means hide the first N-1 stars in a headline.
4077 This works by using the face `org-hide' for these stars. This
4078 face is white for a light background, and black for a dark
4079 background. You may have to customize the face `org-hide' to
4080 make this work.
4081 Changing it requires restart of `font-lock-mode' to become effective
4082 also in regions already fontified.
4083 You may also set this on a per-file basis by adding one of the following
4084 lines to the buffer:
4086 #+STARTUP: hidestars
4087 #+STARTUP: showstars"
4088 :group 'org-appearance
4089 :type 'boolean)
4091 (defcustom org-hidden-keywords nil
4092 "List of symbols corresponding to keywords to be hidden the org buffer.
4093 For example, a value '(title) for this list will make the document's title
4094 appear in the buffer without the initial #+TITLE: keyword."
4095 :group 'org-appearance
4096 :version "24.1"
4097 :type '(set (const :tag "#+AUTHOR" author)
4098 (const :tag "#+DATE" date)
4099 (const :tag "#+EMAIL" email)
4100 (const :tag "#+TITLE" title)))
4102 (defcustom org-custom-properties nil
4103 "List of properties (as strings) with a special meaning.
4104 The default use of these custom properties is to let the user
4105 hide them with `org-toggle-custom-properties-visibility'."
4106 :group 'org-properties
4107 :group 'org-appearance
4108 :version "24.3"
4109 :type '(repeat (string :tag "Property Name")))
4111 (defcustom org-fontify-done-headline nil
4112 "Non-nil means change the face of a headline if it is marked DONE.
4113 Normally, only the TODO/DONE keyword indicates the state of a headline.
4114 When this is non-nil, the headline after the keyword is set to the
4115 `org-headline-done' as an additional indication."
4116 :group 'org-appearance
4117 :type 'boolean)
4119 (defcustom org-fontify-emphasized-text t
4120 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4121 Changing this variable requires a restart of Emacs to take effect."
4122 :group 'org-appearance
4123 :type 'boolean)
4125 (defcustom org-fontify-whole-heading-line nil
4126 "Non-nil means fontify the whole line for headings.
4127 This is useful when setting a background color for the
4128 org-level-* faces."
4129 :group 'org-appearance
4130 :type 'boolean)
4132 (defcustom org-highlight-latex-and-related nil
4133 "Non-nil means highlight LaTeX related syntax in the buffer.
4134 When non nil, the value should be a list containing any of the
4135 following symbols:
4136 `latex' Highlight LaTeX snippets and environments.
4137 `script' Highlight subscript and superscript.
4138 `entities' Highlight entities."
4139 :group 'org-appearance
4140 :version "24.4"
4141 :package-version '(Org . "8.0")
4142 :type '(choice
4143 (const :tag "No highlighting" nil)
4144 (set :greedy t :tag "Highlight"
4145 (const :tag "LaTeX snippets and environments" latex)
4146 (const :tag "Subscript and superscript" script)
4147 (const :tag "Entities" entities))))
4149 (defcustom org-hide-emphasis-markers nil
4150 "Non-nil mean font-lock should hide the emphasis marker characters."
4151 :group 'org-appearance
4152 :type 'boolean)
4154 (defcustom org-hide-macro-markers nil
4155 "Non-nil mean font-lock should hide the brackets marking macro calls."
4156 :group 'org-appearance
4157 :type 'boolean)
4159 (defcustom org-pretty-entities nil
4160 "Non-nil means show entities as UTF8 characters.
4161 When nil, the \\name form remains in the buffer."
4162 :group 'org-appearance
4163 :version "24.1"
4164 :type 'boolean)
4166 (defcustom org-pretty-entities-include-sub-superscripts t
4167 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4168 :group 'org-appearance
4169 :version "24.1"
4170 :type 'boolean)
4172 (defvar org-emph-re nil
4173 "Regular expression for matching emphasis.
4174 After a match, the match groups contain these elements:
4175 0 The match of the full regular expression, including the characters
4176 before and after the proper match
4177 1 The character before the proper match, or empty at beginning of line
4178 2 The proper match, including the leading and trailing markers
4179 3 The leading marker like * or /, indicating the type of highlighting
4180 4 The text between the emphasis markers, not including the markers
4181 5 The character after the match, empty at the end of a line")
4182 (defvar org-verbatim-re nil
4183 "Regular expression for matching verbatim text.")
4184 (defvar org-emphasis-regexp-components) ; defined just below
4185 (defvar org-emphasis-alist) ; defined just below
4186 (defun org-set-emph-re (var val)
4187 "Set variable and compute the emphasis regular expression."
4188 (set var val)
4189 (when (and (boundp 'org-emphasis-alist)
4190 (boundp 'org-emphasis-regexp-components)
4191 org-emphasis-alist org-emphasis-regexp-components)
4192 (let* ((e org-emphasis-regexp-components)
4193 (pre (car e))
4194 (post (nth 1 e))
4195 (border (nth 2 e))
4196 (body (nth 3 e))
4197 (nl (nth 4 e))
4198 (body1 (concat body "*?"))
4199 (markers (mapconcat 'car org-emphasis-alist ""))
4200 (vmarkers (mapconcat
4201 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4202 org-emphasis-alist "")))
4203 ;; make sure special characters appear at the right position in the class
4204 (if (string-match "\\^" markers)
4205 (setq markers (concat (replace-match "" t t markers) "^")))
4206 (if (string-match "-" markers)
4207 (setq markers (concat (replace-match "" t t markers) "-")))
4208 (if (string-match "\\^" vmarkers)
4209 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4210 (if (string-match "-" vmarkers)
4211 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4212 (if (> nl 0)
4213 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4214 (int-to-string nl) "\\}")))
4215 ;; Make the regexp
4216 (setq org-emph-re
4217 (concat "\\([" pre "]\\|^\\)"
4218 "\\("
4219 "\\([" markers "]\\)"
4220 "\\("
4221 "[^" border "]\\|"
4222 "[^" border "]"
4223 body1
4224 "[^" border "]"
4225 "\\)"
4226 "\\3\\)"
4227 "\\([" post "]\\|$\\)"))
4228 (setq org-verbatim-re
4229 (concat "\\([" pre "]\\|^\\)"
4230 "\\("
4231 "\\([" vmarkers "]\\)"
4232 "\\("
4233 "[^" border "]\\|"
4234 "[^" border "]"
4235 body1
4236 "[^" border "]"
4237 "\\)"
4238 "\\3\\)"
4239 "\\([" post "]\\|$\\)")))))
4241 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4242 ;; set this option proved cumbersome. See this message/thread:
4243 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4244 (defvar org-emphasis-regexp-components
4245 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4246 "Components used to build the regular expression for emphasis.
4247 This is a list with five entries. Terminology: In an emphasis string
4248 like \" *strong word* \", we call the initial space PREMATCH, the final
4249 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4250 and \"trong wor\" is the body. The different components in this variable
4251 specify what is allowed/forbidden in each part:
4253 pre Chars allowed as prematch. Beginning of line will be allowed too.
4254 post Chars allowed as postmatch. End of line will be allowed too.
4255 border The chars *forbidden* as border characters.
4256 body-regexp A regexp like \".\" to match a body character. Don't use
4257 non-shy groups here, and don't allow newline here.
4258 newline The maximum number of newlines allowed in an emphasis exp.
4260 You need to reload Org or to restart Emacs after customizing this.")
4262 (defcustom org-emphasis-alist
4263 `(("*" bold)
4264 ("/" italic)
4265 ("_" underline)
4266 ("=" org-verbatim verbatim)
4267 ("~" org-code verbatim)
4268 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4269 "Alist of characters and faces to emphasize text.
4270 Text starting and ending with a special character will be emphasized,
4271 for example *bold*, _underlined_ and /italic/. This variable sets the
4272 marker characters and the face to be used by font-lock for highlighting
4273 in Org-mode Emacs buffers.
4275 You need to reload Org or to restart Emacs after customizing this."
4276 :group 'org-appearance
4277 :set 'org-set-emph-re
4278 :version "24.4"
4279 :package-version '(Org . "8.0")
4280 :type '(repeat
4281 (list
4282 (string :tag "Marker character")
4283 (choice
4284 (face :tag "Font-lock-face")
4285 (plist :tag "Face property list"))
4286 (option (const verbatim)))))
4288 (defvar org-protecting-blocks
4289 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4290 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4291 This is needed for font-lock setup.")
4293 ;;; Miscellaneous options
4295 (defgroup org-completion nil
4296 "Completion in Org-mode."
4297 :tag "Org Completion"
4298 :group 'org)
4300 (defcustom org-completion-use-ido nil
4301 "Non-nil means use ido completion wherever possible.
4302 Note that `ido-mode' must be active for this variable to be relevant.
4303 If you decide to turn this variable on, you might well want to turn off
4304 `org-outline-path-complete-in-steps'.
4305 See also `org-completion-use-iswitchb'."
4306 :group 'org-completion
4307 :type 'boolean)
4309 (defcustom org-completion-use-iswitchb nil
4310 "Non-nil means use iswitchb completion wherever possible.
4311 Note that `iswitchb-mode' must be active for this variable to be relevant.
4312 If you decide to turn this variable on, you might well want to turn off
4313 `org-outline-path-complete-in-steps'.
4314 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4315 :group 'org-completion
4316 :type 'boolean)
4318 (defcustom org-completion-fallback-command 'hippie-expand
4319 "The expansion command called by \\[pcomplete] in normal context.
4320 Normal means, no org-mode-specific context."
4321 :group 'org-completion
4322 :type 'function)
4324 ;;; Functions and variables from their packages
4325 ;; Declared here to avoid compiler warnings
4327 ;; XEmacs only
4328 (defvar outline-mode-menu-heading)
4329 (defvar outline-mode-menu-show)
4330 (defvar outline-mode-menu-hide)
4331 (defvar zmacs-regions) ; XEmacs regions
4333 ;; Emacs only
4334 (defvar mark-active)
4336 ;; Various packages
4337 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4338 (declare-function calendar-forward-day "cal-move" (arg))
4339 (declare-function calendar-goto-date "cal-move" (date))
4340 (declare-function calendar-goto-today "cal-move" ())
4341 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4342 (defvar calc-embedded-close-formula)
4343 (defvar calc-embedded-open-formula)
4344 (declare-function cdlatex-tab "ext:cdlatex" ())
4345 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4346 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4347 (defvar font-lock-unfontify-region-function)
4348 (declare-function iswitchb-read-buffer "iswitchb"
4349 (prompt &optional default require-match start matches-set))
4350 (defvar iswitchb-temp-buflist)
4351 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4352 (defvar org-agenda-tags-todo-honor-ignore-options)
4353 (declare-function org-agenda-skip "org-agenda" ())
4354 (declare-function
4355 org-agenda-format-item "org-agenda"
4356 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4357 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4358 (declare-function org-agenda-change-all-lines "org-agenda"
4359 (newhead hdmarker &optional fixface just-this))
4360 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4361 (declare-function org-agenda-maybe-redo "org-agenda" ())
4362 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4363 (beg end))
4364 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4365 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4366 "org-agenda" (&optional end))
4367 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4368 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4369 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4370 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4371 (declare-function org-indent-mode "org-indent" (&optional arg))
4372 (declare-function parse-time-string "parse-time" (string))
4373 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4374 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4375 (defvar remember-data-file)
4376 (defvar texmathp-why)
4377 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4378 (declare-function table--at-cell-p "table" (position &optional object at-column))
4379 (declare-function calc-eval "calc" (str &optional separator &rest args))
4381 ;;;###autoload
4382 (defun turn-on-orgtbl ()
4383 "Unconditionally turn on `orgtbl-mode'."
4384 (require 'org-table)
4385 (orgtbl-mode 1))
4387 (defun org-at-table-p (&optional table-type)
4388 "Return t if the cursor is inside an org-type table.
4389 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4390 (if org-enable-table-editor
4391 (save-excursion
4392 (beginning-of-line 1)
4393 (looking-at (if table-type org-table-any-line-regexp
4394 org-table-line-regexp)))
4395 nil))
4396 (defsubst org-table-p () (org-at-table-p))
4398 (defun org-at-table.el-p ()
4399 "Return t if and only if we are at a table.el table."
4400 (and (org-at-table-p 'any)
4401 (save-excursion
4402 (goto-char (org-table-begin 'any))
4403 (looking-at org-table1-hline-regexp))))
4405 (defun org-table-recognize-table.el ()
4406 "If there is a table.el table nearby, recognize it and move into it."
4407 (if org-table-tab-recognizes-table.el
4408 (if (org-at-table.el-p)
4409 (progn
4410 (beginning-of-line 1)
4411 (if (looking-at org-table-dataline-regexp)
4413 (if (looking-at org-table1-hline-regexp)
4414 (progn
4415 (beginning-of-line 2)
4416 (if (looking-at org-table-any-border-regexp)
4417 (beginning-of-line -1)))))
4418 (if (re-search-forward "|" (org-table-end t) t)
4419 (progn
4420 (require 'table)
4421 (if (table--at-cell-p (point))
4423 (message "recognizing table.el table...")
4424 (table-recognize-table)
4425 (message "recognizing table.el table...done")))
4426 (error "This should not happen"))
4428 nil)
4429 nil))
4431 (defun org-at-table-hline-p ()
4432 "Return t if the cursor is inside a hline in a table."
4433 (if org-enable-table-editor
4434 (save-excursion
4435 (beginning-of-line 1)
4436 (looking-at org-table-hline-regexp))
4437 nil))
4439 (defun org-table-map-tables (function &optional quietly)
4440 "Apply FUNCTION to the start of all tables in the buffer."
4441 (save-excursion
4442 (save-restriction
4443 (widen)
4444 (goto-char (point-min))
4445 (while (re-search-forward org-table-any-line-regexp nil t)
4446 (unless quietly
4447 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4448 (beginning-of-line 1)
4449 (when (and (looking-at org-table-line-regexp)
4450 ;; Exclude tables in src/example/verbatim/clocktable blocks
4451 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4452 (save-excursion (funcall function))
4453 (or (looking-at org-table-line-regexp)
4454 (forward-char 1)))
4455 (re-search-forward org-table-any-border-regexp nil 1))))
4456 (unless quietly (message "Mapping tables: done")))
4458 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4459 (declare-function org-clock-update-mode-line "org-clock" ())
4460 (declare-function org-resolve-clocks "org-clock"
4461 (&optional also-non-dangling-p prompt last-valid))
4463 (defun org-at-TBLFM-p (&optional pos)
4464 "Return t when point (or POS) is in #+TBLFM line."
4465 (save-excursion
4466 (let ((pos pos)))
4467 (goto-char (or pos (point)))
4468 (beginning-of-line 1)
4469 (looking-at org-TBLFM-regexp)))
4471 (defvar org-clock-start-time)
4472 (defvar org-clock-marker (make-marker)
4473 "Marker recording the last clock-in.")
4474 (defvar org-clock-hd-marker (make-marker)
4475 "Marker recording the last clock-in, but the headline position.")
4476 (defvar org-clock-heading ""
4477 "The heading of the current clock entry.")
4478 (defun org-clock-is-active ()
4479 "Return the buffer where the clock is currently running.
4480 Return nil if no clock is running."
4481 (marker-buffer org-clock-marker))
4483 (defun org-check-running-clock ()
4484 "Check if the current buffer contains the running clock.
4485 If yes, offer to stop it and to save the buffer with the changes."
4486 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4487 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4488 (buffer-name))))
4489 (org-clock-out)
4490 (when (y-or-n-p "Save changed buffer?")
4491 (save-buffer))))
4493 (defun org-clocktable-try-shift (dir n)
4494 "Check if this line starts a clock table, if yes, shift the time block."
4495 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4496 (org-clocktable-shift dir n)))
4498 ;;;###autoload
4499 (defun org-clock-persistence-insinuate ()
4500 "Set up hooks for clock persistence."
4501 (require 'org-clock)
4502 (add-hook 'org-mode-hook 'org-clock-load)
4503 (add-hook 'kill-emacs-hook 'org-clock-save))
4505 (defgroup org-archive nil
4506 "Options concerning archiving in Org-mode."
4507 :tag "Org Archive"
4508 :group 'org-structure)
4510 (defcustom org-archive-location "%s_archive::"
4511 "The location where subtrees should be archived.
4513 The value of this variable is a string, consisting of two parts,
4514 separated by a double-colon. The first part is a filename and
4515 the second part is a headline.
4517 When the filename is omitted, archiving happens in the same file.
4518 %s in the filename will be replaced by the current file
4519 name (without the directory part). Archiving to a different file
4520 is useful to keep archived entries from contributing to the
4521 Org-mode Agenda.
4523 The archived entries will be filed as subtrees of the specified
4524 headline. When the headline is omitted, the subtrees are simply
4525 filed away at the end of the file, as top-level entries. Also in
4526 the heading you can use %s to represent the file name, this can be
4527 useful when using the same archive for a number of different files.
4529 Here are a few examples:
4530 \"%s_archive::\"
4531 If the current file is Projects.org, archive in file
4532 Projects.org_archive, as top-level trees. This is the default.
4534 \"::* Archived Tasks\"
4535 Archive in the current file, under the top-level headline
4536 \"* Archived Tasks\".
4538 \"~/org/archive.org::\"
4539 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4541 \"~/org/archive.org::* From %s\"
4542 Archive in file ~/org/archive.org (absolute path), under headlines
4543 \"From FILENAME\" where file name is the current file name.
4545 \"~/org/datetree.org::datetree/* Finished Tasks\"
4546 The \"datetree/\" string is special, signifying to archive
4547 items to the datetree. Items are placed in either the CLOSED
4548 date of the item, or the current date if there is no CLOSED date.
4549 The heading will be a subentry to the current date. There doesn't
4550 need to be a heading, but there always needs to be a slash after
4551 datetree. For example, to store archived items directly in the
4552 datetree, use \"~/org/datetree.org::datetree/\".
4554 \"basement::** Finished Tasks\"
4555 Archive in file ./basement (relative path), as level 3 trees
4556 below the level 2 heading \"** Finished Tasks\".
4558 You may set this option on a per-file basis by adding to the buffer a
4559 line like
4561 #+ARCHIVE: basement::** Finished Tasks
4563 You may also define it locally for a subtree by setting an ARCHIVE property
4564 in the entry. If such a property is found in an entry, or anywhere up
4565 the hierarchy, it will be used."
4566 :group 'org-archive
4567 :type 'string)
4569 (defcustom org-agenda-skip-archived-trees t
4570 "Non-nil means the agenda will skip any items located in archived trees.
4571 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4572 variable is no longer recommended, you should leave it at the value t.
4573 Instead, use the key `v' to cycle the archives-mode in the agenda."
4574 :group 'org-archive
4575 :group 'org-agenda-skip
4576 :type 'boolean)
4578 (defcustom org-columns-skip-archived-trees t
4579 "Non-nil means ignore archived trees when creating column view."
4580 :group 'org-archive
4581 :group 'org-properties
4582 :type 'boolean)
4584 (defcustom org-cycle-open-archived-trees nil
4585 "Non-nil means `org-cycle' will open archived trees.
4586 An archived tree is a tree marked with the tag ARCHIVE.
4587 When nil, archived trees will stay folded. You can still open them with
4588 normal outline commands like `show-all', but not with the cycling commands."
4589 :group 'org-archive
4590 :group 'org-cycle
4591 :type 'boolean)
4593 (defcustom org-sparse-tree-open-archived-trees nil
4594 "Non-nil means sparse tree construction shows matches in archived trees.
4595 When nil, matches in these trees are highlighted, but the trees are kept in
4596 collapsed state."
4597 :group 'org-archive
4598 :group 'org-sparse-trees
4599 :type 'boolean)
4601 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4602 "The default date type when building a sparse tree.
4603 When this is nil, a date is a scheduled or a deadline timestamp.
4604 Otherwise, these types are allowed:
4606 all: all timestamps
4607 active: only active timestamps (<...>)
4608 inactive: only inactive timestamps (<...)
4609 scheduled: only scheduled timestamps
4610 deadline: only deadline timestamps"
4611 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4612 (const :tag "All timestamps" all)
4613 (const :tag "Only active timestamps" active)
4614 (const :tag "Only inactive timestamps" inactive)
4615 (const :tag "Only scheduled timestamps" scheduled)
4616 (const :tag "Only deadline timestamps" deadline)
4617 (const :tag "Only closed timestamps" closed))
4618 :version "24.3"
4619 :group 'org-sparse-trees)
4621 (defun org-cycle-hide-archived-subtrees (state)
4622 "Re-hide all archived subtrees after a visibility state change."
4623 (when (and (not org-cycle-open-archived-trees)
4624 (not (memq state '(overview folded))))
4625 (save-excursion
4626 (let* ((globalp (memq state '(contents all)))
4627 (beg (if globalp (point-min) (point)))
4628 (end (if globalp (point-max) (org-end-of-subtree t))))
4629 (org-hide-archived-subtrees beg end)
4630 (goto-char beg)
4631 (if (looking-at (concat ".*:" org-archive-tag ":"))
4632 (message "%s" (substitute-command-keys
4633 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4635 (defun org-force-cycle-archived ()
4636 "Cycle subtree even if it is archived."
4637 (interactive)
4638 (setq this-command 'org-cycle)
4639 (let ((org-cycle-open-archived-trees t))
4640 (call-interactively 'org-cycle)))
4642 (defun org-hide-archived-subtrees (beg end)
4643 "Re-hide all archived subtrees after a visibility state change."
4644 (save-excursion
4645 (let* ((re (concat ":" org-archive-tag ":")))
4646 (goto-char beg)
4647 (while (re-search-forward re end t)
4648 (when (org-at-heading-p)
4649 (org-flag-subtree t)
4650 (org-end-of-subtree t))))))
4652 (declare-function outline-end-of-heading "outline" ())
4653 (declare-function outline-flag-region "outline" (from to flag))
4654 (defun org-flag-subtree (flag)
4655 (save-excursion
4656 (org-back-to-heading t)
4657 (outline-end-of-heading)
4658 (outline-flag-region (point)
4659 (progn (org-end-of-subtree t) (point))
4660 flag)))
4662 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4664 ;; Declare Column View Code
4666 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4667 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4668 (declare-function org-columns-compute "org-colview" (property))
4670 ;; Declare ID code
4672 (declare-function org-id-store-link "org-id")
4673 (declare-function org-id-locations-load "org-id")
4674 (declare-function org-id-locations-save "org-id")
4675 (defvar org-id-track-globally)
4677 ;;; Variables for pre-computed regular expressions, all buffer local
4679 (defvar org-todo-regexp nil
4680 "Matches any of the TODO state keywords.")
4681 (make-variable-buffer-local 'org-todo-regexp)
4682 (defvar org-not-done-regexp nil
4683 "Matches any of the TODO state keywords except the last one.")
4684 (make-variable-buffer-local 'org-not-done-regexp)
4685 (defvar org-not-done-heading-regexp nil
4686 "Matches a TODO headline that is not done.")
4687 (make-variable-buffer-local 'org-not-done-regexp)
4688 (defvar org-todo-line-regexp nil
4689 "Matches a headline and puts TODO state into group 2 if present.")
4690 (make-variable-buffer-local 'org-todo-line-regexp)
4691 (defvar org-complex-heading-regexp nil
4692 "Matches a headline and puts everything into groups:
4693 group 1: the stars
4694 group 2: The todo keyword, maybe
4695 group 3: Priority cookie
4696 group 4: True headline
4697 group 5: Tags")
4698 (make-variable-buffer-local 'org-complex-heading-regexp)
4699 (defvar org-complex-heading-regexp-format nil
4700 "Printf format to make regexp to match an exact headline.
4701 This regexp will match the headline of any node which has the
4702 exact headline text that is put into the format, but may have any
4703 TODO state, priority and tags.")
4704 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4705 (defvar org-todo-line-tags-regexp nil
4706 "Matches a headline and puts TODO state into group 2 if present.
4707 Also put tags into group 4 if tags are present.")
4708 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4709 (defvar org-ds-keyword-length 12
4710 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4711 (make-variable-buffer-local 'org-ds-keyword-length)
4712 (defvar org-deadline-regexp nil
4713 "Matches the DEADLINE keyword.")
4714 (make-variable-buffer-local 'org-deadline-regexp)
4715 (defvar org-deadline-time-regexp nil
4716 "Matches the DEADLINE keyword together with a time stamp.")
4717 (make-variable-buffer-local 'org-deadline-time-regexp)
4718 (defvar org-deadline-time-hour-regexp nil
4719 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4720 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4721 (defvar org-deadline-line-regexp nil
4722 "Matches the DEADLINE keyword and the rest of the line.")
4723 (make-variable-buffer-local 'org-deadline-line-regexp)
4724 (defvar org-scheduled-regexp nil
4725 "Matches the SCHEDULED keyword.")
4726 (make-variable-buffer-local 'org-scheduled-regexp)
4727 (defvar org-scheduled-time-regexp nil
4728 "Matches the SCHEDULED keyword together with a time stamp.")
4729 (make-variable-buffer-local 'org-scheduled-time-regexp)
4730 (defvar org-scheduled-time-hour-regexp nil
4731 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4732 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4733 (defvar org-closed-time-regexp nil
4734 "Matches the CLOSED keyword together with a time stamp.")
4735 (make-variable-buffer-local 'org-closed-time-regexp)
4737 (defvar org-keyword-time-regexp nil
4738 "Matches any of the 4 keywords, together with the time stamp.")
4739 (make-variable-buffer-local 'org-keyword-time-regexp)
4740 (defvar org-keyword-time-not-clock-regexp nil
4741 "Matches any of the 3 keywords, together with the time stamp.")
4742 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4743 (defvar org-maybe-keyword-time-regexp nil
4744 "Matches a timestamp, possibly preceded by a keyword.")
4745 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4746 (defvar org-all-time-keywords nil
4747 "List of time keywords.")
4748 (make-variable-buffer-local 'org-all-time-keywords)
4750 (defconst org-plain-time-of-day-regexp
4751 (concat
4752 "\\(\\<[012]?[0-9]"
4753 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4754 "\\(--?"
4755 "\\(\\<[012]?[0-9]"
4756 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4757 "\\)?")
4758 "Regular expression to match a plain time or time range.
4759 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4760 groups carry important information:
4761 0 the full match
4762 1 the first time, range or not
4763 8 the second time, if it is a range.")
4765 (defconst org-plain-time-extension-regexp
4766 (concat
4767 "\\(\\<[012]?[0-9]"
4768 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4769 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4770 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4771 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4772 groups carry important information:
4773 0 the full match
4774 7 hours of duration
4775 9 minutes of duration")
4777 (defconst org-stamp-time-of-day-regexp
4778 (concat
4779 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4780 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4781 "\\(--?"
4782 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4783 "Regular expression to match a timestamp time or time range.
4784 After a match, the following groups carry important information:
4785 0 the full match
4786 1 date plus weekday, for back referencing to make sure both times are on the same day
4787 2 the first time, range or not
4788 4 the second time, if it is a range.")
4790 (defconst org-startup-options
4791 '(("fold" org-startup-folded t)
4792 ("overview" org-startup-folded t)
4793 ("nofold" org-startup-folded nil)
4794 ("showall" org-startup-folded nil)
4795 ("showeverything" org-startup-folded showeverything)
4796 ("content" org-startup-folded content)
4797 ("indent" org-startup-indented t)
4798 ("noindent" org-startup-indented nil)
4799 ("hidestars" org-hide-leading-stars t)
4800 ("showstars" org-hide-leading-stars nil)
4801 ("odd" org-odd-levels-only t)
4802 ("oddeven" org-odd-levels-only nil)
4803 ("align" org-startup-align-all-tables t)
4804 ("noalign" org-startup-align-all-tables nil)
4805 ("inlineimages" org-startup-with-inline-images t)
4806 ("noinlineimages" org-startup-with-inline-images nil)
4807 ("latexpreview" org-startup-with-latex-preview t)
4808 ("nolatexpreview" org-startup-with-latex-preview nil)
4809 ("customtime" org-display-custom-times t)
4810 ("logdone" org-log-done time)
4811 ("lognotedone" org-log-done note)
4812 ("nologdone" org-log-done nil)
4813 ("lognoteclock-out" org-log-note-clock-out t)
4814 ("nolognoteclock-out" org-log-note-clock-out nil)
4815 ("logrepeat" org-log-repeat state)
4816 ("lognoterepeat" org-log-repeat note)
4817 ("logdrawer" org-log-into-drawer t)
4818 ("nologdrawer" org-log-into-drawer nil)
4819 ("logstatesreversed" org-log-states-order-reversed t)
4820 ("nologstatesreversed" org-log-states-order-reversed nil)
4821 ("nologrepeat" org-log-repeat nil)
4822 ("logreschedule" org-log-reschedule time)
4823 ("lognotereschedule" org-log-reschedule note)
4824 ("nologreschedule" org-log-reschedule nil)
4825 ("logredeadline" org-log-redeadline time)
4826 ("lognoteredeadline" org-log-redeadline note)
4827 ("nologredeadline" org-log-redeadline nil)
4828 ("logrefile" org-log-refile time)
4829 ("lognoterefile" org-log-refile note)
4830 ("nologrefile" org-log-refile nil)
4831 ("fninline" org-footnote-define-inline t)
4832 ("nofninline" org-footnote-define-inline nil)
4833 ("fnlocal" org-footnote-section nil)
4834 ("fnauto" org-footnote-auto-label t)
4835 ("fnprompt" org-footnote-auto-label nil)
4836 ("fnconfirm" org-footnote-auto-label confirm)
4837 ("fnplain" org-footnote-auto-label plain)
4838 ("fnadjust" org-footnote-auto-adjust t)
4839 ("nofnadjust" org-footnote-auto-adjust nil)
4840 ("constcgs" constants-unit-system cgs)
4841 ("constSI" constants-unit-system SI)
4842 ("noptag" org-tag-persistent-alist nil)
4843 ("hideblocks" org-hide-block-startup t)
4844 ("nohideblocks" org-hide-block-startup nil)
4845 ("beamer" org-startup-with-beamer-mode t)
4846 ("entitiespretty" org-pretty-entities t)
4847 ("entitiesplain" org-pretty-entities nil))
4848 "Variable associated with STARTUP options for org-mode.
4849 Each element is a list of three items: the startup options (as written
4850 in the #+STARTUP line), the corresponding variable, and the value to set
4851 this variable to if the option is found. An optional forth element PUSH
4852 means to push this value onto the list in the variable.")
4854 (defun org-update-property-plist (key val props)
4855 "Update PROPS with KEY and VAL."
4856 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4857 (key (if appending (substring key 0 (- (length key) 1)) key))
4858 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4859 (previous (cdr (assoc key props))))
4860 (if appending
4861 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4862 (cons (cons key val) remainder))))
4864 (defcustom org-group-tags t
4865 "When non-nil (the default), use group tags.
4866 This can be turned on/off through `org-toggle-tags-groups'."
4867 :group 'org-tags
4868 :group 'org-startup
4869 :type 'boolean)
4871 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4873 (defun org-toggle-tags-groups ()
4874 "Toggle support for group tags.
4875 Support for group tags is controlled by the option
4876 `org-group-tags', which is non-nil by default."
4877 (interactive)
4878 (setq org-group-tags (not org-group-tags))
4879 (cond ((and (derived-mode-p 'org-agenda-mode)
4880 org-group-tags)
4881 (org-agenda-redo))
4882 ((derived-mode-p 'org-mode)
4883 (let ((org-inhibit-startup t)) (org-mode))))
4884 (message "Groups tags support has been turned %s"
4885 (if org-group-tags "on" "off")))
4887 (defun org-set-regexps-and-options-for-tags ()
4888 "Precompute variables used for tags."
4889 (when (derived-mode-p 'org-mode)
4890 (org-set-local 'org-file-tags nil)
4891 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4892 (splitre "[ \t]+")
4893 (start 0)
4894 tags ftags key value)
4895 (save-excursion
4896 (save-restriction
4897 (widen)
4898 (goto-char (point-min))
4899 (while (re-search-forward re nil t)
4900 (setq key (upcase (org-match-string-no-properties 1))
4901 value (org-match-string-no-properties 2))
4902 (if (stringp value) (setq value (org-trim value)))
4903 (cond
4904 ((equal key "TAGS")
4905 (setq tags (append tags (if tags '("\\n") nil)
4906 (org-split-string value splitre))))
4907 ((equal key "FILETAGS")
4908 (when (string-match "\\S-" value)
4909 (setq ftags
4910 (append
4911 ftags
4912 (apply 'append
4913 (mapcar (lambda (x) (org-split-string x ":"))
4914 (org-split-string value)))))))))))
4915 ;; Process the file tags.
4916 (and ftags (org-set-local 'org-file-tags
4917 (mapcar 'org-add-prop-inherited ftags)))
4918 (org-set-local 'org-tag-groups-alist nil)
4919 ;; Process the tags.
4920 (when (and (not tags) org-tag-alist)
4921 (setq tags
4922 (mapcar
4923 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4924 ((eq (car tg) :endgroup) "}")
4925 ((eq (car tg) :grouptags) ":")
4926 ((eq (car tg) :newline) "\n")
4927 (t (concat (car tg)
4928 (if (characterp (cdr tg))
4929 (format "(%s)" (char-to-string (cdr tg))) "")))))
4930 org-tag-alist)))
4931 (let (e tgs g)
4932 (while (setq e (pop tags))
4933 (cond
4934 ((equal e "{")
4935 (progn (push '(:startgroup) tgs)
4936 (when (equal (nth 1 tags) ":")
4937 (push (list (replace-regexp-in-string
4938 "(.+)$" "" (nth 0 tags)))
4939 org-tag-groups-alist)
4940 (setq g 0))))
4941 ((equal e ":") (push '(:grouptags) tgs))
4942 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4943 ((equal e "\\n") (push '(:newline) tgs))
4944 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4945 (push (cons (match-string 1 e)
4946 (string-to-char (match-string 2 e))) tgs)
4947 (if (and g (> g 0))
4948 (setcar org-tag-groups-alist
4949 (append (car org-tag-groups-alist)
4950 (list (match-string 1 e)))))
4951 (if g (setq g (1+ g))))
4952 (t (push (list e) tgs)
4953 (if (and g (> g 0))
4954 (setcar org-tag-groups-alist
4955 (append (car org-tag-groups-alist) (list e))))
4956 (if g (setq g (1+ g))))))
4957 (org-set-local 'org-tag-alist nil)
4958 (while (setq e (pop tgs))
4959 (or (and (stringp (car e))
4960 (assoc (car e) org-tag-alist))
4961 (push e org-tag-alist)))
4962 ;; Return a list with tag variables
4963 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4965 (defvar org-ota nil)
4966 (defun org-set-regexps-and-options ()
4967 "Precompute regular expressions used in the current buffer."
4968 (when (derived-mode-p 'org-mode)
4969 (org-set-local 'org-todo-kwd-alist nil)
4970 (org-set-local 'org-todo-key-alist nil)
4971 (org-set-local 'org-todo-key-trigger nil)
4972 (org-set-local 'org-todo-keywords-1 nil)
4973 (org-set-local 'org-done-keywords nil)
4974 (org-set-local 'org-todo-heads nil)
4975 (org-set-local 'org-todo-sets nil)
4976 (org-set-local 'org-todo-log-states nil)
4977 (org-set-local 'org-file-properties nil)
4978 (let ((re (org-make-options-regexp
4979 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4980 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4981 "SETUPFILE" "OPTIONS")
4982 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4983 (splitre "[ \t]+")
4984 (scripts org-use-sub-superscripts)
4985 kwds kws0 kwsa key log value cat arch const links hw dws
4986 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4987 (start 0))
4988 (save-excursion
4989 (save-restriction
4990 (widen)
4991 (goto-char (point-min))
4992 (while
4993 (or (and
4994 ext-setup-or-nil
4995 (not org-ota)
4996 (let (ret)
4997 (with-temp-buffer
4998 (insert ext-setup-or-nil)
4999 (let ((major-mode 'org-mode) org-ota)
5000 (setq ret (save-match-data
5001 (org-set-regexps-and-options-for-tags)))))
5002 ;; Append setupfile tags to existing tags
5003 (setq org-ota t)
5004 (setq org-file-tags
5005 (delq nil (append org-file-tags (nth 0 ret)))
5006 org-tag-alist
5007 (delq nil (append org-tag-alist (nth 1 ret)))
5008 org-tag-groups-alist
5009 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5010 (and ext-setup-or-nil
5011 (string-match re ext-setup-or-nil start)
5012 (setq start (match-end 0)))
5013 (and (setq ext-setup-or-nil nil start 0)
5014 (re-search-forward re nil t)))
5015 (setq key (upcase (match-string 1 ext-setup-or-nil))
5016 value (org-match-string-no-properties 2 ext-setup-or-nil))
5017 (if (stringp value) (setq value (org-trim value)))
5018 (cond
5019 ((equal key "CATEGORY")
5020 (setq cat value))
5021 ((member key '("SEQ_TODO" "TODO"))
5022 (push (cons 'sequence (org-split-string value splitre)) kwds))
5023 ((equal key "TYP_TODO")
5024 (push (cons 'type (org-split-string value splitre)) kwds))
5025 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5026 ;; general TODO-like setup
5027 (push (cons (intern (downcase (match-string 1 key)))
5028 (org-split-string value splitre)) kwds))
5029 ((equal key "COLUMNS")
5030 (org-set-local 'org-columns-default-format value))
5031 ((equal key "LINK")
5032 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5033 (push (cons (match-string 1 value)
5034 (org-trim (match-string 2 value)))
5035 links)))
5036 ((equal key "PRIORITIES")
5037 (setq prio (org-split-string value " +")))
5038 ((equal key "PROPERTY")
5039 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5040 (setq props (org-update-property-plist (match-string 1 value)
5041 (match-string 2 value)
5042 props))))
5043 ((equal key "CONSTANTS")
5044 (org-table-set-constants))
5045 ((equal key "STARTUP")
5046 (let ((opts (org-split-string value splitre))
5047 l var val)
5048 (while (setq l (pop opts))
5049 (when (setq l (assoc l org-startup-options))
5050 (setq var (nth 1 l) val (nth 2 l))
5051 (if (not (nth 3 l))
5052 (set (make-local-variable var) val)
5053 (if (not (listp (symbol-value var)))
5054 (set (make-local-variable var) nil))
5055 (set (make-local-variable var) (symbol-value var))
5056 (add-to-list var val))))))
5057 ((equal key "ARCHIVE")
5058 (setq arch value)
5059 (remove-text-properties 0 (length arch)
5060 '(face t fontified t) arch))
5061 ((equal key "OPTIONS")
5062 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5063 (setq scripts (read (match-string 2 value)))))
5064 ((and (equal key "SETUPFILE")
5065 ;; Prevent checking in Gnus messages
5066 (not buffer-read-only))
5067 (setq setup-contents (org-file-contents
5068 (expand-file-name
5069 (org-remove-double-quotes value))
5070 'noerror))
5071 (if (not ext-setup-or-nil)
5072 (setq ext-setup-or-nil setup-contents start 0)
5073 (setq ext-setup-or-nil
5074 (concat (substring ext-setup-or-nil 0 start)
5075 "\n" setup-contents "\n"
5076 (substring ext-setup-or-nil start)))))))
5077 ;; search for property blocks
5078 (goto-char (point-min))
5079 (while (re-search-forward org-block-regexp nil t)
5080 (when (equal "PROPERTY" (upcase (match-string 1)))
5081 (setq value (replace-regexp-in-string
5082 "[\n\r]" " " (match-string 4)))
5083 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5084 (setq props (org-update-property-plist (match-string 1 value)
5085 (match-string 2 value)
5086 props)))))))
5087 (org-set-local 'org-use-sub-superscripts scripts)
5088 (when cat
5089 (org-set-local 'org-category (intern cat))
5090 (push (cons "CATEGORY" cat) props))
5091 (when prio
5092 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5093 (setq prio (mapcar 'string-to-char prio))
5094 (org-set-local 'org-highest-priority (nth 0 prio))
5095 (org-set-local 'org-lowest-priority (nth 1 prio))
5096 (org-set-local 'org-default-priority (nth 2 prio)))
5097 (and props (org-set-local 'org-file-properties (nreverse props)))
5098 (and arch (org-set-local 'org-archive-location arch))
5099 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5100 ;; Process the TODO keywords
5101 (unless kwds
5102 ;; Use the global values as if they had been given locally.
5103 (setq kwds (default-value 'org-todo-keywords))
5104 (if (stringp (car kwds))
5105 (setq kwds (list (cons org-todo-interpretation
5106 (default-value 'org-todo-keywords)))))
5107 (setq kwds (reverse kwds)))
5108 (setq kwds (nreverse kwds))
5109 (let (inter kws kw)
5110 (while (setq kws (pop kwds))
5111 (let ((kws (or
5112 (run-hook-with-args-until-success
5113 'org-todo-setup-filter-hook kws)
5114 kws)))
5115 (setq inter (pop kws) sep (member "|" kws)
5116 kws0 (delete "|" (copy-sequence kws))
5117 kwsa nil
5118 kws1 (mapcar
5119 (lambda (x)
5120 ;; 1 2
5121 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5122 (progn
5123 (setq kw (match-string 1 x)
5124 key (and (match-end 2) (match-string 2 x))
5125 log (org-extract-log-state-settings x))
5126 (push (cons kw (and key (string-to-char key))) kwsa)
5127 (and log (push log org-todo-log-states))
5129 (error "Invalid TODO keyword %s" x)))
5130 kws0)
5131 kwsa (if kwsa (append '((:startgroup))
5132 (nreverse kwsa)
5133 '((:endgroup))))
5134 hw (car kws1)
5135 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5136 tail (list inter hw (car dws) (org-last dws))))
5137 (add-to-list 'org-todo-heads hw 'append)
5138 (push kws1 org-todo-sets)
5139 (setq org-done-keywords (append org-done-keywords dws nil))
5140 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5141 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5142 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5143 (setq org-todo-sets (nreverse org-todo-sets)
5144 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5145 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5146 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5147 ;; Compute the regular expressions and other local variables.
5148 ;; Using `org-outline-regexp-bol' would complicate them much,
5149 ;; because of the fixed white space at the end of that string.
5150 (if (not org-done-keywords)
5151 (setq org-done-keywords (and org-todo-keywords-1
5152 (list (org-last org-todo-keywords-1)))))
5153 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5154 (length org-scheduled-string)
5155 (length org-clock-string)
5156 (length org-closed-string)))
5157 org-not-done-keywords
5158 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5159 org-todo-regexp
5160 (concat "\\("
5161 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5162 "\\)")
5163 org-not-done-regexp
5164 (concat "\\("
5165 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5166 "\\)")
5167 org-not-done-heading-regexp
5168 (format org-heading-keyword-regexp-format org-not-done-regexp)
5169 org-todo-line-regexp
5170 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5171 org-complex-heading-regexp
5172 (concat "^\\(\\*+\\)"
5173 "\\(?: +" org-todo-regexp "\\)?"
5174 "\\(?: +\\(\\[#.\\]\\)\\)?"
5175 "\\(?: +\\(.*?\\)\\)??"
5176 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5177 "[ \t]*$")
5178 org-complex-heading-regexp-format
5179 (concat "^\\(\\*+\\)"
5180 "\\(?: +" org-todo-regexp "\\)?"
5181 "\\(?: +\\(\\[#.\\]\\)\\)?"
5182 "\\(?: +"
5183 ;; Stats cookies can be stuck to body.
5184 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5185 "\\(%s\\)"
5186 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5187 "\\)"
5188 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5189 "[ \t]*$")
5190 org-todo-line-tags-regexp
5191 (concat "^\\(\\*+\\)"
5192 "\\(?: +" org-todo-regexp "\\)?"
5193 "\\(?: +\\(.*?\\)\\)??"
5194 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5195 "[ \t]*$")
5196 org-deadline-regexp (concat "\\<" org-deadline-string)
5197 org-deadline-time-regexp
5198 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5199 org-deadline-time-hour-regexp
5200 (concat "\\<" org-deadline-string
5201 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5202 org-deadline-line-regexp
5203 (concat "\\<\\(" org-deadline-string "\\).*")
5204 org-scheduled-regexp
5205 (concat "\\<" org-scheduled-string)
5206 org-scheduled-time-regexp
5207 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5208 org-scheduled-time-hour-regexp
5209 (concat "\\<" org-scheduled-string
5210 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5211 org-closed-time-regexp
5212 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5213 org-keyword-time-regexp
5214 (concat "\\<\\(" org-scheduled-string
5215 "\\|" org-deadline-string
5216 "\\|" org-closed-string
5217 "\\|" org-clock-string "\\)"
5218 " *[[<]\\([^]>]+\\)[]>]")
5219 org-keyword-time-not-clock-regexp
5220 (concat "\\<\\(" org-scheduled-string
5221 "\\|" org-deadline-string
5222 "\\|" org-closed-string
5223 "\\)"
5224 " *[[<]\\([^]>]+\\)[]>]")
5225 org-maybe-keyword-time-regexp
5226 (concat "\\(\\<\\(" org-scheduled-string
5227 "\\|" org-deadline-string
5228 "\\|" org-closed-string
5229 "\\|" org-clock-string "\\)\\)?"
5230 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5231 org-all-time-keywords
5232 (mapcar (lambda (w) (substring w 0 -1))
5233 (list org-scheduled-string org-deadline-string
5234 org-clock-string org-closed-string)))
5235 (setq org-ota nil)
5236 (org-compute-latex-and-related-regexp))))
5238 (defun org-file-contents (file &optional noerror)
5239 "Return the contents of FILE, as a string."
5240 (if (and file (file-readable-p file))
5241 (with-temp-buffer
5242 (insert-file-contents file)
5243 (buffer-string))
5244 (funcall (if noerror #'message #'error)
5245 "Cannot read file \"%s\"%s"
5246 file
5247 (let ((from (buffer-file-name (buffer-base-buffer))))
5248 (if from (concat " (referenced in file \"" from "\")") "")))))
5250 (defun org-extract-log-state-settings (x)
5251 "Extract the log state setting from a TODO keyword string.
5252 This will extract info from a string like \"WAIT(w@/!)\"."
5253 (let (kw key log1 log2)
5254 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5255 (setq kw (match-string 1 x)
5256 key (and (match-end 2) (match-string 2 x))
5257 log1 (and (match-end 3) (match-string 3 x))
5258 log2 (and (match-end 4) (match-string 4 x)))
5259 (and (or log1 log2)
5260 (list kw
5261 (and log1 (if (equal log1 "!") 'time 'note))
5262 (and log2 (if (equal log2 "!") 'time 'note)))))))
5264 (defun org-remove-keyword-keys (list)
5265 "Remove a pair of parenthesis at the end of each string in LIST."
5266 (mapcar (lambda (x)
5267 (if (string-match "(.*)$" x)
5268 (substring x 0 (match-beginning 0))
5270 list))
5272 (defun org-assign-fast-keys (alist)
5273 "Assign fast keys to a keyword-key alist.
5274 Respect keys that are already there."
5275 (let (new e (alt ?0))
5276 (while (setq e (pop alist))
5277 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5278 (cdr e)) ;; Key already assigned.
5279 (push e new)
5280 (let ((clist (string-to-list (downcase (car e))))
5281 (used (append new alist)))
5282 (when (= (car clist) ?@)
5283 (pop clist))
5284 (while (and clist (rassoc (car clist) used))
5285 (pop clist))
5286 (unless clist
5287 (while (rassoc alt used)
5288 (incf alt)))
5289 (push (cons (car e) (or (car clist) alt)) new))))
5290 (nreverse new)))
5292 ;;; Some variables used in various places
5294 (defvar org-window-configuration nil
5295 "Used in various places to store a window configuration.")
5296 (defvar org-selected-window nil
5297 "Used in various places to store a window configuration.")
5298 (defvar org-finish-function nil
5299 "Function to be called when `C-c C-c' is used.
5300 This is for getting out of special buffers like capture.")
5303 ;; FIXME: Occasionally check by commenting these, to make sure
5304 ;; no other functions uses these, forgetting to let-bind them.
5305 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5306 (defvar org-last-state)
5307 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5309 ;; Defined somewhere in this file, but used before definition.
5310 (defvar org-entities) ;; defined in org-entities.el
5311 (defvar org-struct-menu)
5312 (defvar org-org-menu)
5313 (defvar org-tbl-menu)
5315 ;;;; Define the Org-mode
5317 ;; We use a before-change function to check if a table might need
5318 ;; an update.
5319 (defvar org-table-may-need-update t
5320 "Indicates that a table might need an update.
5321 This variable is set by `org-before-change-function'.
5322 `org-table-align' sets it back to nil.")
5323 (defun org-before-change-function (beg end)
5324 "Every change indicates that a table might need an update."
5325 (setq org-table-may-need-update t))
5326 (defvar org-mode-map)
5327 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5328 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5329 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5330 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5331 (defvar org-table-buffer-is-an nil)
5333 (defvar bidi-paragraph-direction)
5334 (defvar buffer-face-mode-face)
5336 (require 'outline)
5337 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5338 (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"))
5339 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5341 ;; Other stuff we need.
5342 (require 'time-date)
5343 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5344 (require 'easymenu)
5345 (require 'overlay)
5347 ;; (require 'org-macs) moved higher up in the file before it is first used
5348 (require 'org-entities)
5349 ;; (require 'org-compat) moved higher up in the file before it is first used
5350 (require 'org-faces)
5351 (require 'org-list)
5352 (require 'org-pcomplete)
5353 (require 'org-src)
5354 (require 'org-footnote)
5355 (require 'org-macro)
5357 ;; babel
5358 (require 'ob)
5360 ;;;###autoload
5361 (define-derived-mode org-mode outline-mode "Org"
5362 "Outline-based notes management and organizer, alias
5363 \"Carsten's outline-mode for keeping track of everything.\"
5365 Org-mode develops organizational tasks around a NOTES file which
5366 contains information about projects as plain text. Org-mode is
5367 implemented on top of outline-mode, which is ideal to keep the content
5368 of large files well structured. It supports ToDo items, deadlines and
5369 time stamps, which magically appear in the diary listing of the Emacs
5370 calendar. Tables are easily created with a built-in table editor.
5371 Plain text URL-like links connect to websites, emails (VM), Usenet
5372 messages (Gnus), BBDB entries, and any files related to the project.
5373 For printing and sharing of notes, an Org-mode file (or a part of it)
5374 can be exported as a structured ASCII or HTML file.
5376 The following commands are available:
5378 \\{org-mode-map}"
5380 ;; Get rid of Outline menus, they are not needed
5381 ;; Need to do this here because define-derived-mode sets up
5382 ;; the keymap so late. Still, it is a waste to call this each time
5383 ;; we switch another buffer into org-mode.
5384 (if (featurep 'xemacs)
5385 (when (boundp 'outline-mode-menu-heading)
5386 ;; Assume this is Greg's port, it uses easymenu
5387 (easy-menu-remove outline-mode-menu-heading)
5388 (easy-menu-remove outline-mode-menu-show)
5389 (easy-menu-remove outline-mode-menu-hide))
5390 (define-key org-mode-map [menu-bar headings] 'undefined)
5391 (define-key org-mode-map [menu-bar hide] 'undefined)
5392 (define-key org-mode-map [menu-bar show] 'undefined))
5394 (org-load-modules-maybe)
5395 (easy-menu-add org-org-menu)
5396 (easy-menu-add org-tbl-menu)
5397 (org-install-agenda-files-menu)
5398 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5399 (add-to-invisibility-spec '(org-cwidth))
5400 (add-to-invisibility-spec '(org-hide-block . t))
5401 (when (featurep 'xemacs)
5402 (org-set-local 'line-move-ignore-invisible t))
5403 (org-set-local 'outline-regexp org-outline-regexp)
5404 (org-set-local 'outline-level 'org-outline-level)
5405 (setq bidi-paragraph-direction 'left-to-right)
5406 (when (and org-ellipsis
5407 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5408 (fboundp 'make-glyph-code))
5409 (unless org-display-table
5410 (setq org-display-table (make-display-table)))
5411 (set-display-table-slot
5412 org-display-table 4
5413 (vconcat (mapcar
5414 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5415 org-ellipsis)))
5416 (if (stringp org-ellipsis) org-ellipsis "..."))))
5417 (setq buffer-display-table org-display-table))
5418 (org-set-regexps-and-options-for-tags)
5419 (org-set-regexps-and-options)
5420 (org-set-font-lock-defaults)
5421 (when (and org-tag-faces (not org-tags-special-faces-re))
5422 ;; tag faces set outside customize.... force initialization.
5423 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5424 ;; Calc embedded
5425 (org-set-local 'calc-embedded-open-mode "# ")
5426 ;; Modify a few syntax entries
5427 (modify-syntax-entry ?@ "w")
5428 (modify-syntax-entry ?\" "\"")
5429 (modify-syntax-entry ?\\ "_")
5430 (modify-syntax-entry ?~ "_")
5431 (if org-startup-truncated (setq truncate-lines t))
5432 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5433 (org-set-local 'font-lock-unfontify-region-function
5434 'org-unfontify-region)
5435 ;; Activate before-change-function
5436 (org-set-local 'org-table-may-need-update t)
5437 (org-add-hook 'before-change-functions 'org-before-change-function nil
5438 'local)
5439 ;; Check for running clock before killing a buffer
5440 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5441 ;; Initialize macros templates.
5442 (org-macro-initialize-templates)
5443 ;; Initialize radio targets.
5444 (org-update-radio-target-regexp)
5445 ;; Indentation.
5446 (org-set-local 'indent-line-function 'org-indent-line)
5447 (org-set-local 'indent-region-function 'org-indent-region)
5448 ;; Filling and auto-filling.
5449 (org-setup-filling)
5450 ;; Comments.
5451 (org-setup-comments-handling)
5452 ;; Initialize cache.
5453 (org-element-cache-reset)
5454 ;; Beginning/end of defun
5455 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5456 (org-set-local 'end-of-defun-function
5457 (lambda ()
5458 (if (not (org-at-heading-p))
5459 (org-forward-element)
5460 (org-forward-element)
5461 (forward-char -1))))
5462 ;; Next error for sparse trees
5463 (org-set-local 'next-error-function 'org-occur-next-match)
5464 ;; Make sure dependence stuff works reliably, even for users who set it
5465 ;; too late :-(
5466 (if org-enforce-todo-dependencies
5467 (add-hook 'org-blocker-hook
5468 'org-block-todo-from-children-or-siblings-or-parent)
5469 (remove-hook 'org-blocker-hook
5470 'org-block-todo-from-children-or-siblings-or-parent))
5471 (if org-enforce-todo-checkbox-dependencies
5472 (add-hook 'org-blocker-hook
5473 'org-block-todo-from-checkboxes)
5474 (remove-hook 'org-blocker-hook
5475 'org-block-todo-from-checkboxes))
5477 ;; Align options lines
5478 (org-set-local
5479 'align-mode-rules-list
5480 '((org-in-buffer-settings
5481 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5482 (modes . '(org-mode)))))
5484 ;; Imenu
5485 (org-set-local 'imenu-create-index-function
5486 'org-imenu-get-tree)
5488 ;; Make isearch reveal context
5489 (if (or (featurep 'xemacs)
5490 (not (boundp 'outline-isearch-open-invisible-function)))
5491 ;; Emacs 21 and XEmacs make use of the hook
5492 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5493 ;; Emacs 22 deals with this through a special variable
5494 (org-set-local 'outline-isearch-open-invisible-function
5495 (lambda (&rest ignore) (org-show-context 'isearch)))
5496 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5498 ;; Setup the pcomplete hooks
5499 (set (make-local-variable 'pcomplete-command-completion-function)
5500 'org-pcomplete-initial)
5501 (set (make-local-variable 'pcomplete-command-name-function)
5502 'org-command-at-point)
5503 (set (make-local-variable 'pcomplete-default-completion-function)
5504 'ignore)
5505 (set (make-local-variable 'pcomplete-parse-arguments-function)
5506 'org-parse-arguments)
5507 (set (make-local-variable 'pcomplete-termination-string) "")
5508 (when (>= emacs-major-version 23)
5509 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5511 ;; If empty file that did not turn on org-mode automatically, make it to.
5512 (if (and org-insert-mode-line-in-empty-file
5513 (org-called-interactively-p 'any)
5514 (= (point-min) (point-max)))
5515 (insert "# -*- mode: org -*-\n\n"))
5516 (unless org-inhibit-startup
5517 (org-unmodified
5518 (and org-startup-with-beamer-mode (org-beamer-mode))
5519 (when org-startup-align-all-tables
5520 (org-table-map-tables 'org-table-align 'quietly))
5521 (when org-startup-with-inline-images
5522 (org-display-inline-images))
5523 (when org-startup-with-latex-preview
5524 (org-preview-latex-fragment))
5525 (unless org-inhibit-startup-visibility-stuff
5526 (org-set-startup-visibility))))
5527 ;; Try to set org-hide correctly
5528 (let ((foreground (org-find-invisible-foreground)))
5529 (if foreground
5530 (set-face-foreground 'org-hide foreground))))
5532 ;; Update `customize-package-emacs-version-alist'
5533 (add-to-list 'customize-package-emacs-version-alist
5534 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5535 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5536 ("8.2.6" . "24.4")))
5538 (defvar org-mode-transpose-word-syntax-table
5539 (let ((st (make-syntax-table)))
5540 (mapc (lambda(c) (modify-syntax-entry
5541 (string-to-char (car c)) "w p" st))
5542 org-emphasis-alist)
5543 st))
5545 (when (fboundp 'abbrev-table-put)
5546 (abbrev-table-put org-mode-abbrev-table
5547 :parents (list text-mode-abbrev-table)))
5549 (defsubst org-fix-ellipsis-at-bol ()
5550 (save-excursion (goto-char (window-start)) (recenter 0)))
5552 (defun org-find-invisible-foreground ()
5553 (let ((candidates (remove
5554 "unspecified-bg"
5555 (nconc
5556 (list (face-background 'default)
5557 (face-background 'org-default))
5558 (mapcar
5559 (lambda (alist)
5560 (when (boundp alist)
5561 (cdr (assoc 'background-color (symbol-value alist)))))
5562 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5563 (list (face-foreground 'org-hide))))))
5564 (car (remove nil candidates))))
5566 (defun org-current-time (&optional rounding-minutes past)
5567 "Current time, possibly rounded to ROUNDING-MINUTES.
5568 When ROUNDING-MINUTES is not an integer, fall back on the car of
5569 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5570 the rounding returns a past time."
5571 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5572 (car org-time-stamp-rounding-minutes)))
5573 (time (decode-time)) res)
5574 (if (< r 1)
5575 (current-time)
5576 (setq res
5577 (apply 'encode-time
5578 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5579 (nthcdr 2 time))))
5580 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5581 (seconds-to-time (- (org-float-time res) (* r 60)))
5582 res))))
5584 (defun org-today ()
5585 "Return today date, considering `org-extend-today-until'."
5586 (time-to-days
5587 (time-subtract (current-time)
5588 (list 0 (* 3600 org-extend-today-until) 0))))
5590 ;;;; Font-Lock stuff, including the activators
5592 (defvar org-mouse-map (make-sparse-keymap))
5593 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5594 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5595 (when org-mouse-1-follows-link
5596 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5597 (when org-tab-follows-link
5598 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5599 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5601 (require 'font-lock)
5603 (defconst org-non-link-chars "]\t\n\r<>")
5604 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5605 "file+sys" "news" "shell" "elisp" "doi" "message"
5606 "help"))
5607 (defvar org-link-types-re nil
5608 "Matches a link that has a url-like prefix like \"http:\"")
5609 (defvar org-link-re-with-space nil
5610 "Matches a link with spaces, optional angular brackets around it.")
5611 (defvar org-link-re-with-space2 nil
5612 "Matches a link with spaces, optional angular brackets around it.")
5613 (defvar org-link-re-with-space3 nil
5614 "Matches a link with spaces, only for internal part in bracket links.")
5615 (defvar org-angle-link-re nil
5616 "Matches link with angular brackets, spaces are allowed.")
5617 (defvar org-plain-link-re nil
5618 "Matches plain link, without spaces.")
5619 (defvar org-bracket-link-regexp nil
5620 "Matches a link in double brackets.")
5621 (defvar org-bracket-link-analytic-regexp nil
5622 "Regular expression used to analyze links.
5623 Here is what the match groups contain after a match:
5624 1: http:
5625 2: http
5626 3: path
5627 4: [desc]
5628 5: desc")
5629 (defvar org-bracket-link-analytic-regexp++ nil
5630 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5631 (defvar org-any-link-re nil
5632 "Regular expression matching any link.")
5634 (defconst org-match-sexp-depth 3
5635 "Number of stacked braces for sub/superscript matching.")
5637 (defun org-create-multibrace-regexp (left right n)
5638 "Create a regular expression which will match a balanced sexp.
5639 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5640 as single character strings.
5641 The regexp returned will match the entire expression including the
5642 delimiters. It will also define a single group which contains the
5643 match except for the outermost delimiters. The maximum depth of
5644 stacked delimiters is N. Escaping delimiters is not possible."
5645 (let* ((nothing (concat "[^" left right "]*?"))
5646 (or "\\|")
5647 (re nothing)
5648 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5649 (while (> n 1)
5650 (setq n (1- n)
5651 re (concat re or next)
5652 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5653 (concat left "\\(" re "\\)" right)))
5655 (defconst org-match-substring-regexp
5656 (concat
5657 "\\(\\S-\\)\\([_^]\\)\\("
5658 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5659 "\\|"
5660 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5661 "\\|"
5662 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5663 "The regular expression matching a sub- or superscript.")
5665 (defconst org-match-substring-with-braces-regexp
5666 (concat
5667 "\\(\\S-\\)\\([_^]\\)"
5668 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5669 "The regular expression matching a sub- or superscript, forcing braces.")
5671 (defun org-make-link-regexps ()
5672 "Update the link regular expressions.
5673 This should be called after the variable `org-link-types' has changed."
5674 (let ((types-re (regexp-opt org-link-types t)))
5675 (setq org-link-types-re
5676 (concat "\\`" types-re ":")
5677 org-link-re-with-space
5678 (concat "<?" types-re ":"
5679 "\\([^" org-non-link-chars " ]"
5680 "[^" org-non-link-chars "]*"
5681 "[^" org-non-link-chars " ]\\)>?")
5682 org-link-re-with-space2
5683 (concat "<?" types-re ":"
5684 "\\([^" org-non-link-chars " ]"
5685 "[^\t\n\r]*"
5686 "[^" org-non-link-chars " ]\\)>?")
5687 org-link-re-with-space3
5688 (concat "<?" types-re ":"
5689 "\\([^" org-non-link-chars " ]"
5690 "[^\t\n\r]*\\)")
5691 org-angle-link-re
5692 (concat "<" types-re ":"
5693 "\\([^" org-non-link-chars " ]"
5694 "[^" org-non-link-chars "]*"
5695 "\\)>")
5696 org-plain-link-re
5697 (concat
5698 "\\<" types-re ":"
5699 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5700 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5701 org-bracket-link-regexp
5702 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5703 org-bracket-link-analytic-regexp
5704 (concat
5705 "\\[\\["
5706 "\\(" types-re ":\\)?"
5707 "\\([^]]+\\)"
5708 "\\]"
5709 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5710 "\\]")
5711 org-bracket-link-analytic-regexp++
5712 (concat
5713 "\\[\\["
5714 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5715 "\\([^]]+\\)"
5716 "\\]"
5717 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5718 "\\]")
5719 org-any-link-re
5720 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5721 org-angle-link-re "\\)\\|\\("
5722 org-plain-link-re "\\)"))))
5724 (org-make-link-regexps)
5726 (defvar org-emph-face nil)
5728 (defun org-do-emphasis-faces (limit)
5729 "Run through the buffer and emphasize strings."
5730 (let (rtn a)
5731 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5732 (let* ((border (char-after (match-beginning 3)))
5733 (bre (regexp-quote (char-to-string border))))
5734 (if (and (not (= border (char-after (match-beginning 4))))
5735 (not (save-match-data
5736 (string-match (concat bre ".*" bre)
5737 (replace-regexp-in-string
5738 "\n" " "
5739 (substring (match-string 2) 1 -1))))))
5740 (progn
5741 (setq rtn t)
5742 (setq a (assoc (match-string 3) org-emphasis-alist))
5743 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5744 'face
5745 (nth 1 a))
5746 (and (nth 2 a)
5747 (org-remove-flyspell-overlays-in
5748 (match-beginning 0) (match-end 0)))
5749 (add-text-properties (match-beginning 2) (match-end 2)
5750 '(font-lock-multiline t org-emphasis t))
5751 (when org-hide-emphasis-markers
5752 (add-text-properties (match-end 4) (match-beginning 5)
5753 '(invisible org-link))
5754 (add-text-properties (match-beginning 3) (match-end 3)
5755 '(invisible org-link))))))
5756 (goto-char (1+ (match-beginning 0))))
5757 rtn))
5759 (defun org-emphasize (&optional char)
5760 "Insert or change an emphasis, i.e. a font like bold or italic.
5761 If there is an active region, change that region to a new emphasis.
5762 If there is no region, just insert the marker characters and position
5763 the cursor between them.
5764 CHAR should be the marker character. If it is a space, it means to
5765 remove the emphasis of the selected region.
5766 If CHAR is not given (for example in an interactive call) it will be
5767 prompted for."
5768 (interactive)
5769 (let ((erc org-emphasis-regexp-components)
5770 (prompt "")
5771 (string "") beg end move c s)
5772 (if (org-region-active-p)
5773 (setq beg (region-beginning) end (region-end)
5774 string (buffer-substring beg end))
5775 (setq move t))
5777 (unless char
5778 (message "Emphasis marker or tag: [%s]"
5779 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5780 (setq char (read-char-exclusive)))
5781 (if (equal char ?\ )
5782 (setq s "" move nil)
5783 (unless (assoc (char-to-string char) org-emphasis-alist)
5784 (user-error "No such emphasis marker: \"%c\"" char))
5785 (setq s (char-to-string char)))
5786 (while (and (> (length string) 1)
5787 (equal (substring string 0 1) (substring string -1))
5788 (assoc (substring string 0 1) org-emphasis-alist))
5789 (setq string (substring string 1 -1)))
5790 (setq string (concat s string s))
5791 (if beg (delete-region beg end))
5792 (unless (or (bolp)
5793 (string-match (concat "[" (nth 0 erc) "\n]")
5794 (char-to-string (char-before (point)))))
5795 (insert " "))
5796 (unless (or (eobp)
5797 (string-match (concat "[" (nth 1 erc) "\n]")
5798 (char-to-string (char-after (point)))))
5799 (insert " ") (backward-char 1))
5800 (insert string)
5801 (and move (backward-char 1))))
5803 (defconst org-nonsticky-props
5804 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5806 (defsubst org-rear-nonsticky-at (pos)
5807 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5809 (defun org-activate-plain-links (limit)
5810 "Run through the buffer and add overlays to links."
5811 (let (f hl)
5812 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5813 (not (org-in-src-block-p)))
5814 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5815 (setq f (get-text-property (match-beginning 0) 'face))
5816 (setq hl (org-match-string-no-properties 0))
5817 (if (or (eq f 'org-tag)
5818 (and (listp f) (memq 'org-tag f)))
5820 (add-text-properties (match-beginning 0) (match-end 0)
5821 (list 'mouse-face 'highlight
5822 'face 'org-link
5823 'htmlize-link `(:uri ,hl)
5824 'keymap org-mouse-map))
5825 (org-rear-nonsticky-at (match-end 0)))
5826 t)))
5828 (defun org-activate-code (limit)
5829 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5830 (progn
5831 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5832 (remove-text-properties (match-beginning 0) (match-end 0)
5833 '(display t invisible t intangible t))
5834 t)))
5836 (defcustom org-src-fontify-natively t
5837 "When non-nil, fontify code in code blocks."
5838 :type 'boolean
5839 :version "24.4"
5840 :package-version '(Org . "8.3")
5841 :group 'org-appearance
5842 :group 'org-babel)
5844 (defcustom org-allow-promoting-top-level-subtree nil
5845 "When non-nil, allow promoting a top level subtree.
5846 The leading star of the top level headline will be replaced
5847 by a #."
5848 :type 'boolean
5849 :version "24.1"
5850 :group 'org-appearance)
5852 (defun org-fontify-meta-lines-and-blocks (limit)
5853 (condition-case nil
5854 (org-fontify-meta-lines-and-blocks-1 limit)
5855 (error (message "org-mode fontification error"))))
5857 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5858 "Fontify #+ lines and blocks."
5859 (let ((case-fold-search t))
5860 (if (re-search-forward
5861 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5862 limit t)
5863 (let ((beg (match-beginning 0))
5864 (block-start (match-end 0))
5865 (block-end nil)
5866 (lang (match-string 7))
5867 (beg1 (line-beginning-position 2))
5868 (dc1 (downcase (match-string 2)))
5869 (dc3 (downcase (match-string 3)))
5870 end end1 quoting block-type ovl)
5871 (cond
5872 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5873 ;; a single line of backend-specific content
5874 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5875 (remove-text-properties (match-beginning 0) (match-end 0)
5876 '(display t invisible t intangible t))
5877 (add-text-properties (match-beginning 1) (match-end 3)
5878 '(font-lock-fontified t face org-meta-line))
5879 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5880 '(font-lock-fontified t face org-block))
5881 ; for backend-specific code
5883 ((and (match-end 4) (equal dc3 "+begin"))
5884 ;; Truly a block
5885 (setq block-type (downcase (match-string 5))
5886 quoting (member block-type org-protecting-blocks))
5887 (when (re-search-forward
5888 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5889 nil t) ;; on purpose, we look further than LIMIT
5890 (setq end (min (point-max) (match-end 0))
5891 end1 (min (point-max) (1- (match-beginning 0))))
5892 (setq block-end (match-beginning 0))
5893 (when quoting
5894 (org-remove-flyspell-overlays-in beg1 end1)
5895 (remove-text-properties beg end
5896 '(display t invisible t intangible t)))
5897 (add-text-properties
5898 beg end '(font-lock-fontified t font-lock-multiline t))
5899 (add-text-properties beg beg1 '(face org-meta-line))
5900 (org-remove-flyspell-overlays-in beg beg1)
5901 (add-text-properties ; For end_src
5902 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5903 (org-remove-flyspell-overlays-in end1 end)
5904 (cond
5905 ((and lang (not (string= lang "")) org-src-fontify-natively)
5906 (org-src-font-lock-fontify-block lang block-start block-end)
5907 ;; remove old background overlays
5908 (mapc (lambda (ov)
5909 (if (eq (overlay-get ov 'face) 'org-block-background)
5910 (delete-overlay ov)))
5911 (overlays-at (/ (+ beg1 block-end) 2)))
5912 ;; add a background overlay
5913 (setq ovl (make-overlay beg1 block-end))
5914 (overlay-put ovl 'face 'org-block-background)
5915 (overlay-put ovl 'evaporate t)) ; make it go away when empty
5916 (quoting
5917 (add-text-properties beg1 (min (point-max) (1+ end1))
5918 '(face org-block))) ; end of source block
5919 ((not org-fontify-quote-and-verse-blocks))
5920 ((string= block-type "quote")
5921 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5922 ((string= block-type "verse")
5923 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5924 (add-text-properties beg beg1 '(face org-block-begin-line))
5925 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5926 '(face org-block-end-line))
5928 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5929 (org-remove-flyspell-overlays-in
5930 (match-beginning 0)
5931 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5932 (add-text-properties
5933 beg (match-end 3)
5934 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5935 '(font-lock-fontified t invisible t)
5936 '(font-lock-fontified t face org-document-info-keyword)))
5937 (add-text-properties
5938 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5939 (if (string-equal dc1 "+title:")
5940 '(font-lock-fontified t face org-document-title)
5941 '(font-lock-fontified t face org-document-info))))
5942 ((or (equal dc1 "+results")
5943 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5944 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5945 "+call:" "+header:" "+headers:" "+name:"))
5946 (and (match-end 4) (equal dc3 "+attr")))
5947 (org-remove-flyspell-overlays-in
5948 (match-beginning 0)
5949 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5950 (add-text-properties
5951 beg (match-end 0)
5952 '(font-lock-fontified t face org-meta-line))
5954 ((member dc3 '(" " ""))
5955 (org-remove-flyspell-overlays-in beg (match-end 0))
5956 (add-text-properties
5957 beg (match-end 0)
5958 '(font-lock-fontified t face font-lock-comment-face)))
5959 (t ;; just any other in-buffer setting, but not indented
5960 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5961 (add-text-properties
5962 beg (match-end 0)
5963 '(font-lock-fontified t face org-meta-line))
5964 t))))))
5966 (defun org-fontify-drawers (limit)
5967 "Fontify drawers."
5968 (when (re-search-forward org-drawer-regexp limit t)
5969 (add-text-properties
5970 (match-beginning 0) (match-end 0)
5971 '(font-lock-fontified t face org-special-keyword))
5972 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5975 (defun org-fontify-macros (limit)
5976 "Fontify macros."
5977 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5978 (add-text-properties
5979 (match-beginning 0) (match-end 0)
5980 '(font-lock-fontified t face org-macro))
5981 (when org-hide-macro-markers
5982 (add-text-properties (match-end 2) (match-beginning 2)
5983 '(invisible t))
5984 (add-text-properties (match-beginning 1) (match-end 1)
5985 '(invisible t)))
5986 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5989 (defun org-activate-angle-links (limit)
5990 "Run through the buffer and add overlays to links."
5991 (if (and (re-search-forward org-angle-link-re limit t)
5992 (not (org-in-src-block-p)))
5993 (progn
5994 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5995 (add-text-properties (match-beginning 0) (match-end 0)
5996 (list 'mouse-face 'highlight
5997 'keymap org-mouse-map))
5998 (org-rear-nonsticky-at (match-end 0))
5999 t)))
6001 (defun org-activate-footnote-links (limit)
6002 "Run through the buffer and add overlays to footnotes."
6003 (let ((fn (org-footnote-next-reference-or-definition limit)))
6004 (when fn
6005 (let* ((beg (nth 1 fn))
6006 (end (nth 2 fn))
6007 (label (car fn))
6008 (referencep (/= (line-beginning-position) beg)))
6009 (when (and referencep (nth 3 fn))
6010 (save-excursion
6011 (goto-char beg)
6012 (search-forward (or label "fn:"))
6013 (org-remove-flyspell-overlays-in beg (match-end 0))))
6014 (add-text-properties beg end
6015 (list 'mouse-face 'highlight
6016 'keymap org-mouse-map
6017 'help-echo
6018 (if referencep "Footnote reference"
6019 "Footnote definition")
6020 'font-lock-fontified t
6021 'font-lock-multiline t
6022 'face 'org-footnote))))))
6024 (defun org-activate-bracket-links (limit)
6025 "Run through the buffer and add overlays to bracketed links."
6026 (if (and (re-search-forward org-bracket-link-regexp limit t)
6027 (not (org-in-src-block-p)))
6028 (let* ((hl (org-match-string-no-properties 1))
6029 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6030 (ip (org-maybe-intangible
6031 (list 'invisible 'org-link
6032 'keymap org-mouse-map 'mouse-face 'highlight
6033 'font-lock-multiline t 'help-echo help
6034 'htmlize-link `(:uri ,hl))))
6035 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6036 'font-lock-multiline t 'help-echo help
6037 'htmlize-link `(:uri ,hl))))
6038 ;; We need to remove the invisible property here. Table narrowing
6039 ;; may have made some of this invisible.
6040 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6041 (remove-text-properties (match-beginning 0) (match-end 0)
6042 '(invisible nil))
6043 (if (match-end 3)
6044 (progn
6045 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6046 (org-rear-nonsticky-at (match-beginning 3))
6047 (add-text-properties (match-beginning 3) (match-end 3) vp)
6048 (org-rear-nonsticky-at (match-end 3))
6049 (add-text-properties (match-end 3) (match-end 0) ip)
6050 (org-rear-nonsticky-at (match-end 0)))
6051 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6052 (org-rear-nonsticky-at (match-beginning 1))
6053 (add-text-properties (match-beginning 1) (match-end 1) vp)
6054 (org-rear-nonsticky-at (match-end 1))
6055 (add-text-properties (match-end 1) (match-end 0) ip)
6056 (org-rear-nonsticky-at (match-end 0)))
6057 t)))
6059 (defun org-activate-dates (limit)
6060 "Run through the buffer and add overlays to dates."
6061 (if (and (re-search-forward org-tsr-regexp-both limit t)
6062 (not (equal (char-before (match-beginning 0)) 91)))
6063 (progn
6064 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6065 (add-text-properties (match-beginning 0) (match-end 0)
6066 (list 'mouse-face 'highlight
6067 'keymap org-mouse-map))
6068 (org-rear-nonsticky-at (match-end 0))
6069 (when org-display-custom-times
6070 (if (match-end 3)
6071 (org-display-custom-time (match-beginning 3) (match-end 3)))
6072 (org-display-custom-time (match-beginning 1) (match-end 1)))
6073 t)))
6075 (defvar org-target-link-regexp nil
6076 "Regular expression matching radio targets in plain text.")
6077 (make-variable-buffer-local 'org-target-link-regexp)
6079 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6080 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6081 border border border))
6082 "Regular expression matching a link target.")
6084 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6085 "Regular expression matching a radio target.")
6087 (defconst org-any-target-regexp
6088 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6089 "Regular expression matching any target.")
6091 (defun org-activate-target-links (limit)
6092 "Run through the buffer and add overlays to target matches."
6093 (when org-target-link-regexp
6094 (let ((case-fold-search t))
6095 (if (re-search-forward org-target-link-regexp limit t)
6096 (progn
6097 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6098 (add-text-properties (match-beginning 1) (match-end 1)
6099 (list 'mouse-face 'highlight
6100 'keymap org-mouse-map
6101 'help-echo "Radio target link"
6102 'org-linked-text t))
6103 (org-rear-nonsticky-at (match-end 1))
6104 t)))))
6106 (defun org-update-radio-target-regexp ()
6107 "Find all radio targets in this file and update the regular expression.
6108 Also refresh fontification if needed."
6109 (interactive)
6110 (let ((old-regexp org-target-link-regexp)
6111 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6112 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6113 (targets
6114 (org-with-wide-buffer
6115 (goto-char (point-min))
6116 (let (rtn)
6117 (while (re-search-forward org-radio-target-regexp nil t)
6118 ;; Make sure point is really within the object.
6119 (backward-char)
6120 (let ((obj (org-element-context)))
6121 (when (eq (org-element-type obj) 'radio-target)
6122 (add-to-list 'rtn (org-element-property :value obj)))))
6123 rtn))))
6124 (setq org-target-link-regexp
6125 (and targets
6126 (concat before-re
6127 (mapconcat
6128 #'(lambda (x)
6129 (replace-regexp-in-string
6130 " +" "\\s-+" (regexp-quote x) t t))
6131 targets
6132 "\\|")
6133 after-re)))
6134 (unless (equal old-regexp org-target-link-regexp)
6135 ;; Clean-up cache.
6136 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6137 ((not org-target-link-regexp) old-regexp)
6139 (concat before-re
6140 (mapconcat
6141 #'(lambda (re)
6142 (substring re (length before-re)
6143 (- (length after-re))))
6144 (list old-regexp org-target-link-regexp)
6145 "\\|")
6146 after-re)))))
6147 (org-with-wide-buffer
6148 (goto-char (point-min))
6149 (while (re-search-forward regexp nil t)
6150 (org-element-cache-refresh (match-beginning 1)))))
6151 ;; Re fontify buffer.
6152 (when (memq 'radio org-highlight-links)
6153 (org-restart-font-lock)))))
6155 (defun org-hide-wide-columns (limit)
6156 (let (s e)
6157 (setq s (text-property-any (point) (or limit (point-max))
6158 'org-cwidth t))
6159 (when s
6160 (setq e (next-single-property-change s 'org-cwidth))
6161 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6162 (goto-char e)
6163 t)))
6165 (defvar org-latex-and-related-regexp nil
6166 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6168 (defun org-compute-latex-and-related-regexp ()
6169 "Compute regular expression for LaTeX, entities and sub/superscript.
6170 Result depends on variable `org-highlight-latex-and-related'."
6171 (org-set-local
6172 'org-latex-and-related-regexp
6173 (let* ((re-sub
6174 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6175 ((eq org-use-sub-superscripts '{})
6176 (list org-match-substring-with-braces-regexp))
6177 (org-use-sub-superscripts (list org-match-substring-regexp))))
6178 (re-latex
6179 (when (memq 'latex org-highlight-latex-and-related)
6180 (let ((matchers (plist-get org-format-latex-options :matchers)))
6181 (delq nil
6182 (mapcar (lambda (x)
6183 (and (member (car x) matchers) (nth 1 x)))
6184 org-latex-regexps)))))
6185 (re-entities
6186 (when (memq 'entities org-highlight-latex-and-related)
6187 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6188 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6190 (defun org-do-latex-and-related (limit)
6191 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6192 LIMIT bounds the search for syntax to highlight. Stop at first
6193 highlighted object, if any. Return t if some highlighting was
6194 done, nil otherwise."
6195 (when (org-string-nw-p org-latex-and-related-regexp)
6196 (catch 'found
6197 (while (re-search-forward org-latex-and-related-regexp limit t)
6198 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6199 'face))
6200 '(org-code org-verbatim underline))
6201 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6202 '(?_ ?^))
6204 0)))
6205 (font-lock-prepend-text-property
6206 (+ offset (match-beginning 0)) (match-end 0)
6207 'face 'org-latex-and-related)
6208 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6209 '(font-lock-multiline t)))
6210 (throw 'found t)))
6211 nil)))
6213 (defun org-restart-font-lock ()
6214 "Restart `font-lock-mode', to force refontification."
6215 (when (and (boundp 'font-lock-mode) font-lock-mode)
6216 (font-lock-mode -1)
6217 (font-lock-mode 1)))
6219 (defun org-activate-tags (limit)
6220 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6221 (progn
6222 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6223 (add-text-properties (match-beginning 1) (match-end 1)
6224 (list 'mouse-face 'highlight
6225 'keymap org-mouse-map))
6226 (org-rear-nonsticky-at (match-end 1))
6227 t)))
6229 (defun org-outline-level ()
6230 "Compute the outline level of the heading at point.
6231 If this is called at a normal headline, the level is the number of stars.
6232 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6233 (save-excursion
6234 (if (not (condition-case nil
6235 (org-back-to-heading t)
6236 (error nil)))
6238 (looking-at org-outline-regexp)
6239 (1- (- (match-end 0) (match-beginning 0))))))
6241 (defvar org-font-lock-keywords nil)
6243 (defsubst org-re-property (property &optional literal)
6244 "Return a regexp matching a PROPERTY line.
6245 Match group 3 will be set to the value if it exists."
6246 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6247 (if literal property (regexp-quote property))
6248 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6250 (defconst org-property-re
6251 (org-re-property ".*?" 'literal)
6252 "Regular expression matching a property line.
6253 There are four matching groups:
6254 1: :PROPKEY: including the leading and trailing colon,
6255 2: PROPKEY without the leading and trailing colon,
6256 3: PROPVAL without leading or trailing spaces,
6257 4: the indentation of the current line,
6258 5: trailing whitespace.")
6260 (defvar org-font-lock-hook nil
6261 "Functions to be called for special font lock stuff.")
6263 (defvar org-font-lock-set-keywords-hook nil
6264 "Functions that can manipulate `org-font-lock-extra-keywords'.
6265 This is called after `org-font-lock-extra-keywords' is defined, but before
6266 it is installed to be used by font lock. This can be useful if something
6267 needs to be inserted at a specific position in the font-lock sequence.")
6269 (defun org-font-lock-hook (limit)
6270 "Run `org-font-lock-hook' within LIMIT."
6271 (run-hook-with-args 'org-font-lock-hook limit))
6273 (defun org-set-font-lock-defaults ()
6274 "Set font lock defaults for the current buffer."
6275 (let* ((em org-fontify-emphasized-text)
6276 (lk org-highlight-links)
6277 (org-font-lock-extra-keywords
6278 (list
6279 ;; Call the hook
6280 '(org-font-lock-hook)
6281 ;; Headlines
6282 `(,(if org-fontify-whole-heading-line
6283 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6284 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6285 (1 (org-get-level-face 1))
6286 (2 (org-get-level-face 2))
6287 (3 (org-get-level-face 3)))
6288 ;; Table lines
6289 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6290 (1 'org-table t))
6291 ;; Table internals
6292 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6293 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6294 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6295 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6296 ;; Drawers
6297 '(org-fontify-drawers)
6298 ;; Properties
6299 (list org-property-re
6300 '(1 'org-special-keyword t)
6301 '(3 'org-property-value t))
6302 ;; Links
6303 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6304 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6305 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6306 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6307 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6308 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6309 (if (memq 'footnote lk) '(org-activate-footnote-links))
6310 ;; Targets.
6311 (list org-any-target-regexp '(0 'org-target t))
6312 ;; Diary sexps.
6313 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6314 ;; Macro
6315 '(org-fontify-macros)
6316 '(org-hide-wide-columns (0 nil append))
6317 ;; TODO keyword
6318 (list (format org-heading-keyword-regexp-format
6319 org-todo-regexp)
6320 '(2 (org-get-todo-face 2) t))
6321 ;; DONE
6322 (if org-fontify-done-headline
6323 (list (format org-heading-keyword-regexp-format
6324 (concat
6325 "\\(?:"
6326 (mapconcat 'regexp-quote org-done-keywords "\\|")
6327 "\\)"))
6328 '(2 'org-headline-done t))
6329 nil)
6330 ;; Priorities
6331 '(org-font-lock-add-priority-faces)
6332 ;; Tags
6333 '(org-font-lock-add-tag-faces)
6334 ;; Tags groups
6335 (if (and org-group-tags org-tag-groups-alist)
6336 (list (concat org-outline-regexp-bol ".+\\(:"
6337 (regexp-opt (mapcar 'car org-tag-groups-alist))
6338 ":\\).*$")
6339 '(1 'org-tag-group prepend)))
6340 ;; Special keywords
6341 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6342 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6343 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6344 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6345 ;; Emphasis
6346 (if em
6347 (if (featurep 'xemacs)
6348 '(org-do-emphasis-faces (0 nil append))
6349 '(org-do-emphasis-faces)))
6350 ;; Checkboxes
6351 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6352 1 'org-checkbox prepend)
6353 (if (cdr (assq 'checkbox org-list-automatic-rules))
6354 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6355 (0 (org-get-checkbox-statistics-face) t)))
6356 ;; Description list items
6357 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6358 1 'org-list-dt prepend)
6359 ;; ARCHIVEd headings
6360 (list (concat
6361 org-outline-regexp-bol
6362 "\\(.*:" org-archive-tag ":.*\\)")
6363 '(1 'org-archived prepend))
6364 ;; Specials
6365 '(org-do-latex-and-related)
6366 '(org-fontify-entities)
6367 '(org-raise-scripts)
6368 ;; Code
6369 '(org-activate-code (1 'org-code t))
6370 ;; COMMENT
6371 (list (format
6372 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6373 org-todo-regexp
6374 org-comment-string)
6375 '(9 'org-special-keyword t))
6376 ;; Blocks and meta lines
6377 '(org-fontify-meta-lines-and-blocks))))
6378 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6379 (run-hooks 'org-font-lock-set-keywords-hook)
6380 ;; Now set the full font-lock-keywords
6381 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6382 (org-set-local 'font-lock-defaults
6383 '(org-font-lock-keywords t nil nil backward-paragraph))
6384 (kill-local-variable 'font-lock-keywords) nil))
6386 (defun org-toggle-pretty-entities ()
6387 "Toggle the composition display of entities as UTF8 characters."
6388 (interactive)
6389 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6390 (org-restart-font-lock)
6391 (if org-pretty-entities
6392 (message "Entities are now displayed as UTF8 characters")
6393 (save-restriction
6394 (widen)
6395 (org-decompose-region (point-min) (point-max))
6396 (message "Entities are now displayed as plain text"))))
6398 (defvar org-custom-properties-overlays nil
6399 "List of overlays used for custom properties.")
6400 (make-variable-buffer-local 'org-custom-properties-overlays)
6402 (defun org-toggle-custom-properties-visibility ()
6403 "Display or hide properties in `org-custom-properties'."
6404 (interactive)
6405 (if org-custom-properties-overlays
6406 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6407 (setq org-custom-properties-overlays nil))
6408 (unless (not org-custom-properties)
6409 (save-excursion
6410 (save-restriction
6411 (widen)
6412 (goto-char (point-min))
6413 (while (re-search-forward org-property-re nil t)
6414 (mapc (lambda(p)
6415 (when (equal p (substring (match-string 1) 1 -1))
6416 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6417 (overlay-put o 'invisible t)
6418 (overlay-put o 'org-custom-property t)
6419 (push o org-custom-properties-overlays))))
6420 org-custom-properties)))))))
6422 (defun org-fontify-entities (limit)
6423 "Find an entity to fontify."
6424 (let (ee)
6425 (when org-pretty-entities
6426 (catch 'match
6427 (while (re-search-forward
6428 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6429 limit t)
6430 (if (and (not (org-at-comment-p))
6431 (setq ee (org-entity-get (match-string 1)))
6432 (= (length (nth 6 ee)) 1))
6433 (let*
6434 ((end (if (equal (match-string 2) "{}")
6435 (match-end 2)
6436 (match-end 1))))
6437 (add-text-properties
6438 (match-beginning 0) end
6439 (list 'font-lock-fontified t))
6440 (compose-region (match-beginning 0) end
6441 (nth 6 ee) nil)
6442 (backward-char 1)
6443 (throw 'match t))))
6444 nil))))
6446 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6447 "Fontify string S like in Org-mode."
6448 (with-temp-buffer
6449 (insert s)
6450 (let ((org-odd-levels-only odd-levels))
6451 (org-mode)
6452 (font-lock-fontify-buffer)
6453 (buffer-string))))
6455 (defvar org-m nil)
6456 (defvar org-l nil)
6457 (defvar org-f nil)
6458 (defun org-get-level-face (n)
6459 "Get the right face for match N in font-lock matching of headlines."
6460 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6461 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6462 (if org-cycle-level-faces
6463 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6464 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6465 (cond
6466 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6467 ((eq n 2) org-f)
6468 (t (if org-level-color-stars-only nil org-f))))
6471 (defun org-get-todo-face (kwd)
6472 "Get the right face for a TODO keyword KWD.
6473 If KWD is a number, get the corresponding match group."
6474 (if (numberp kwd) (setq kwd (match-string kwd)))
6475 (or (org-face-from-face-or-color
6476 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6477 (and (member kwd org-done-keywords) 'org-done)
6478 'org-todo))
6480 (defun org-face-from-face-or-color (context inherit face-or-color)
6481 "Create a face list that inherits INHERIT, but sets the foreground color.
6482 When FACE-OR-COLOR is not a string, just return it."
6483 (if (stringp face-or-color)
6484 (list :inherit inherit
6485 (cdr (assoc context org-faces-easy-properties))
6486 face-or-color)
6487 face-or-color))
6489 (defun org-font-lock-add-tag-faces (limit)
6490 "Add the special tag faces."
6491 (when (and org-tag-faces org-tags-special-faces-re)
6492 (while (re-search-forward org-tags-special-faces-re limit t)
6493 (add-text-properties (match-beginning 1) (match-end 1)
6494 (list 'face (org-get-tag-face 1)
6495 'font-lock-fontified t))
6496 (backward-char 1))))
6498 (defun org-font-lock-add-priority-faces (limit)
6499 "Add the special priority faces."
6500 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6501 (when (save-match-data (org-at-heading-p))
6502 (add-text-properties
6503 (match-beginning 0) (match-end 0)
6504 (list 'face (or (org-face-from-face-or-color
6505 'priority 'org-priority
6506 (cdr (assoc (char-after (match-beginning 1))
6507 org-priority-faces)))
6508 'org-priority)
6509 'font-lock-fontified t)))))
6511 (defun org-get-tag-face (kwd)
6512 "Get the right face for a TODO keyword KWD.
6513 If KWD is a number, get the corresponding match group."
6514 (if (numberp kwd) (setq kwd (match-string kwd)))
6515 (or (org-face-from-face-or-color
6516 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6517 'org-tag))
6519 (defun org-unfontify-region (beg end &optional maybe_loudly)
6520 "Remove fontification and activation overlays from links."
6521 (font-lock-default-unfontify-region beg end)
6522 (let* ((buffer-undo-list t)
6523 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6524 (inhibit-modification-hooks t)
6525 deactivate-mark buffer-file-name buffer-file-truename)
6526 (org-decompose-region beg end)
6527 (remove-text-properties beg end
6528 '(mouse-face t keymap t org-linked-text t
6529 invisible t intangible t
6530 org-emphasis t))
6531 (org-remove-font-lock-display-properties beg end)))
6533 (defconst org-script-display '(((raise -0.3) (height 0.7))
6534 ((raise 0.3) (height 0.7))
6535 ((raise -0.5))
6536 ((raise 0.5)))
6537 "Display properties for showing superscripts and subscripts.")
6539 (defun org-remove-font-lock-display-properties (beg end)
6540 "Remove specific display properties that have been added by font lock.
6541 The will remove the raise properties that are used to show superscripts
6542 and subscripts."
6543 (let (next prop)
6544 (while (< beg end)
6545 (setq next (next-single-property-change beg 'display nil end)
6546 prop (get-text-property beg 'display))
6547 (if (member prop org-script-display)
6548 (put-text-property beg next 'display nil))
6549 (setq beg next))))
6551 (defun org-raise-scripts (limit)
6552 "Add raise properties to sub/superscripts."
6553 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6554 (if (re-search-forward
6555 (if (eq org-use-sub-superscripts t)
6556 org-match-substring-regexp
6557 org-match-substring-with-braces-regexp)
6558 limit t)
6559 (let* ((pos (point)) table-p comment-p
6560 (mpos (match-beginning 3))
6561 (emph-p (get-text-property mpos 'org-emphasis))
6562 (link-p (get-text-property mpos 'mouse-face))
6563 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6564 (goto-char (point-at-bol))
6565 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6566 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6567 (goto-char pos)
6568 ;; Handle a_b^c
6569 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6570 (if (or comment-p emph-p link-p keyw-p)
6572 (put-text-property (match-beginning 3) (match-end 0)
6573 'display
6574 (if (equal (char-after (match-beginning 2)) ?^)
6575 (nth (if table-p 3 1) org-script-display)
6576 (nth (if table-p 2 0) org-script-display)))
6577 (add-text-properties (match-beginning 2) (match-end 2)
6578 (list 'invisible t
6579 'org-dwidth t 'org-dwidth-n 1))
6580 (if (and (eq (char-after (match-beginning 3)) ?{)
6581 (eq (char-before (match-end 3)) ?}))
6582 (progn
6583 (add-text-properties
6584 (match-beginning 3) (1+ (match-beginning 3))
6585 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6586 (add-text-properties
6587 (1- (match-end 3)) (match-end 3)
6588 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6589 t)))))
6591 ;;;; Visibility cycling, including org-goto and indirect buffer
6593 ;;; Cycling
6595 (defvar org-cycle-global-status nil)
6596 (make-variable-buffer-local 'org-cycle-global-status)
6597 (put 'org-cycle-global-status 'org-state t)
6598 (defvar org-cycle-subtree-status nil)
6599 (make-variable-buffer-local 'org-cycle-subtree-status)
6600 (put 'org-cycle-subtree-status 'org-state t)
6602 (defvar org-inlinetask-min-level)
6604 (defun org-unlogged-message (&rest args)
6605 "Display a message, but avoid logging it in the *Messages* buffer."
6606 (let ((message-log-max nil))
6607 (apply 'message args)))
6609 ;;;###autoload
6610 (defun org-cycle (&optional arg)
6611 "TAB-action and visibility cycling for Org-mode.
6613 This is the command invoked in Org-mode by the TAB key. Its main purpose
6614 is outline visibility cycling, but it also invokes other actions
6615 in special contexts.
6617 - When this function is called with a prefix argument, rotate the entire
6618 buffer through 3 states (global cycling)
6619 1. OVERVIEW: Show only top-level headlines.
6620 2. CONTENTS: Show all headlines of all levels, but no body text.
6621 3. SHOW ALL: Show everything.
6622 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6623 determined by the variable `org-startup-folded', and by any VISIBILITY
6624 properties in the buffer.
6625 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6626 including any drawers.
6628 - When inside a table, re-align the table and move to the next field.
6630 - When point is at the beginning of a headline, rotate the subtree started
6631 by this line through 3 different states (local cycling)
6632 1. FOLDED: Only the main headline is shown.
6633 2. CHILDREN: The main headline and the direct children are shown.
6634 From this state, you can move to one of the children
6635 and zoom in further.
6636 3. SUBTREE: Show the entire subtree, including body text.
6637 If there is no subtree, switch directly from CHILDREN to FOLDED.
6639 - When point is at the beginning of an empty headline and the variable
6640 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6641 of the headline by demoting and promoting it to likely levels. This
6642 speeds up creation document structure by pressing TAB once or several
6643 times right after creating a new headline.
6645 - When there is a numeric prefix, go up to a heading with level ARG, do
6646 a `show-subtree' and return to the previous cursor position. If ARG
6647 is negative, go up that many levels.
6649 - When point is not at the beginning of a headline, execute the global
6650 binding for TAB, which is re-indenting the line. See the option
6651 `org-cycle-emulate-tab' for details.
6653 - Special case: if point is at the beginning of the buffer and there is
6654 no headline in line 1, this function will act as if called with prefix arg
6655 (C-u TAB, same as S-TAB) also when called without prefix arg.
6656 But only if also the variable `org-cycle-global-at-bob' is t."
6657 (interactive "P")
6658 (org-load-modules-maybe)
6659 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6660 (and org-cycle-level-after-item/entry-creation
6661 (or (org-cycle-level)
6662 (org-cycle-item-indentation))))
6663 (let* ((limit-level
6664 (or org-cycle-max-level
6665 (and (boundp 'org-inlinetask-min-level)
6666 org-inlinetask-min-level
6667 (1- org-inlinetask-min-level))))
6668 (nstars (and limit-level
6669 (if org-odd-levels-only
6670 (and limit-level (1- (* limit-level 2)))
6671 limit-level)))
6672 (org-outline-regexp
6673 (if (not (derived-mode-p 'org-mode))
6674 outline-regexp
6675 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6676 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6677 (not (looking-at org-outline-regexp))))
6678 (org-cycle-hook
6679 (if bob-special
6680 (delq 'org-optimize-window-after-visibility-change
6681 (copy-sequence org-cycle-hook))
6682 org-cycle-hook))
6683 (pos (point)))
6685 (if (or bob-special (equal arg '(4)))
6686 ;; special case: use global cycling
6687 (setq arg t))
6689 (cond
6691 ((equal arg '(16))
6692 (setq last-command 'dummy)
6693 (org-set-startup-visibility)
6694 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6696 ((equal arg '(64))
6697 (show-all)
6698 (org-unlogged-message "Entire buffer visible, including drawers"))
6700 ;; Try cdlatex TAB completion
6701 ((org-try-cdlatex-tab))
6703 ;; Table: enter it or move to the next field.
6704 ((org-at-table-p 'any)
6705 (if (org-at-table.el-p)
6706 (message "Use C-c ' to edit table.el tables")
6707 (if arg (org-table-edit-field t)
6708 (org-table-justify-field-maybe)
6709 (call-interactively 'org-table-next-field))))
6711 ((run-hook-with-args-until-success
6712 'org-tab-after-check-for-table-hook))
6714 ;; Global cycling: delegate to `org-cycle-internal-global'.
6715 ((eq arg t) (org-cycle-internal-global))
6717 ;; Drawers: delegate to `org-flag-drawer'.
6718 ((save-excursion
6719 (beginning-of-line 1)
6720 (looking-at org-drawer-regexp))
6721 (org-flag-drawer ; toggle block visibility
6722 (not (get-char-property (match-end 0) 'invisible))))
6724 ;; Show-subtree, ARG levels up from here.
6725 ((integerp arg)
6726 (save-excursion
6727 (org-back-to-heading)
6728 (outline-up-heading (if (< arg 0) (- arg)
6729 (- (funcall outline-level) arg)))
6730 (org-show-subtree)))
6732 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6733 ((and (featurep 'org-inlinetask)
6734 (org-inlinetask-at-task-p)
6735 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6736 (org-inlinetask-toggle-visibility))
6738 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6739 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6740 (save-excursion (beginning-of-line 1)
6741 (looking-at org-outline-regexp)))
6742 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6743 (org-cycle-internal-local))
6745 ;; From there: TAB emulation and template completion.
6746 (buffer-read-only (org-back-to-heading))
6748 ((run-hook-with-args-until-success
6749 'org-tab-after-check-for-cycling-hook))
6751 ((org-try-structure-completion))
6753 ((run-hook-with-args-until-success
6754 'org-tab-before-tab-emulation-hook))
6756 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6757 (or (not (bolp))
6758 (not (looking-at org-outline-regexp))))
6759 (call-interactively (global-key-binding "\t")))
6761 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6762 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6763 (or (and (eq org-cycle-emulate-tab 'white)
6764 (= (match-end 0) (point-at-eol)))
6765 (and (eq org-cycle-emulate-tab 'whitestart)
6766 (>= (match-end 0) pos))))
6768 (eq org-cycle-emulate-tab t))
6769 (call-interactively (global-key-binding "\t")))
6771 (t (save-excursion
6772 (org-back-to-heading)
6773 (org-cycle)))))))
6775 (defun org-cycle-internal-global ()
6776 "Do the global cycling action."
6777 ;; Hack to avoid display of messages for .org attachments in Gnus
6778 (let ((ga (string-match "\\*fontification" (buffer-name))))
6779 (cond
6780 ((and (eq last-command this-command)
6781 (eq org-cycle-global-status 'overview))
6782 ;; We just created the overview - now do table of contents
6783 ;; This can be slow in very large buffers, so indicate action
6784 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6785 (unless ga (org-unlogged-message "CONTENTS..."))
6786 (org-content)
6787 (unless ga (org-unlogged-message "CONTENTS...done"))
6788 (setq org-cycle-global-status 'contents)
6789 (run-hook-with-args 'org-cycle-hook 'contents))
6791 ((and (eq last-command this-command)
6792 (eq org-cycle-global-status 'contents))
6793 ;; We just showed the table of contents - now show everything
6794 (run-hook-with-args 'org-pre-cycle-hook 'all)
6795 (show-all)
6796 (unless ga (org-unlogged-message "SHOW ALL"))
6797 (setq org-cycle-global-status 'all)
6798 (run-hook-with-args 'org-cycle-hook 'all))
6801 ;; Default action: go to overview
6802 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6803 (org-overview)
6804 (unless ga (org-unlogged-message "OVERVIEW"))
6805 (setq org-cycle-global-status 'overview)
6806 (run-hook-with-args 'org-cycle-hook 'overview)))))
6808 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6810 (defun org-cycle-internal-local ()
6811 "Do the local cycling action."
6812 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6813 ;; First, determine end of headline (EOH), end of subtree or item
6814 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6815 (save-excursion
6816 (if (org-at-item-p)
6817 (progn
6818 (beginning-of-line)
6819 (setq struct (org-list-struct))
6820 (setq eoh (point-at-eol))
6821 (setq eos (org-list-get-item-end-before-blank (point) struct))
6822 (setq has-children (org-list-has-child-p (point) struct)))
6823 (org-back-to-heading)
6824 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6825 (setq eos (save-excursion (org-end-of-subtree t t)
6826 (when (bolp) (backward-char)) (point)))
6827 (setq has-children
6828 (or (save-excursion
6829 (let ((level (funcall outline-level)))
6830 (outline-next-heading)
6831 (and (org-at-heading-p t)
6832 (> (funcall outline-level) level))))
6833 (save-excursion
6834 (org-list-search-forward (org-item-beginning-re) eos t)))))
6835 ;; Determine end invisible part of buffer (EOL)
6836 (beginning-of-line 2)
6837 ;; XEmacs doesn't have `next-single-char-property-change'
6838 (if (featurep 'xemacs)
6839 (while (and (not (eobp)) ;; this is like `next-line'
6840 (get-char-property (1- (point)) 'invisible))
6841 (beginning-of-line 2))
6842 (while (and (not (eobp)) ;; this is like `next-line'
6843 (get-char-property (1- (point)) 'invisible))
6844 (goto-char (next-single-char-property-change (point) 'invisible))
6845 (and (eolp) (beginning-of-line 2))))
6846 (setq eol (point)))
6847 ;; Find out what to do next and set `this-command'
6848 (cond
6849 ((= eos eoh)
6850 ;; Nothing is hidden behind this heading
6851 (unless (org-before-first-heading-p)
6852 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6853 (org-unlogged-message "EMPTY ENTRY")
6854 (setq org-cycle-subtree-status nil)
6855 (save-excursion
6856 (goto-char eos)
6857 (outline-next-heading)
6858 (if (outline-invisible-p) (org-flag-heading nil))))
6859 ((and (or (>= eol eos)
6860 (not (string-match "\\S-" (buffer-substring eol eos))))
6861 (or has-children
6862 (not (setq children-skipped
6863 org-cycle-skip-children-state-if-no-children))))
6864 ;; Entire subtree is hidden in one line: children view
6865 (unless (org-before-first-heading-p)
6866 (run-hook-with-args 'org-pre-cycle-hook 'children))
6867 (if (org-at-item-p)
6868 (org-list-set-item-visibility (point-at-bol) struct 'children)
6869 (org-show-entry)
6870 (org-with-limited-levels (show-children))
6871 ;; FIXME: This slows down the func way too much.
6872 ;; How keep drawers hidden in subtree anyway?
6873 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6874 ;; (org-cycle-hide-drawers 'subtree))
6876 ;; Fold every list in subtree to top-level items.
6877 (when (eq org-cycle-include-plain-lists 'integrate)
6878 (save-excursion
6879 (org-back-to-heading)
6880 (while (org-list-search-forward (org-item-beginning-re) eos t)
6881 (beginning-of-line 1)
6882 (let* ((struct (org-list-struct))
6883 (prevs (org-list-prevs-alist struct))
6884 (end (org-list-get-bottom-point struct)))
6885 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6886 (org-list-get-all-items (point) struct prevs))
6887 (goto-char (if (< end eos) end eos)))))))
6888 (org-unlogged-message "CHILDREN")
6889 (save-excursion
6890 (goto-char eos)
6891 (outline-next-heading)
6892 (if (outline-invisible-p) (org-flag-heading nil)))
6893 (setq org-cycle-subtree-status 'children)
6894 (unless (org-before-first-heading-p)
6895 (run-hook-with-args 'org-cycle-hook 'children)))
6896 ((or children-skipped
6897 (and (eq last-command this-command)
6898 (eq org-cycle-subtree-status 'children)))
6899 ;; We just showed the children, or no children are there,
6900 ;; now show everything.
6901 (unless (org-before-first-heading-p)
6902 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6903 (outline-flag-region eoh eos nil)
6904 (org-unlogged-message
6905 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6906 (setq org-cycle-subtree-status 'subtree)
6907 (unless (org-before-first-heading-p)
6908 (run-hook-with-args 'org-cycle-hook 'subtree)))
6910 ;; Default action: hide the subtree.
6911 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6912 (outline-flag-region eoh eos t)
6913 (org-unlogged-message "FOLDED")
6914 (setq org-cycle-subtree-status 'folded)
6915 (unless (org-before-first-heading-p)
6916 (run-hook-with-args 'org-cycle-hook 'folded))))))
6918 ;;;###autoload
6919 (defun org-global-cycle (&optional arg)
6920 "Cycle the global visibility. For details see `org-cycle'.
6921 With \\[universal-argument] prefix arg, switch to startup visibility.
6922 With a numeric prefix, show all headlines up to that level."
6923 (interactive "P")
6924 (let ((org-cycle-include-plain-lists
6925 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6926 (cond
6927 ((integerp arg)
6928 (show-all)
6929 (hide-sublevels arg)
6930 (setq org-cycle-global-status 'contents))
6931 ((equal arg '(4))
6932 (org-set-startup-visibility)
6933 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6935 (org-cycle '(4))))))
6937 (defun org-set-startup-visibility ()
6938 "Set the visibility required by startup options and properties."
6939 (cond
6940 ((eq org-startup-folded t)
6941 (org-overview))
6942 ((eq org-startup-folded 'content)
6943 (org-content))
6944 ((or (eq org-startup-folded 'showeverything)
6945 (eq org-startup-folded nil))
6946 (show-all)))
6947 (unless (eq org-startup-folded 'showeverything)
6948 (if org-hide-block-startup (org-hide-block-all))
6949 (org-set-visibility-according-to-property 'no-cleanup)
6950 (org-cycle-hide-archived-subtrees 'all)
6951 (org-cycle-hide-drawers 'all)
6952 (org-cycle-show-empty-lines t)))
6954 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6955 "Switch subtree visibilities according to :VISIBILITY: property."
6956 (interactive)
6957 (let (org-show-entry-below state)
6958 (save-excursion
6959 (goto-char (point-min))
6960 (while (re-search-forward
6961 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6962 nil t)
6963 (setq state (match-string 1))
6964 (save-excursion
6965 (org-back-to-heading t)
6966 (hide-subtree)
6967 (org-reveal)
6968 (cond
6969 ((equal state '("fold" "folded"))
6970 (hide-subtree))
6971 ((equal state "children")
6972 (org-show-hidden-entry)
6973 (show-children))
6974 ((equal state "content")
6975 (save-excursion
6976 (save-restriction
6977 (org-narrow-to-subtree)
6978 (org-content))))
6979 ((member state '("all" "showall"))
6980 (show-subtree)))))
6981 (unless no-cleanup
6982 (org-cycle-hide-archived-subtrees 'all)
6983 (org-cycle-hide-drawers 'all)
6984 (org-cycle-show-empty-lines 'all)))))
6986 ;; This function uses outline-regexp instead of the more fundamental
6987 ;; org-outline-regexp so that org-cycle-global works outside of Org
6988 ;; buffers, where outline-regexp is needed.
6989 (defun org-overview ()
6990 "Switch to overview mode, showing only top-level headlines.
6991 This shows all headlines with a level equal or greater than the level
6992 of the first headline in the buffer. This is important, because if the
6993 first headline is not level one, then (hide-sublevels 1) gives confusing
6994 results."
6995 (interactive)
6996 (save-excursion
6997 (let ((level
6998 (save-excursion
6999 (goto-char (point-min))
7000 (if (re-search-forward (concat "^" outline-regexp) nil t)
7001 (progn
7002 (goto-char (match-beginning 0))
7003 (funcall outline-level))))))
7004 (and level (hide-sublevels level)))))
7006 (defun org-content (&optional arg)
7007 "Show all headlines in the buffer, like a table of contents.
7008 With numerical argument N, show content up to level N."
7009 (interactive "P")
7010 (org-overview)
7011 (save-excursion
7012 ;; Visit all headings and show their offspring
7013 (and (integerp arg) (org-overview))
7014 (goto-char (point-max))
7015 (catch 'exit
7016 (while (and (progn (condition-case nil
7017 (outline-previous-visible-heading 1)
7018 (error (goto-char (point-min))))
7020 (looking-at org-outline-regexp))
7021 (if (integerp arg)
7022 (show-children (1- arg))
7023 (show-branches))
7024 (if (bobp) (throw 'exit nil))))))
7026 (defun org-optimize-window-after-visibility-change (state)
7027 "Adjust the window after a change in outline visibility.
7028 This function is the default value of the hook `org-cycle-hook'."
7029 (when (get-buffer-window (current-buffer))
7030 (cond
7031 ((eq state 'content) nil)
7032 ((eq state 'all) nil)
7033 ((eq state 'folded) nil)
7034 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7035 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7037 (defun org-remove-empty-overlays-at (pos)
7038 "Remove outline overlays that do not contain non-white stuff."
7039 (mapc
7040 (lambda (o)
7041 (and (eq 'outline (overlay-get o 'invisible))
7042 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7043 (overlay-end o))))
7044 (delete-overlay o)))
7045 (overlays-at pos)))
7047 (defun org-clean-visibility-after-subtree-move ()
7048 "Fix visibility issues after moving a subtree."
7049 ;; First, find a reasonable region to look at:
7050 ;; Start two siblings above, end three below
7051 (let* ((beg (save-excursion
7052 (and (org-get-last-sibling)
7053 (org-get-last-sibling))
7054 (point)))
7055 (end (save-excursion
7056 (and (org-get-next-sibling)
7057 (org-get-next-sibling)
7058 (org-get-next-sibling))
7059 (if (org-at-heading-p)
7060 (point-at-eol)
7061 (point))))
7062 (level (looking-at "\\*+"))
7063 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7064 (save-excursion
7065 (save-restriction
7066 (narrow-to-region beg end)
7067 (when re
7068 ;; Properly fold already folded siblings
7069 (goto-char (point-min))
7070 (while (re-search-forward re nil t)
7071 (if (and (not (outline-invisible-p))
7072 (save-excursion
7073 (goto-char (point-at-eol)) (outline-invisible-p)))
7074 (hide-entry))))
7075 (org-cycle-show-empty-lines 'overview)
7076 (org-cycle-hide-drawers 'overview)))))
7078 (defun org-cycle-show-empty-lines (state)
7079 "Show empty lines above all visible headlines.
7080 The region to be covered depends on STATE when called through
7081 `org-cycle-hook'. Lisp program can use t for STATE to get the
7082 entire buffer covered. Note that an empty line is only shown if there
7083 are at least `org-cycle-separator-lines' empty lines before the headline."
7084 (when (not (= org-cycle-separator-lines 0))
7085 (save-excursion
7086 (let* ((n (abs org-cycle-separator-lines))
7087 (re (cond
7088 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7089 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7090 (t (let ((ns (number-to-string (- n 2))))
7091 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7092 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7093 beg end b e)
7094 (cond
7095 ((memq state '(overview contents t))
7096 (setq beg (point-min) end (point-max)))
7097 ((memq state '(children folded))
7098 (setq beg (point) end (progn (org-end-of-subtree t t)
7099 (beginning-of-line 2)
7100 (point)))))
7101 (when beg
7102 (goto-char beg)
7103 (while (re-search-forward re end t)
7104 (unless (get-char-property (match-end 1) 'invisible)
7105 (setq e (match-end 1))
7106 (if (< org-cycle-separator-lines 0)
7107 (setq b (save-excursion
7108 (goto-char (match-beginning 0))
7109 (org-back-over-empty-lines)
7110 (if (save-excursion
7111 (goto-char (max (point-min) (1- (point))))
7112 (org-at-heading-p))
7113 (1- (point))
7114 (point))))
7115 (setq b (match-beginning 1)))
7116 (outline-flag-region b e nil)))))))
7117 ;; Never hide empty lines at the end of the file.
7118 (save-excursion
7119 (goto-char (point-max))
7120 (outline-previous-heading)
7121 (outline-end-of-heading)
7122 (if (and (looking-at "[ \t\n]+")
7123 (= (match-end 0) (point-max)))
7124 (outline-flag-region (point) (match-end 0) nil))))
7126 (defun org-show-empty-lines-in-parent ()
7127 "Move to the parent and re-show empty lines before visible headlines."
7128 (save-excursion
7129 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7130 (org-cycle-show-empty-lines context))))
7132 (defun org-files-list ()
7133 "Return `org-agenda-files' list, plus all open org-mode files.
7134 This is useful for operations that need to scan all of a user's
7135 open and agenda-wise Org files."
7136 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7137 (dolist (buf (buffer-list))
7138 (with-current-buffer buf
7139 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7140 (let ((file (expand-file-name (buffer-file-name))))
7141 (unless (member file files)
7142 (push file files))))))
7143 files))
7145 (defsubst org-entry-beginning-position ()
7146 "Return the beginning position of the current entry."
7147 (save-excursion (outline-back-to-heading t) (point)))
7149 (defsubst org-entry-end-position ()
7150 "Return the end position of the current entry."
7151 (save-excursion (outline-next-heading) (point)))
7153 (defun org-cycle-hide-drawers (state &optional exceptions)
7154 "Re-hide all drawers after a visibility state change.
7155 When non-nil, optional argument EXCEPTIONS is a list of strings
7156 specifying which drawers should not be hidden."
7157 (when (and (derived-mode-p 'org-mode)
7158 (not (memq state '(overview folded contents))))
7159 (save-excursion
7160 (let* ((globalp (memq state '(contents all)))
7161 (beg (if globalp (point-min) (point)))
7162 (end (if globalp (point-max)
7163 (if (eq state 'children)
7164 (save-excursion (outline-next-heading) (point))
7165 (org-end-of-subtree t)))))
7166 (goto-char beg)
7167 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7168 (unless (member-ignore-case (match-string 1) exceptions)
7169 (let ((drawer (org-element-at-point)))
7170 (when (memq (org-element-type drawer) '(drawer property-drawer))
7171 (org-flag-drawer t drawer)
7172 ;; Make sure to skip drawer entirely or we might flag
7173 ;; it another time when matching its ending line with
7174 ;; `org-drawer-regexp'.
7175 (goto-char (org-element-property :end drawer))))))))))
7177 (defun org-cycle-hide-inline-tasks (state)
7178 "Re-hide inline tasks when switching to 'contents or 'children
7179 visibility state."
7180 (case state
7181 (contents
7182 (when (org-bound-and-true-p org-inlinetask-min-level)
7183 (hide-sublevels (1- org-inlinetask-min-level))))
7184 (children
7185 (when (featurep 'org-inlinetask)
7186 (save-excursion
7187 (while (and (outline-next-heading)
7188 (org-inlinetask-at-task-p))
7189 (org-inlinetask-toggle-visibility)
7190 (org-inlinetask-goto-end)))))))
7192 (defun org-flag-drawer (flag &optional element)
7193 "When FLAG is non-nil, hide the drawer we are at.
7194 Otherwise make it visible. When optional argument ELEMENT is
7195 a parsed drawer, as returned by `org-element-at-point', hide or
7196 show that drawer instead."
7197 (when (save-excursion
7198 (beginning-of-line)
7199 (org-looking-at-p org-drawer-regexp))
7200 (let ((drawer (or element (org-element-at-point))))
7201 (when (memq (org-element-type drawer) '(drawer property-drawer))
7202 (let ((post (org-element-property :post-affiliated drawer)))
7203 (save-excursion
7204 (outline-flag-region
7205 (progn (goto-char post) (line-end-position))
7206 (progn (goto-char (org-element-property :end drawer))
7207 (skip-chars-backward " \r\t\n")
7208 (line-end-position))
7209 flag))
7210 ;; When the drawer is hidden away, make sure point lies in
7211 ;; a visible part of the buffer.
7212 (when (and flag (> (line-beginning-position) post))
7213 (goto-char post)))))))
7215 (defun org-subtree-end-visible-p ()
7216 "Is the end of the current subtree visible?"
7217 (pos-visible-in-window-p
7218 (save-excursion (org-end-of-subtree t) (point))))
7220 (defun org-first-headline-recenter (&optional N)
7221 "Move cursor to the first headline and recenter the headline.
7222 Optional argument N means put the headline into the Nth line of the window."
7223 (goto-char (point-min))
7224 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7225 (beginning-of-line)
7226 (recenter (prefix-numeric-value N))))
7228 ;;; Saving and restoring visibility
7230 (defun org-outline-overlay-data (&optional use-markers)
7231 "Return a list of the locations of all outline overlays.
7232 These are overlays with the `invisible' property value `outline'.
7233 The return value is a list of cons cells, with start and stop
7234 positions for each overlay.
7235 If USE-MARKERS is set, return the positions as markers."
7236 (let (beg end)
7237 (save-excursion
7238 (save-restriction
7239 (widen)
7240 (delq nil
7241 (mapcar (lambda (o)
7242 (when (eq (overlay-get o 'invisible) 'outline)
7243 (setq beg (overlay-start o)
7244 end (overlay-end o))
7245 (and beg end (> end beg)
7246 (if use-markers
7247 (cons (copy-marker beg)
7248 (copy-marker end t))
7249 (cons beg end)))))
7250 (overlays-in (point-min) (point-max))))))))
7252 (defun org-set-outline-overlay-data (data)
7253 "Create visibility overlays for all positions in DATA.
7254 DATA should have been made by `org-outline-overlay-data'."
7255 (let (o)
7256 (save-excursion
7257 (save-restriction
7258 (widen)
7259 (show-all)
7260 (mapc (lambda (c)
7261 (outline-flag-region (car c) (cdr c) t))
7262 data)))))
7264 ;;; Folding of blocks
7266 (defvar org-hide-block-overlays nil
7267 "Overlays hiding blocks.")
7268 (make-variable-buffer-local 'org-hide-block-overlays)
7270 (defun org-block-map (function &optional start end)
7271 "Call FUNCTION at the head of all source blocks in the current buffer.
7272 Optional arguments START and END can be used to limit the range."
7273 (let ((start (or start (point-min)))
7274 (end (or end (point-max))))
7275 (save-excursion
7276 (goto-char start)
7277 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7278 (save-excursion
7279 (save-match-data
7280 (goto-char (match-beginning 0))
7281 (funcall function)))))))
7283 (defun org-hide-block-toggle-all ()
7284 "Toggle the visibility of all blocks in the current buffer."
7285 (org-block-map #'org-hide-block-toggle))
7287 (defun org-hide-block-all ()
7288 "Fold all blocks in the current buffer."
7289 (interactive)
7290 (org-show-block-all)
7291 (org-block-map #'org-hide-block-toggle-maybe))
7293 (defun org-show-block-all ()
7294 "Unfold all blocks in the current buffer."
7295 (interactive)
7296 (mapc 'delete-overlay org-hide-block-overlays)
7297 (setq org-hide-block-overlays nil))
7299 (defun org-hide-block-toggle-maybe ()
7300 "Toggle visibility of block at point."
7301 (interactive)
7302 (let ((case-fold-search t))
7303 (if (save-excursion
7304 (beginning-of-line 1)
7305 (looking-at org-block-regexp))
7306 (progn (org-hide-block-toggle)
7307 t) ;; to signal that we took action
7308 nil))) ;; to signal that we did not
7310 (defun org-hide-block-toggle (&optional force)
7311 "Toggle the visibility of the current block."
7312 (interactive)
7313 (save-excursion
7314 (beginning-of-line)
7315 (if (re-search-forward org-block-regexp nil t)
7316 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7317 (end (match-end 0)) ;; end of entire body
7319 (if (memq t (mapcar (lambda (overlay)
7320 (eq (overlay-get overlay 'invisible)
7321 'org-hide-block))
7322 (overlays-at start)))
7323 (if (or (not force) (eq force 'off))
7324 (mapc (lambda (ov)
7325 (when (member ov org-hide-block-overlays)
7326 (setq org-hide-block-overlays
7327 (delq ov org-hide-block-overlays)))
7328 (when (eq (overlay-get ov 'invisible)
7329 'org-hide-block)
7330 (delete-overlay ov)))
7331 (overlays-at start)))
7332 (setq ov (make-overlay start end))
7333 (overlay-put ov 'invisible 'org-hide-block)
7334 ;; make the block accessible to isearch
7335 (overlay-put
7336 ov 'isearch-open-invisible
7337 (lambda (ov)
7338 (when (member ov org-hide-block-overlays)
7339 (setq org-hide-block-overlays
7340 (delq ov org-hide-block-overlays)))
7341 (when (eq (overlay-get ov 'invisible)
7342 'org-hide-block)
7343 (delete-overlay ov))))
7344 (push ov org-hide-block-overlays)))
7345 (user-error "Not looking at a source block"))))
7347 ;; org-tab-after-check-for-cycling-hook
7348 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7349 ;; Remove overlays when changing major mode
7350 (add-hook 'org-mode-hook
7351 (lambda () (org-add-hook 'change-major-mode-hook
7352 'org-show-block-all 'append 'local)))
7354 ;;; Org-goto
7356 (defvar org-goto-window-configuration nil)
7357 (defvar org-goto-marker nil)
7358 (defvar org-goto-map)
7359 (defun org-goto-map ()
7360 "Set the keymap `org-goto'."
7361 (setq org-goto-map
7362 (let ((map (make-sparse-keymap)))
7363 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7364 mouse-drag-region universal-argument org-occur))
7365 cmd)
7366 (while (setq cmd (pop cmds))
7367 (substitute-key-definition cmd cmd map global-map)))
7368 (suppress-keymap map)
7369 (org-defkey map "\C-m" 'org-goto-ret)
7370 (org-defkey map [(return)] 'org-goto-ret)
7371 (org-defkey map [(left)] 'org-goto-left)
7372 (org-defkey map [(right)] 'org-goto-right)
7373 (org-defkey map [(control ?g)] 'org-goto-quit)
7374 (org-defkey map "\C-i" 'org-cycle)
7375 (org-defkey map [(tab)] 'org-cycle)
7376 (org-defkey map [(down)] 'outline-next-visible-heading)
7377 (org-defkey map [(up)] 'outline-previous-visible-heading)
7378 (if org-goto-auto-isearch
7379 (if (fboundp 'define-key-after)
7380 (define-key-after map [t] 'org-goto-local-auto-isearch)
7381 nil)
7382 (org-defkey map "q" 'org-goto-quit)
7383 (org-defkey map "n" 'outline-next-visible-heading)
7384 (org-defkey map "p" 'outline-previous-visible-heading)
7385 (org-defkey map "f" 'outline-forward-same-level)
7386 (org-defkey map "b" 'outline-backward-same-level)
7387 (org-defkey map "u" 'outline-up-heading))
7388 (org-defkey map "/" 'org-occur)
7389 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7390 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7391 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7392 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7393 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7394 map)))
7396 (defconst org-goto-help
7397 "Browse buffer copy, to find location or copy text.%s
7398 RET=jump to location C-g=quit and return to previous location
7399 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7401 (defvar org-goto-start-pos) ; dynamically scoped parameter
7403 (defun org-goto (&optional alternative-interface)
7404 "Look up a different location in the current file, keeping current visibility.
7406 When you want look-up or go to a different location in a
7407 document, the fastest way is often to fold the entire buffer and
7408 then dive into the tree. This method has the disadvantage, that
7409 the previous location will be folded, which may not be what you
7410 want.
7412 This command works around this by showing a copy of the current
7413 buffer in an indirect buffer, in overview mode. You can dive
7414 into the tree in that copy, use org-occur and incremental search
7415 to find a location. When pressing RET or `Q', the command
7416 returns to the original buffer in which the visibility is still
7417 unchanged. After RET it will also jump to the location selected
7418 in the indirect buffer and expose the headline hierarchy above.
7420 With a prefix argument, use the alternative interface: e.g. if
7421 `org-goto-interface' is 'outline use 'outline-path-completion."
7422 (interactive "P")
7423 (org-goto-map)
7424 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7425 (org-refile-use-outline-path t)
7426 (org-refile-target-verify-function nil)
7427 (interface
7428 (if (not alternative-interface)
7429 org-goto-interface
7430 (if (eq org-goto-interface 'outline)
7431 'outline-path-completion
7432 'outline)))
7433 (org-goto-start-pos (point))
7434 (selected-point
7435 (if (eq interface 'outline)
7436 (car (org-get-location (current-buffer) org-goto-help))
7437 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7438 (org-refile-check-position pa)
7439 (nth 3 pa)))))
7440 (if selected-point
7441 (progn
7442 (org-mark-ring-push org-goto-start-pos)
7443 (goto-char selected-point)
7444 (if (or (outline-invisible-p) (org-invisible-p2))
7445 (org-show-context 'org-goto)))
7446 (message "Quit"))))
7448 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7449 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7450 (defvar org-goto-local-auto-isearch-map) ; defined below
7452 (defun org-get-location (buf help)
7453 "Let the user select a location in the Org-mode buffer BUF.
7454 This function uses a recursive edit. It returns the selected position
7455 or nil."
7456 (org-no-popups
7457 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7458 (isearch-hide-immediately nil)
7459 (isearch-search-fun-function
7460 (lambda () 'org-goto-local-search-headings))
7461 (org-goto-selected-point org-goto-exit-command))
7462 (save-excursion
7463 (save-window-excursion
7464 (delete-other-windows)
7465 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7466 (org-pop-to-buffer-same-window
7467 (condition-case nil
7468 (make-indirect-buffer (current-buffer) "*org-goto*")
7469 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7470 (with-output-to-temp-buffer "*Org Help*"
7471 (princ (format help (if org-goto-auto-isearch
7472 " Just type for auto-isearch."
7473 " n/p/f/b/u to navigate, q to quit."))))
7474 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7475 (setq buffer-read-only nil)
7476 (let ((org-startup-truncated t)
7477 (org-startup-folded nil)
7478 (org-startup-align-all-tables nil))
7479 (org-mode)
7480 (org-overview))
7481 (setq buffer-read-only t)
7482 (if (and (boundp 'org-goto-start-pos)
7483 (integer-or-marker-p org-goto-start-pos))
7484 (let ((org-show-hierarchy-above t)
7485 (org-show-siblings t)
7486 (org-show-following-heading t))
7487 (goto-char org-goto-start-pos)
7488 (and (outline-invisible-p) (org-show-context)))
7489 (goto-char (point-min)))
7490 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7491 (message "Select location and press RET")
7492 (use-local-map org-goto-map)
7493 (recursive-edit)))
7494 (kill-buffer "*org-goto*")
7495 (cons org-goto-selected-point org-goto-exit-command))))
7497 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7498 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7499 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7500 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7502 (defun org-goto-local-search-headings (string bound noerror)
7503 "Search and make sure that any matches are in headlines."
7504 (catch 'return
7505 (while (if isearch-forward
7506 (search-forward string bound noerror)
7507 (search-backward string bound noerror))
7508 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7509 (and (member :headline context)
7510 (not (member :tags context))))
7511 (throw 'return (point))))))
7513 (defun org-goto-local-auto-isearch ()
7514 "Start isearch."
7515 (interactive)
7516 (goto-char (point-min))
7517 (let ((keys (this-command-keys)))
7518 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7519 (isearch-mode t)
7520 (isearch-process-search-char (string-to-char keys)))))
7522 (defun org-goto-ret (&optional arg)
7523 "Finish `org-goto' by going to the new location."
7524 (interactive "P")
7525 (setq org-goto-selected-point (point)
7526 org-goto-exit-command 'return)
7527 (throw 'exit nil))
7529 (defun org-goto-left ()
7530 "Finish `org-goto' by going to the new location."
7531 (interactive)
7532 (if (org-at-heading-p)
7533 (progn
7534 (beginning-of-line 1)
7535 (setq org-goto-selected-point (point)
7536 org-goto-exit-command 'left)
7537 (throw 'exit nil))
7538 (user-error "Not on a heading")))
7540 (defun org-goto-right ()
7541 "Finish `org-goto' by going to the new location."
7542 (interactive)
7543 (if (org-at-heading-p)
7544 (progn
7545 (setq org-goto-selected-point (point)
7546 org-goto-exit-command 'right)
7547 (throw 'exit nil))
7548 (user-error "Not on a heading")))
7550 (defun org-goto-quit ()
7551 "Finish `org-goto' without cursor motion."
7552 (interactive)
7553 (setq org-goto-selected-point nil)
7554 (setq org-goto-exit-command 'quit)
7555 (throw 'exit nil))
7557 ;;; Indirect buffer display of subtrees
7559 (defvar org-indirect-dedicated-frame nil
7560 "This is the frame being used for indirect tree display.")
7561 (defvar org-last-indirect-buffer nil)
7563 (defun org-tree-to-indirect-buffer (&optional arg)
7564 "Create indirect buffer and narrow it to current subtree.
7565 With a numerical prefix ARG, go up to this level and then take that tree.
7566 If ARG is negative, go up that many levels.
7568 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7569 indirect buffer previously made with this command, to avoid proliferation of
7570 indirect buffers. However, when you call the command with a \
7571 \\[universal-argument] prefix, or
7572 when `org-indirect-buffer-display' is `new-frame', the last buffer
7573 is kept so that you can work with several indirect buffers at the same time.
7574 If `org-indirect-buffer-display' is `dedicated-frame', the \
7575 \\[universal-argument] prefix also
7576 requests that a new frame be made for the new buffer, so that the dedicated
7577 frame is not changed."
7578 (interactive "P")
7579 (let ((cbuf (current-buffer))
7580 (cwin (selected-window))
7581 (pos (point))
7582 beg end level heading ibuf)
7583 (save-excursion
7584 (org-back-to-heading t)
7585 (when (numberp arg)
7586 (setq level (org-outline-level))
7587 (if (< arg 0) (setq arg (+ level arg)))
7588 (while (> (setq level (org-outline-level)) arg)
7589 (org-up-heading-safe)))
7590 (setq beg (point)
7591 heading (org-get-heading))
7592 (org-end-of-subtree t t)
7593 (if (org-at-heading-p) (backward-char 1))
7594 (setq end (point)))
7595 (if (and (buffer-live-p org-last-indirect-buffer)
7596 (not (eq org-indirect-buffer-display 'new-frame))
7597 (not arg))
7598 (kill-buffer org-last-indirect-buffer))
7599 (setq ibuf (org-get-indirect-buffer cbuf heading)
7600 org-last-indirect-buffer ibuf)
7601 (cond
7602 ((or (eq org-indirect-buffer-display 'new-frame)
7603 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7604 (select-frame (make-frame))
7605 (delete-other-windows)
7606 (org-pop-to-buffer-same-window ibuf)
7607 (org-set-frame-title heading))
7608 ((eq org-indirect-buffer-display 'dedicated-frame)
7609 (raise-frame
7610 (select-frame (or (and org-indirect-dedicated-frame
7611 (frame-live-p org-indirect-dedicated-frame)
7612 org-indirect-dedicated-frame)
7613 (setq org-indirect-dedicated-frame (make-frame)))))
7614 (delete-other-windows)
7615 (org-pop-to-buffer-same-window ibuf)
7616 (org-set-frame-title (concat "Indirect: " heading)))
7617 ((eq org-indirect-buffer-display 'current-window)
7618 (org-pop-to-buffer-same-window ibuf))
7619 ((eq org-indirect-buffer-display 'other-window)
7620 (pop-to-buffer ibuf))
7621 (t (error "Invalid value")))
7622 (if (featurep 'xemacs)
7623 (save-excursion (org-mode) (turn-on-font-lock)))
7624 (narrow-to-region beg end)
7625 (show-all)
7626 (goto-char pos)
7627 (run-hook-with-args 'org-cycle-hook 'all)
7628 (and (window-live-p cwin) (select-window cwin))))
7630 (defun org-get-indirect-buffer (&optional buffer heading)
7631 (setq buffer (or buffer (current-buffer)))
7632 (let ((n 1) (base (buffer-name buffer)) bname)
7633 (while (buffer-live-p
7634 (get-buffer
7635 (setq bname
7636 (concat base "-"
7637 (if heading (concat heading "-" (number-to-string n))
7638 (number-to-string n))))))
7639 (setq n (1+ n)))
7640 (condition-case nil
7641 (make-indirect-buffer buffer bname 'clone)
7642 (error (make-indirect-buffer buffer bname)))))
7644 (defun org-set-frame-title (title)
7645 "Set the title of the current frame to the string TITLE."
7646 ;; FIXME: how to name a single frame in XEmacs???
7647 (unless (featurep 'xemacs)
7648 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7650 ;;;; Structure editing
7652 ;;; Inserting headlines
7654 (defun org-previous-line-empty-p (&optional next)
7655 "Is the previous line a blank line?
7656 When NEXT is non-nil, check the next line instead."
7657 (save-excursion
7658 (and (not (bobp))
7659 (or (beginning-of-line (if next 2 0)) t)
7660 (save-match-data
7661 (looking-at "[ \t]*$")))))
7663 (defun org-insert-heading (&optional arg invisible-ok)
7664 "Insert a new heading or item with same depth at point.
7666 If point is in a plain list and ARG is nil, add a new list item.
7668 With one universal prefix argument, insert a heading even when
7669 the point is within a list.
7671 With two universal prefix arguments, insert the heading at the
7672 end of the grandparent subtree. For example, if point is within
7673 a 2nd-level heading, then it will insert a 2nd-level heading at
7674 the end of the 1st-level parent heading.
7676 If point is at the beginning of a headline, insert a sibling
7677 before the current headline. If point is not at the beginning,
7678 split the line and create a new headline with the text in the
7679 current line after point \(see `org-M-RET-may-split-line' on how
7680 to modify this behavior).
7682 If point is at the beginning of a normal line, turn this line
7683 into a heading.
7685 When INVISIBLE-OK is set, stop at invisible headlines when going
7686 back. This is important for non-interactive uses of the
7687 command."
7688 (interactive "P")
7689 (if (org-called-interactively-p 'any) (org-reveal))
7690 (let ((itemp (org-in-item-p))
7691 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7692 (respect-content (or org-insert-heading-respect-content
7693 (equal arg '(4))))
7694 (initial-content "")
7695 (adjust-empty-lines t))
7697 (cond
7699 ((or (= (buffer-size) 0)
7700 (and (not (save-excursion
7701 (and (ignore-errors (org-back-to-heading invisible-ok))
7702 (org-at-heading-p))))
7703 (or arg (not itemp))))
7704 ;; At beginning of buffer or so high up that only a heading
7705 ;; makes sense.
7706 (when (and (org-before-first-heading-p) (not (bolp)))
7707 (re-search-forward org-outline-regexp-bol)
7708 (beginning-of-line 0))
7709 (insert
7710 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7711 (if (org-in-src-block-p) ",* " "* "))
7712 (run-hooks 'org-insert-heading-hook))
7714 ((and itemp (not (equal arg '(4))))
7715 ;; Insert an item
7716 (org-insert-item))
7719 ;; Maybe move at the end of the subtree
7720 (when (equal arg '(16))
7721 (org-up-heading-safe)
7722 (org-end-of-subtree t))
7723 ;; Insert a heading
7724 (save-restriction
7725 (widen)
7726 (let* ((level nil)
7727 (on-heading (org-at-heading-p))
7728 (empty-line-p (if on-heading
7729 (org-previous-line-empty-p)
7730 ;; We will decide later
7731 nil))
7732 ;; Get a level string to fall back on
7733 (fix-level
7734 (if (org-before-first-heading-p) "*"
7735 (save-excursion
7736 (org-back-to-heading t)
7737 (if (org-previous-line-empty-p) (setq empty-line-p t))
7738 (looking-at org-outline-regexp)
7739 (make-string (1- (length (match-string 0))) ?*))))
7740 (stars
7741 (save-excursion
7742 (condition-case nil
7743 (progn
7744 (org-back-to-heading invisible-ok)
7745 (when (and (not on-heading)
7746 (featurep 'org-inlinetask)
7747 (integerp org-inlinetask-min-level)
7748 (>= (length (match-string 0))
7749 org-inlinetask-min-level))
7750 ;; Find a heading level before the inline task
7751 (while (and (setq level (org-up-heading-safe))
7752 (>= level org-inlinetask-min-level)))
7753 (if (org-at-heading-p)
7754 (org-back-to-heading invisible-ok)
7755 (error "This should not happen")))
7756 (unless (and (save-excursion
7757 (save-match-data
7758 (org-backward-heading-same-level
7759 1 invisible-ok))
7760 (= (point) (match-beginning 0)))
7761 (not (org-previous-line-empty-p t)))
7762 (setq empty-line-p (or empty-line-p
7763 (org-previous-line-empty-p))))
7764 (match-string 0))
7765 (error (or fix-level "* ")))))
7766 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7767 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7768 pos hide-previous previous-pos)
7770 ;; If we insert after content, move there and clean up whitespace
7771 (when (and respect-content
7772 (not (org-looking-at-p org-outline-regexp-bol))
7773 (not (bolp)))
7774 (if (not (org-before-first-heading-p))
7775 (org-end-of-subtree nil t)
7776 (re-search-forward org-outline-regexp-bol)
7777 (beginning-of-line 0))
7778 (skip-chars-backward " \r\n")
7779 (and (not (looking-back "^\\*+"))
7780 (looking-at "[ \t]+") (replace-match ""))
7781 (unless (eobp) (forward-char 1))
7782 (when (looking-at "^\\*")
7783 (unless (bobp) (backward-char 1))
7784 (insert "\n")))
7786 ;; If we are splitting, grab the text that should be moved to the new headline
7787 (when may-split
7788 (if (org-on-heading-p)
7789 ;; This is a heading, we split intelligently (keeping tags)
7790 (let ((pos (point)))
7791 (goto-char (point-at-bol))
7792 (unless (looking-at org-complex-heading-regexp)
7793 (error "This should not happen"))
7794 (when (and (match-beginning 4)
7795 (> pos (match-beginning 4))
7796 (< pos (match-end 4)))
7797 (setq initial-content (buffer-substring pos (match-end 4)))
7798 (goto-char pos)
7799 (delete-region (point) (match-end 4))
7800 (if (looking-at "[ \t]*$")
7801 (replace-match "")
7802 (insert (make-string (length initial-content) ?\ )))
7803 (setq initial-content (org-trim initial-content)))
7804 (goto-char pos))
7805 ;; a normal line
7806 (setq initial-content
7807 (org-trim (buffer-substring (point) (point-at-eol))))
7808 (delete-region (point) (point-at-eol))))
7810 ;; If we are at the beginning of the line, insert before it. Else after
7811 (cond
7812 ((and (bolp) (looking-at "[ \t]*$")))
7813 ((and (bolp) (not (looking-at "[ \t]*$")))
7814 (open-line 1))
7816 (goto-char (point-at-eol))
7817 (insert "\n")))
7819 ;; Insert the new heading
7820 (insert stars)
7821 (just-one-space)
7822 (insert initial-content)
7823 (when adjust-empty-lines
7824 (if (or (not blank)
7825 (and blank (not (org-previous-line-empty-p))))
7826 (org-N-empty-lines-before-current (if blank 1 0))))
7827 (run-hooks 'org-insert-heading-hook)))))))
7829 (defun org-N-empty-lines-before-current (N)
7830 "Make the number of empty lines before current exactly N.
7831 So this will delete or add empty lines."
7832 (save-excursion
7833 (goto-char (point-at-bol))
7834 (if (looking-back "\\s-+" nil 'greedy)
7835 (replace-match ""))
7836 (or (bobp) (insert "\n"))
7837 (while (> N 0)
7838 (insert "\n")
7839 (setq N (1- N)))))
7841 (defun org-get-heading (&optional no-tags no-todo)
7842 "Return the heading of the current entry, without the stars.
7843 When NO-TAGS is non-nil, don't include tags.
7844 When NO-TODO is non-nil, don't include TODO keywords."
7845 (save-excursion
7846 (org-back-to-heading t)
7847 (cond
7848 ((and no-tags no-todo)
7849 (looking-at org-complex-heading-regexp)
7850 (match-string 4))
7851 (no-tags
7852 (looking-at (concat org-outline-regexp
7853 "\\(.*?\\)"
7854 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7855 (match-string 1))
7856 (no-todo
7857 (looking-at org-todo-line-regexp)
7858 (match-string 3))
7859 (t (looking-at org-heading-regexp)
7860 (match-string 2)))))
7862 (defvar orgstruct-mode) ; defined below
7864 (defun org-heading-components ()
7865 "Return the components of the current heading.
7866 This is a list with the following elements:
7867 - the level as an integer
7868 - the reduced level, different if `org-odd-levels-only' is set.
7869 - the TODO keyword, or nil
7870 - the priority character, like ?A, or nil if no priority is given
7871 - the headline text itself, or the tags string if no headline text
7872 - the tags string, or nil."
7873 (save-excursion
7874 (org-back-to-heading t)
7875 (if (let (case-fold-search)
7876 (looking-at
7877 (if orgstruct-mode
7878 org-heading-regexp
7879 org-complex-heading-regexp)))
7880 (if orgstruct-mode
7881 (list (length (match-string 1))
7882 (org-reduced-level (length (match-string 1)))
7885 (match-string 2)
7886 nil)
7887 (list (length (match-string 1))
7888 (org-reduced-level (length (match-string 1)))
7889 (org-match-string-no-properties 2)
7890 (and (match-end 3) (aref (match-string 3) 2))
7891 (org-match-string-no-properties 4)
7892 (org-match-string-no-properties 5))))))
7894 (defun org-get-entry ()
7895 "Get the entry text, after heading, entire subtree."
7896 (save-excursion
7897 (org-back-to-heading t)
7898 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7900 (defun org-insert-heading-after-current ()
7901 "Insert a new heading with same level as current, after current subtree."
7902 (interactive)
7903 (org-back-to-heading)
7904 (org-insert-heading)
7905 (org-move-subtree-down)
7906 (end-of-line 1))
7908 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7909 "Insert heading with `org-insert-heading-respect-content' set to t."
7910 (interactive "P")
7911 (let ((org-insert-heading-respect-content t))
7912 (org-insert-heading '(4) invisible-ok)))
7914 (defun org-insert-todo-heading-respect-content (&optional force-state)
7915 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7916 (interactive "P")
7917 (let ((org-insert-heading-respect-content t))
7918 (org-insert-todo-heading force-state '(4))))
7920 (defun org-insert-todo-heading (arg &optional force-heading)
7921 "Insert a new heading with the same level and TODO state as current heading.
7922 If the heading has no TODO state, or if the state is DONE, use the first
7923 state (TODO by default). Also with one prefix arg, force first state. With
7924 two prefix args, force inserting at the end of the parent subtree."
7925 (interactive "P")
7926 (when (or force-heading (not (org-insert-item 'checkbox)))
7927 (org-insert-heading (or (and (equal arg '(16)) '(16))
7928 force-heading))
7929 (save-excursion
7930 (org-back-to-heading)
7931 (outline-previous-heading)
7932 (looking-at org-todo-line-regexp))
7933 (let*
7934 ((new-mark-x
7935 (if (or (equal arg '(4))
7936 (not (match-beginning 2))
7937 (member (match-string 2) org-done-keywords))
7938 (car org-todo-keywords-1)
7939 (match-string 2)))
7940 (new-mark
7942 (run-hook-with-args-until-success
7943 'org-todo-get-default-hook new-mark-x nil)
7944 new-mark-x)))
7945 (beginning-of-line 1)
7946 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7947 (if org-treat-insert-todo-heading-as-state-change
7948 (org-todo new-mark)
7949 (insert new-mark " "))))
7950 (when org-provide-todo-statistics
7951 (org-update-parent-todo-statistics))))
7953 (defun org-insert-subheading (arg)
7954 "Insert a new subheading and demote it.
7955 Works for outline headings and for plain lists alike."
7956 (interactive "P")
7957 (org-insert-heading arg)
7958 (cond
7959 ((org-at-heading-p) (org-do-demote))
7960 ((org-at-item-p) (org-indent-item))))
7962 (defun org-insert-todo-subheading (arg)
7963 "Insert a new subheading with TODO keyword or checkbox and demote it.
7964 Works for outline headings and for plain lists alike."
7965 (interactive "P")
7966 (org-insert-todo-heading arg)
7967 (cond
7968 ((org-at-heading-p) (org-do-demote))
7969 ((org-at-item-p) (org-indent-item))))
7971 ;;; Promotion and Demotion
7973 (defvar org-after-demote-entry-hook nil
7974 "Hook run after an entry has been demoted.
7975 The cursor will be at the beginning of the entry.
7976 When a subtree is being demoted, the hook will be called for each node.")
7978 (defvar org-after-promote-entry-hook nil
7979 "Hook run after an entry has been promoted.
7980 The cursor will be at the beginning of the entry.
7981 When a subtree is being promoted, the hook will be called for each node.")
7983 (defun org-promote-subtree ()
7984 "Promote the entire subtree.
7985 See also `org-promote'."
7986 (interactive)
7987 (save-excursion
7988 (org-with-limited-levels (org-map-tree 'org-promote)))
7989 (org-fix-position-after-promote))
7991 (defun org-demote-subtree ()
7992 "Demote the entire subtree. See `org-demote'.
7993 See also `org-promote'."
7994 (interactive)
7995 (save-excursion
7996 (org-with-limited-levels (org-map-tree 'org-demote)))
7997 (org-fix-position-after-promote))
8000 (defun org-do-promote ()
8001 "Promote the current heading higher up the tree.
8002 If the region is active in `transient-mark-mode', promote all headings
8003 in the region."
8004 (interactive)
8005 (save-excursion
8006 (if (org-region-active-p)
8007 (org-map-region 'org-promote (region-beginning) (region-end))
8008 (org-promote)))
8009 (org-fix-position-after-promote))
8011 (defun org-do-demote ()
8012 "Demote the current heading lower down the tree.
8013 If the region is active in `transient-mark-mode', demote all headings
8014 in the region."
8015 (interactive)
8016 (save-excursion
8017 (if (org-region-active-p)
8018 (org-map-region 'org-demote (region-beginning) (region-end))
8019 (org-demote)))
8020 (org-fix-position-after-promote))
8022 (defun org-fix-position-after-promote ()
8023 "Make sure that after pro/demotion cursor position is right."
8024 (let ((pos (point)))
8025 (when (save-excursion
8026 (beginning-of-line 1)
8027 (looking-at org-todo-line-regexp)
8028 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8029 (cond ((eobp) (insert " "))
8030 ((eolp) (insert " "))
8031 ((equal (char-after) ?\ ) (forward-char 1))))))
8033 (defun org-current-level ()
8034 "Return the level of the current entry, or nil if before the first headline.
8035 The level is the number of stars at the beginning of the headline."
8036 (save-excursion
8037 (org-with-limited-levels
8038 (if (ignore-errors (org-back-to-heading t))
8039 (funcall outline-level)))))
8041 (defun org-get-previous-line-level ()
8042 "Return the outline depth of the last headline before the current line.
8043 Returns 0 for the first headline in the buffer, and nil if before the
8044 first headline."
8045 (and (org-current-level)
8046 (or (and (/= (line-beginning-position) (point-min))
8047 (save-excursion (beginning-of-line 0) (org-current-level)))
8048 0)))
8050 (defun org-reduced-level (l)
8051 "Compute the effective level of a heading.
8052 This takes into account the setting of `org-odd-levels-only'."
8053 (cond
8054 ((zerop l) 0)
8055 (org-odd-levels-only (1+ (floor (/ l 2))))
8056 (t l)))
8058 (defun org-level-increment ()
8059 "Return the number of stars that will be added or removed at a
8060 time to headlines when structure editing, based on the value of
8061 `org-odd-levels-only'."
8062 (if org-odd-levels-only 2 1))
8064 (defun org-get-valid-level (level &optional change)
8065 "Rectify a level change under the influence of `org-odd-levels-only'
8066 LEVEL is a current level, CHANGE is by how much the level should be
8067 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8068 even level numbers will become the next higher odd number."
8069 (if org-odd-levels-only
8070 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8071 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8072 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8073 (max 1 (+ level (or change 0)))))
8075 (if (boundp 'define-obsolete-function-alias)
8076 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8077 (define-obsolete-function-alias 'org-get-legal-level
8078 'org-get-valid-level)
8079 (define-obsolete-function-alias 'org-get-legal-level
8080 'org-get-valid-level "23.1")))
8082 (defun org-promote ()
8083 "Promote the current heading higher up the tree.
8084 If the region is active in `transient-mark-mode', promote all headings
8085 in the region."
8086 (org-back-to-heading t)
8087 (let* ((level (save-match-data (funcall outline-level)))
8088 (after-change-functions (remove 'flyspell-after-change-function
8089 after-change-functions))
8090 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8091 (diff (abs (- level (length up-head) -1))))
8092 (cond ((and (= level 1) org-called-with-limited-levels
8093 org-allow-promoting-top-level-subtree)
8094 (replace-match "# " nil t))
8095 ((= level 1)
8096 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8097 (t (replace-match up-head nil t)))
8098 ;; Fixup tag positioning
8099 (unless (= level 1)
8100 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8101 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8102 (run-hooks 'org-after-promote-entry-hook)))
8104 (defun org-demote ()
8105 "Demote the current heading lower down the tree.
8106 If the region is active in `transient-mark-mode', demote all headings
8107 in the region."
8108 (org-back-to-heading t)
8109 (let* ((level (save-match-data (funcall outline-level)))
8110 (after-change-functions (remove 'flyspell-after-change-function
8111 after-change-functions))
8112 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8113 (diff (abs (- level (length down-head) -1))))
8114 (replace-match down-head nil t)
8115 ;; Fixup tag positioning
8116 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8117 (if org-adapt-indentation (org-fixup-indentation diff))
8118 (run-hooks 'org-after-demote-entry-hook)))
8120 (defun org-cycle-level ()
8121 "Cycle the level of an empty headline through possible states.
8122 This goes first to child, then to parent, level, then up the hierarchy.
8123 After top level, it switches back to sibling level."
8124 (interactive)
8125 (let ((org-adapt-indentation nil))
8126 (when (org-point-at-end-of-empty-headline)
8127 (setq this-command 'org-cycle-level) ; Only needed for caching
8128 (let ((cur-level (org-current-level))
8129 (prev-level (org-get-previous-line-level)))
8130 (cond
8131 ;; If first headline in file, promote to top-level.
8132 ((= prev-level 0)
8133 (loop repeat (/ (- cur-level 1) (org-level-increment))
8134 do (org-do-promote)))
8135 ;; If same level as prev, demote one.
8136 ((= prev-level cur-level)
8137 (org-do-demote))
8138 ;; If parent is top-level, promote to top level if not already.
8139 ((= prev-level 1)
8140 (loop repeat (/ (- cur-level 1) (org-level-increment))
8141 do (org-do-promote)))
8142 ;; If top-level, return to prev-level.
8143 ((= cur-level 1)
8144 (loop repeat (/ (- prev-level 1) (org-level-increment))
8145 do (org-do-demote)))
8146 ;; If less than prev-level, promote one.
8147 ((< cur-level prev-level)
8148 (org-do-promote))
8149 ;; If deeper than prev-level, promote until higher than
8150 ;; prev-level.
8151 ((> cur-level prev-level)
8152 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8153 do (org-do-promote))))
8154 t))))
8156 (defun org-map-tree (fun)
8157 "Call FUN for every heading underneath the current one."
8158 (org-back-to-heading)
8159 (let ((level (funcall outline-level)))
8160 (save-excursion
8161 (funcall fun)
8162 (while (and (progn
8163 (outline-next-heading)
8164 (> (funcall outline-level) level))
8165 (not (eobp)))
8166 (funcall fun)))))
8168 (defun org-map-region (fun beg end)
8169 "Call FUN for every heading between BEG and END."
8170 (let ((org-ignore-region t))
8171 (save-excursion
8172 (setq end (copy-marker end))
8173 (goto-char beg)
8174 (if (and (re-search-forward org-outline-regexp-bol nil t)
8175 (< (point) end))
8176 (funcall fun))
8177 (while (and (progn
8178 (outline-next-heading)
8179 (< (point) end))
8180 (not (eobp)))
8181 (funcall fun)))))
8183 (defvar org-property-end-re) ; silence byte-compiler
8184 (defun org-fixup-indentation (diff)
8185 "Change the indentation in the current entry by DIFF.
8186 However, if any line in the current entry has no indentation, or if it
8187 would end up with no indentation after the change, nothing at all is done."
8188 (save-excursion
8189 (let ((end (save-excursion (outline-next-heading)
8190 (point-marker)))
8191 (prohibit (if (> diff 0)
8192 "^\\S-"
8193 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8194 col)
8195 (unless (save-excursion (end-of-line 1)
8196 (re-search-forward prohibit end t))
8197 (while (and (< (point) end)
8198 (re-search-forward "^[ \t]+" end t))
8199 (goto-char (match-end 0))
8200 (setq col (current-column))
8201 (if (< diff 0) (replace-match ""))
8202 (org-indent-to-column (+ diff col))))
8203 (move-marker end nil))))
8205 (defun org-convert-to-odd-levels ()
8206 "Convert an org-mode file with all levels allowed to one with odd levels.
8207 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8208 level 5 etc."
8209 (interactive)
8210 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8211 (let ((outline-level 'org-outline-level)
8212 (org-odd-levels-only nil) n)
8213 (save-excursion
8214 (goto-char (point-min))
8215 (while (re-search-forward "^\\*\\*+ " nil t)
8216 (setq n (- (length (match-string 0)) 2))
8217 (while (>= (setq n (1- n)) 0)
8218 (org-demote))
8219 (end-of-line 1))))))
8221 (defun org-convert-to-oddeven-levels ()
8222 "Convert an org-mode file with only odd levels to one with odd/even levels.
8223 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8224 file contains a section with an even level, conversion would
8225 destroy the structure of the file. An error is signaled in this
8226 case."
8227 (interactive)
8228 (goto-char (point-min))
8229 ;; First check if there are no even levels
8230 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8231 (org-show-context t)
8232 (error "Not all levels are odd in this file. Conversion not possible"))
8233 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8234 (let ((outline-regexp org-outline-regexp)
8235 (outline-level 'org-outline-level)
8236 (org-odd-levels-only nil) n)
8237 (save-excursion
8238 (goto-char (point-min))
8239 (while (re-search-forward "^\\*\\*+ " nil t)
8240 (setq n (/ (1- (length (match-string 0))) 2))
8241 (while (>= (setq n (1- n)) 0)
8242 (org-promote))
8243 (end-of-line 1))))))
8245 (defun org-tr-level (n)
8246 "Make N odd if required."
8247 (if org-odd-levels-only (1+ (/ n 2)) n))
8249 ;;; Vertical tree motion, cutting and pasting of subtrees
8251 (defun org-move-subtree-up (&optional arg)
8252 "Move the current subtree up past ARG headlines of the same level."
8253 (interactive "p")
8254 (org-move-subtree-down (- (prefix-numeric-value arg))))
8256 (defun org-move-subtree-down (&optional arg)
8257 "Move the current subtree down past ARG headlines of the same level."
8258 (interactive "p")
8259 (setq arg (prefix-numeric-value arg))
8260 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8261 'org-get-last-sibling))
8262 (ins-point (make-marker))
8263 (cnt (abs arg))
8264 (col (current-column))
8265 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8266 ;; Select the tree
8267 (org-back-to-heading)
8268 (setq beg0 (point))
8269 (save-excursion
8270 (setq ne-beg (org-back-over-empty-lines))
8271 (setq beg (point)))
8272 (save-match-data
8273 (save-excursion (outline-end-of-heading)
8274 (setq folded (outline-invisible-p)))
8275 (progn (org-end-of-subtree nil t)
8276 (unless (eobp) (backward-char))))
8277 (outline-next-heading)
8278 (setq ne-end (org-back-over-empty-lines))
8279 (setq end (point))
8280 (goto-char beg0)
8281 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8282 ;; include less whitespace
8283 (save-excursion
8284 (goto-char beg)
8285 (forward-line (- ne-beg ne-end))
8286 (setq beg (point))))
8287 ;; Find insertion point, with error handling
8288 (while (> cnt 0)
8289 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8290 (progn (goto-char beg0)
8291 (user-error "Cannot move past superior level or buffer limit")))
8292 (setq cnt (1- cnt)))
8293 (if (> arg 0)
8294 ;; Moving forward - still need to move over subtree
8295 (progn (org-end-of-subtree t t)
8296 (save-excursion
8297 (org-back-over-empty-lines)
8298 (or (bolp) (newline)))))
8299 (setq ne-ins (org-back-over-empty-lines))
8300 (move-marker ins-point (point))
8301 (setq txt (buffer-substring beg end))
8302 (org-save-markers-in-region beg end)
8303 (delete-region beg end)
8304 (org-remove-empty-overlays-at beg)
8305 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8306 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8307 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8308 (let ((bbb (point)))
8309 (insert-before-markers txt)
8310 (org-reinstall-markers-in-region bbb)
8311 (move-marker ins-point bbb))
8312 (or (bolp) (insert "\n"))
8313 (setq ins-end (point))
8314 (goto-char ins-point)
8315 (org-skip-whitespace)
8316 (when (and (< arg 0)
8317 (org-first-sibling-p)
8318 (> ne-ins ne-beg))
8319 ;; Move whitespace back to beginning
8320 (save-excursion
8321 (goto-char ins-end)
8322 (let ((kill-whole-line t))
8323 (kill-line (- ne-ins ne-beg)) (point)))
8324 (insert (make-string (- ne-ins ne-beg) ?\n)))
8325 (move-marker ins-point nil)
8326 (if folded
8327 (hide-subtree)
8328 (org-show-entry)
8329 (show-children)
8330 (org-cycle-hide-drawers 'children))
8331 (org-clean-visibility-after-subtree-move)
8332 ;; move back to the initial column we were at
8333 (move-to-column col)))
8335 (defvar org-subtree-clip ""
8336 "Clipboard for cut and paste of subtrees.
8337 This is actually only a copy of the kill, because we use the normal kill
8338 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8340 (defvar org-subtree-clip-folded nil
8341 "Was the last copied subtree folded?
8342 This is used to fold the tree back after pasting.")
8344 (defun org-cut-subtree (&optional n)
8345 "Cut the current subtree into the clipboard.
8346 With prefix arg N, cut this many sequential subtrees.
8347 This is a short-hand for marking the subtree and then cutting it."
8348 (interactive "p")
8349 (org-copy-subtree n 'cut))
8351 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8352 "Copy the current subtree it in the clipboard.
8353 With prefix arg N, copy this many sequential subtrees.
8354 This is a short-hand for marking the subtree and then copying it.
8355 If CUT is non-nil, actually cut the subtree.
8356 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8357 of some markers in the region, even if CUT is non-nil. This is
8358 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8359 (interactive "p")
8360 (let (beg end folded (beg0 (point)))
8361 (if (org-called-interactively-p 'any)
8362 (org-back-to-heading nil) ; take what looks like a subtree
8363 (org-back-to-heading t)) ; take what is really there
8364 (setq beg (point))
8365 (skip-chars-forward " \t\r\n")
8366 (save-match-data
8367 (if nosubtrees
8368 (outline-next-heading)
8369 (save-excursion (outline-end-of-heading)
8370 (setq folded (outline-invisible-p)))
8371 (condition-case nil
8372 (org-forward-heading-same-level (1- n) t)
8373 (error nil))
8374 (org-end-of-subtree t t)))
8375 (setq end (point))
8376 (goto-char beg0)
8377 (when (> end beg)
8378 (setq org-subtree-clip-folded folded)
8379 (when (or cut force-store-markers)
8380 (org-save-markers-in-region beg end))
8381 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8382 (setq org-subtree-clip (current-kill 0))
8383 (message "%s: Subtree(s) with %d characters"
8384 (if cut "Cut" "Copied")
8385 (length org-subtree-clip)))))
8387 (defun org-paste-subtree (&optional level tree for-yank)
8388 "Paste the clipboard as a subtree, with modification of headline level.
8389 The entire subtree is promoted or demoted in order to match a new headline
8390 level.
8392 If the cursor is at the beginning of a headline, the same level as
8393 that headline is used to paste the tree.
8395 If not, the new level is derived from the *visible* headings
8396 before and after the insertion point, and taken to be the inferior headline
8397 level of the two. So if the previous visible heading is level 3 and the
8398 next is level 4 (or vice versa), level 4 will be used for insertion.
8399 This makes sure that the subtree remains an independent subtree and does
8400 not swallow low level entries.
8402 You can also force a different level, either by using a numeric prefix
8403 argument, or by inserting the heading marker by hand. For example, if the
8404 cursor is after \"*****\", then the tree will be shifted to level 5.
8406 If optional TREE is given, use this text instead of the kill ring.
8408 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8409 move back over whitespace before inserting, and move point to the end of
8410 the inserted text when done."
8411 (interactive "P")
8412 (setq tree (or tree (and kill-ring (current-kill 0))))
8413 (unless (org-kill-is-subtree-p tree)
8414 (user-error "%s"
8415 (substitute-command-keys
8416 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8417 (org-with-limited-levels
8418 (let* ((visp (not (outline-invisible-p)))
8419 (txt tree)
8420 (^re_ "\\(\\*+\\)[ \t]*")
8421 (old-level (if (string-match org-outline-regexp-bol txt)
8422 (- (match-end 0) (match-beginning 0) 1)
8423 -1))
8424 (force-level (cond (level (prefix-numeric-value level))
8425 ((and (looking-at "[ \t]*$")
8426 (string-match
8427 "^\\*+$" (buffer-substring
8428 (point-at-bol) (point))))
8429 (- (match-end 1) (match-beginning 1)))
8430 ((and (bolp)
8431 (looking-at org-outline-regexp))
8432 (- (match-end 0) (point) 1))))
8433 (previous-level (save-excursion
8434 (condition-case nil
8435 (progn
8436 (outline-previous-visible-heading 1)
8437 (if (looking-at ^re_)
8438 (- (match-end 0) (match-beginning 0) 1)
8440 (error 1))))
8441 (next-level (save-excursion
8442 (condition-case nil
8443 (progn
8444 (or (looking-at org-outline-regexp)
8445 (outline-next-visible-heading 1))
8446 (if (looking-at ^re_)
8447 (- (match-end 0) (match-beginning 0) 1)
8449 (error 1))))
8450 (new-level (or force-level (max previous-level next-level)))
8451 (shift (if (or (= old-level -1)
8452 (= new-level -1)
8453 (= old-level new-level))
8455 (- new-level old-level)))
8456 (delta (if (> shift 0) -1 1))
8457 (func (if (> shift 0) 'org-demote 'org-promote))
8458 (org-odd-levels-only nil)
8459 beg end newend)
8460 ;; Remove the forced level indicator
8461 (if force-level
8462 (delete-region (point-at-bol) (point)))
8463 ;; Paste
8464 (beginning-of-line (if (bolp) 1 2))
8465 (setq beg (point))
8466 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8467 (insert-before-markers txt)
8468 (unless (string-match "\n\\'" txt) (insert "\n"))
8469 (setq newend (point))
8470 (org-reinstall-markers-in-region beg)
8471 (setq end (point))
8472 (goto-char beg)
8473 (skip-chars-forward " \t\n\r")
8474 (setq beg (point))
8475 (if (and (outline-invisible-p) visp)
8476 (save-excursion (outline-show-heading)))
8477 ;; Shift if necessary
8478 (unless (= shift 0)
8479 (save-restriction
8480 (narrow-to-region beg end)
8481 (while (not (= shift 0))
8482 (org-map-region func (point-min) (point-max))
8483 (setq shift (+ delta shift)))
8484 (goto-char (point-min))
8485 (setq newend (point-max))))
8486 (when (or (org-called-interactively-p 'interactive) for-yank)
8487 (message "Clipboard pasted as level %d subtree" new-level))
8488 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8489 kill-ring
8490 (eq org-subtree-clip (current-kill 0))
8491 org-subtree-clip-folded)
8492 ;; The tree was folded before it was killed/copied
8493 (hide-subtree))
8494 (and for-yank (goto-char newend)))))
8496 (defun org-kill-is-subtree-p (&optional txt)
8497 "Check if the current kill is an outline subtree, or a set of trees.
8498 Returns nil if kill does not start with a headline, or if the first
8499 headline level is not the largest headline level in the tree.
8500 So this will actually accept several entries of equal levels as well,
8501 which is OK for `org-paste-subtree'.
8502 If optional TXT is given, check this string instead of the current kill."
8503 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8504 (re (org-get-limited-outline-regexp))
8505 (^re (concat "^" re))
8506 (start-level (and kill
8507 (string-match
8508 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8509 kill)
8510 (- (match-end 2) (match-beginning 2) 1)))
8511 (start (1+ (or (match-beginning 2) -1))))
8512 (if (not start-level)
8513 (progn
8514 nil) ;; does not even start with a heading
8515 (catch 'exit
8516 (while (setq start (string-match ^re kill (1+ start)))
8517 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8518 (throw 'exit nil)))
8519 t))))
8521 (defvar org-markers-to-move nil
8522 "Markers that should be moved with a cut-and-paste operation.
8523 Those markers are stored together with their positions relative to
8524 the start of the region.")
8526 (defun org-save-markers-in-region (beg end)
8527 "Check markers in region.
8528 If these markers are between BEG and END, record their position relative
8529 to BEG, so that after moving the block of text, we can put the markers back
8530 into place.
8531 This function gets called just before an entry or tree gets cut from the
8532 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8533 called immediately, to move the markers with the entries."
8534 (setq org-markers-to-move nil)
8535 (when (featurep 'org-clock)
8536 (org-clock-save-markers-for-cut-and-paste beg end))
8537 (when (featurep 'org-agenda)
8538 (org-agenda-save-markers-for-cut-and-paste beg end)))
8540 (defun org-check-and-save-marker (marker beg end)
8541 "Check if MARKER is between BEG and END.
8542 If yes, remember the marker and the distance to BEG."
8543 (when (and (marker-buffer marker)
8544 (equal (marker-buffer marker) (current-buffer)))
8545 (if (and (>= marker beg) (< marker end))
8546 (push (cons marker (- marker beg)) org-markers-to-move))))
8548 (defun org-reinstall-markers-in-region (beg)
8549 "Move all remembered markers to their position relative to BEG."
8550 (mapc (lambda (x)
8551 (move-marker (car x) (+ beg (cdr x))))
8552 org-markers-to-move)
8553 (setq org-markers-to-move nil))
8555 (defun org-narrow-to-subtree ()
8556 "Narrow buffer to the current subtree."
8557 (interactive)
8558 (save-excursion
8559 (save-match-data
8560 (org-with-limited-levels
8561 (narrow-to-region
8562 (progn (org-back-to-heading t) (point))
8563 (progn (org-end-of-subtree t t)
8564 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8565 (point)))))))
8567 (defun org-narrow-to-block ()
8568 "Narrow buffer to the current block."
8569 (interactive)
8570 (let* ((case-fold-search t)
8571 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8572 "^[ \t]*#\\+end_.*")))
8573 (if blockp
8574 (narrow-to-region (car blockp) (cdr blockp))
8575 (user-error "Not in a block"))))
8577 (eval-when-compile
8578 (defvar org-property-drawer-re))
8580 (defvar org-property-start-re) ;; defined below
8581 (defun org-clone-subtree-with-time-shift (n &optional shift)
8582 "Clone the task (subtree) at point N times.
8583 The clones will be inserted as siblings.
8585 In interactive use, the user will be prompted for the number of
8586 clones to be produced. If the entry has a timestamp, the user
8587 will also be prompted for a time shift, which may be a repeater
8588 as used in time stamps, for example `+3d'. To disable this,
8589 you can call the function with a universal prefix argument.
8591 When a valid repeater is given and the entry contains any time
8592 stamps, the clones will become a sequence in time, with time
8593 stamps in the subtree shifted for each clone produced. If SHIFT
8594 is nil or the empty string, time stamps will be left alone. The
8595 ID property of the original subtree is removed.
8597 If the original subtree did contain time stamps with a repeater,
8598 the following will happen:
8599 - the repeater will be removed in each clone
8600 - an additional clone will be produced, with the current, unshifted
8601 date(s) in the entry.
8602 - the original entry will be placed *after* all the clones, with
8603 repeater intact.
8604 - the start days in the repeater in the original entry will be shifted
8605 to past the last clone.
8606 In this way you can spell out a number of instances of a repeating task,
8607 and still retain the repeater to cover future instances of the task."
8608 (interactive "nNumber of clones to produce: ")
8609 (let ((shift
8610 (or shift
8611 (if (and (not (equal current-prefix-arg '(4)))
8612 (save-excursion
8613 (re-search-forward org-ts-regexp-both
8614 (save-excursion
8615 (org-end-of-subtree t)
8616 (point)) t)))
8617 (read-from-minibuffer
8618 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8619 ""))) ;; No time shift
8620 (n-no-remove -1)
8621 (drawer-re org-drawer-regexp)
8622 beg end template task idprop
8623 shift-n shift-what doshift nmin nmax)
8624 (if (not (and (integerp n) (> n 0)))
8625 (user-error "Invalid number of replications %s" n))
8626 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8627 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8628 shift)))
8629 (user-error "Invalid shift specification %s" shift))
8630 (when doshift
8631 (setq shift-n (string-to-number (match-string 1 shift))
8632 shift-what (cdr (assoc (match-string 2 shift)
8633 '(("d" . day) ("w" . week)
8634 ("m" . month) ("y" . year))))))
8635 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8636 (setq nmin 1 nmax n)
8637 (org-back-to-heading t)
8638 (setq beg (point))
8639 (setq idprop (org-entry-get nil "ID"))
8640 (org-end-of-subtree t t)
8641 (or (bolp) (insert "\n"))
8642 (setq end (point))
8643 (setq template (buffer-substring beg end))
8644 (when (and doshift
8645 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8646 (delete-region beg end)
8647 (setq end beg)
8648 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8649 (goto-char end)
8650 (loop for n from nmin to nmax do
8651 ;; prepare clone
8652 (with-temp-buffer
8653 (insert template)
8654 (org-mode)
8655 (goto-char (point-min))
8656 (org-show-subtree)
8657 (and idprop (if org-clone-delete-id
8658 (org-entry-delete nil "ID")
8659 (org-id-get-create t)))
8660 (unless (= n 0)
8661 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8662 (kill-whole-line))
8663 (goto-char (point-min))
8664 (while (re-search-forward drawer-re nil t)
8665 (org-remove-empty-drawer-at (point))))
8666 (goto-char (point-min))
8667 (when doshift
8668 (while (re-search-forward org-ts-regexp-both nil t)
8669 (org-timestamp-change (* n shift-n) shift-what))
8670 (unless (= n n-no-remove)
8671 (goto-char (point-min))
8672 (while (re-search-forward org-ts-regexp nil t)
8673 (save-excursion
8674 (goto-char (match-beginning 0))
8675 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8676 (delete-region (match-beginning 1) (match-end 1)))))))
8677 (setq task (buffer-string)))
8678 (insert task))
8679 (goto-char beg)))
8681 ;;; Outline Sorting
8683 (defun org-sort (with-case)
8684 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8685 Optional argument WITH-CASE means sort case-sensitively."
8686 (interactive "P")
8687 (cond
8688 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8689 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8691 (org-call-with-arg 'org-sort-entries with-case))))
8693 (defun org-sort-remove-invisible (s)
8694 "Remove invisible links from string S."
8695 (remove-text-properties 0 (length s) org-rm-props s)
8696 (while (string-match org-bracket-link-regexp s)
8697 (setq s (replace-match (if (match-end 2)
8698 (match-string 3 s)
8699 (match-string 1 s)) t t s)))
8700 (let ((st (format " %s " s)))
8701 (while (string-match org-emph-re st)
8702 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8703 (setq s (substring st 1 -1)))
8706 (defvar org-priority-regexp) ; defined later in the file
8708 (defvar org-after-sorting-entries-or-items-hook nil
8709 "Hook that is run after a bunch of entries or items have been sorted.
8710 When children are sorted, the cursor is in the parent line when this
8711 hook gets called. When a region or a plain list is sorted, the cursor
8712 will be in the first entry of the sorted region/list.")
8714 (defun org-sort-entries
8715 (&optional with-case sorting-type getkey-func compare-func property)
8716 "Sort entries on a certain level of an outline tree.
8717 If there is an active region, the entries in the region are sorted.
8718 Else, if the cursor is before the first entry, sort the top-level items.
8719 Else, the children of the entry at point are sorted.
8721 Sorting can be alphabetically, numerically, by date/time as given by
8722 a time stamp, by a property, by priority order, or by a custom function.
8724 The command prompts for the sorting type unless it has been given to the
8725 function through the SORTING-TYPE argument, which needs to be a character,
8726 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8727 the precise meaning of each character:
8729 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8730 c By creation time, which is assumed to be the first inactive time stamp
8731 at the beginning of a line.
8732 d By deadline date/time.
8733 k By clocking time.
8734 n Numerically, by converting the beginning of the entry/item to a number.
8735 o By order of TODO keywords.
8736 p By priority according to the cookie.
8737 r By the value of a property.
8738 s By scheduled date/time.
8739 t By date/time, either the first active time stamp in the entry, or, if
8740 none exist, by the first inactive one.
8742 Capital letters will reverse the sort order.
8744 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8745 called with point at the beginning of the record. It must return either
8746 a string or a number that should serve as the sorting key for that record.
8748 Comparing entries ignores case by default. However, with an optional argument
8749 WITH-CASE, the sorting considers case as well.
8751 Sorting is done against the visible part of the headlines, it ignores hidden
8752 links.
8754 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8755 (interactive "P")
8756 (let ((case-func (if with-case 'identity 'downcase))
8757 (cmstr
8758 ;; The clock marker is lost when using `sort-subr', let's
8759 ;; store the clocking string.
8760 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8761 (save-excursion
8762 (goto-char org-clock-marker)
8763 (looking-back "^.*") (match-string-no-properties 0))))
8764 start beg end stars re re2
8765 txt what tmp)
8766 ;; Find beginning and end of region to sort
8767 (cond
8768 ((org-region-active-p)
8769 ;; we will sort the region
8770 (setq end (region-end)
8771 what "region")
8772 (goto-char (region-beginning))
8773 (if (not (org-at-heading-p)) (outline-next-heading))
8774 (setq start (point)))
8775 ((or (org-at-heading-p)
8776 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8777 ;; we will sort the children of the current headline
8778 (org-back-to-heading)
8779 (setq start (point)
8780 end (progn (org-end-of-subtree t t)
8781 (or (bolp) (insert "\n"))
8782 (when (>= (org-back-over-empty-lines) 1)
8783 (forward-line 1))
8784 (point))
8785 what "children")
8786 (goto-char start)
8787 (show-subtree)
8788 (outline-next-heading))
8790 ;; we will sort the top-level entries in this file
8791 (goto-char (point-min))
8792 (or (org-at-heading-p) (outline-next-heading))
8793 (setq start (point))
8794 (goto-char (point-max))
8795 (beginning-of-line 1)
8796 (when (looking-at ".*?\\S-")
8797 ;; File ends in a non-white line
8798 (end-of-line 1)
8799 (insert "\n"))
8800 (setq end (point-max))
8801 (setq what "top-level")
8802 (goto-char start)
8803 (show-all)))
8805 (setq beg (point))
8806 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8808 (looking-at "\\(\\*+\\)")
8809 (setq stars (match-string 1)
8810 re (concat "^" (regexp-quote stars) " +")
8811 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8812 txt (buffer-substring beg end))
8813 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8814 (if (and (not (equal stars "*")) (string-match re2 txt))
8815 (user-error "Region to sort contains a level above the first entry"))
8817 (unless sorting-type
8818 (message
8819 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8820 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8821 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8822 what)
8823 (setq sorting-type (read-char-exclusive))
8825 (unless getkey-func
8826 (and (= (downcase sorting-type) ?f)
8827 (setq getkey-func
8828 (org-icompleting-read "Sort using function: "
8829 obarray 'fboundp t nil nil))
8830 (setq getkey-func (intern getkey-func))))
8832 (and (= (downcase sorting-type) ?r)
8833 (not property)
8834 (setq property
8835 (org-icompleting-read "Property: "
8836 (mapcar 'list (org-buffer-property-keys t))
8837 nil t))))
8839 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8840 (message "Sorting entries...")
8842 (save-restriction
8843 (narrow-to-region start end)
8844 (let ((dcst (downcase sorting-type))
8845 (case-fold-search nil)
8846 (now (current-time)))
8847 (sort-subr
8848 (/= dcst sorting-type)
8849 ;; This function moves to the beginning character of the "record" to
8850 ;; be sorted.
8851 (lambda nil
8852 (if (re-search-forward re nil t)
8853 (goto-char (match-beginning 0))
8854 (goto-char (point-max))))
8855 ;; This function moves to the last character of the "record" being
8856 ;; sorted.
8857 (lambda nil
8858 (save-match-data
8859 (condition-case nil
8860 (outline-forward-same-level 1)
8861 (error
8862 (goto-char (point-max))))))
8863 ;; This function returns the value that gets sorted against.
8864 (lambda nil
8865 (cond
8866 ((= dcst ?n)
8867 (if (looking-at org-complex-heading-regexp)
8868 (string-to-number (org-sort-remove-invisible (match-string 4)))
8869 nil))
8870 ((= dcst ?a)
8871 (if (looking-at org-complex-heading-regexp)
8872 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8873 nil))
8874 ((= dcst ?k)
8875 (or (get-text-property (point) :org-clock-minutes) 0))
8876 ((= dcst ?t)
8877 (let ((end (save-excursion (outline-next-heading) (point))))
8878 (if (or (re-search-forward org-ts-regexp end t)
8879 (re-search-forward org-ts-regexp-both end t))
8880 (org-time-string-to-seconds (match-string 0))
8881 (org-float-time now))))
8882 ((= dcst ?c)
8883 (let ((end (save-excursion (outline-next-heading) (point))))
8884 (if (re-search-forward
8885 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8886 end t)
8887 (org-time-string-to-seconds (match-string 0))
8888 (org-float-time now))))
8889 ((= dcst ?s)
8890 (let ((end (save-excursion (outline-next-heading) (point))))
8891 (if (re-search-forward org-scheduled-time-regexp end t)
8892 (org-time-string-to-seconds (match-string 1))
8893 (org-float-time now))))
8894 ((= dcst ?d)
8895 (let ((end (save-excursion (outline-next-heading) (point))))
8896 (if (re-search-forward org-deadline-time-regexp end t)
8897 (org-time-string-to-seconds (match-string 1))
8898 (org-float-time now))))
8899 ((= dcst ?p)
8900 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8901 (string-to-char (match-string 2))
8902 org-default-priority))
8903 ((= dcst ?r)
8904 (or (org-entry-get nil property) ""))
8905 ((= dcst ?o)
8906 (if (looking-at org-complex-heading-regexp)
8907 (let* ((m (match-string 2))
8908 (s (if (member m org-done-keywords) '- '+)))
8909 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8910 ((= dcst ?f)
8911 (if getkey-func
8912 (progn
8913 (setq tmp (funcall getkey-func))
8914 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8915 tmp)
8916 (error "Invalid key function `%s'" getkey-func)))
8917 (t (error "Invalid sorting type `%c'" sorting-type))))
8919 (cond
8920 ((= dcst ?a) 'string<)
8921 ((= dcst ?f) compare-func)
8922 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8923 (run-hooks 'org-after-sorting-entries-or-items-hook)
8924 ;; Reset the clock marker if needed
8925 (when cmstr
8926 (save-excursion
8927 (goto-char start)
8928 (search-forward cmstr nil t)
8929 (move-marker org-clock-marker (point))))
8930 (message "Sorting entries...done")))
8932 (defun org-do-sort (table what &optional with-case sorting-type)
8933 "Sort TABLE of WHAT according to SORTING-TYPE.
8934 The user will be prompted for the SORTING-TYPE if the call to this
8935 function does not specify it.
8936 WHAT is only for the prompt, to indicate what is being sorted.
8937 The sorting key will be extracted from the car of the elements of
8938 the table.
8939 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8940 (unless sorting-type
8941 (message
8942 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8943 what)
8944 (setq sorting-type (read-char-exclusive)))
8945 (let ((dcst (downcase sorting-type))
8946 extractfun comparefun)
8947 ;; Define the appropriate functions
8948 (cond
8949 ((= dcst ?n)
8950 (setq extractfun 'string-to-number
8951 comparefun (if (= dcst sorting-type) '< '>)))
8952 ((= dcst ?a)
8953 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8954 (lambda(x) (downcase (org-sort-remove-invisible x))))
8955 comparefun (if (= dcst sorting-type)
8956 'string<
8957 (lambda (a b) (and (not (string< a b))
8958 (not (string= a b)))))))
8959 ((= dcst ?t)
8960 (setq extractfun
8961 (lambda (x)
8962 (cond ((or (string-match org-ts-regexp x)
8963 (string-match org-ts-regexp-both x))
8964 (org-float-time
8965 (org-time-string-to-time (match-string 0 x))))
8966 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
8967 (org-hh:mm-string-to-minutes x))
8968 (t 0)))
8969 comparefun (if (= dcst sorting-type) '< '>)))
8970 (t (error "Invalid sorting type `%c'" sorting-type)))
8972 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8973 table)
8974 (lambda (a b) (funcall comparefun (car a) (car b))))))
8977 ;;; The orgstruct minor mode
8979 ;; Define a minor mode which can be used in other modes in order to
8980 ;; integrate the org-mode structure editing commands.
8982 ;; This is really a hack, because the org-mode structure commands use
8983 ;; keys which normally belong to the major mode. Here is how it
8984 ;; works: The minor mode defines all the keys necessary to operate the
8985 ;; structure commands, but wraps the commands into a function which
8986 ;; tests if the cursor is currently at a headline or a plain list
8987 ;; item. If that is the case, the structure command is used,
8988 ;; temporarily setting many Org-mode variables like regular
8989 ;; expressions for filling etc. However, when any of those keys is
8990 ;; used at a different location, function uses `key-binding' to look
8991 ;; up if the key has an associated command in another currently active
8992 ;; keymap (minor modes, major mode, global), and executes that
8993 ;; command. There might be problems if any of the keys is otherwise
8994 ;; used as a prefix key.
8996 (defcustom orgstruct-heading-prefix-regexp ""
8997 "Regexp that matches the custom prefix of Org headlines in
8998 orgstruct(++)-mode."
8999 :group 'org
9000 :version "24.4"
9001 :package-version '(Org . "8.3")
9002 :type 'regexp)
9003 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9005 (defcustom orgstruct-setup-hook nil
9006 "Hook run after orgstruct-mode-map is filled."
9007 :group 'org
9008 :version "24.4"
9009 :package-version '(Org . "8.0")
9010 :type 'hook)
9012 (defvar orgstruct-initialized nil)
9014 (defvar org-local-vars nil
9015 "List of local variables, for use by `orgstruct-mode'.")
9017 ;;;###autoload
9018 (define-minor-mode orgstruct-mode
9019 "Toggle the minor mode `orgstruct-mode'.
9020 This mode is for using Org-mode structure commands in other
9021 modes. The following keys behave as if Org-mode were active, if
9022 the cursor is on a headline, or on a plain list item (both as
9023 defined by Org-mode)."
9024 nil " OrgStruct" (make-sparse-keymap)
9025 (funcall (if orgstruct-mode
9026 'add-to-invisibility-spec
9027 'remove-from-invisibility-spec)
9028 '(outline . t))
9029 (when orgstruct-mode
9030 (org-load-modules-maybe)
9031 (unless orgstruct-initialized
9032 (orgstruct-setup)
9033 (setq orgstruct-initialized t))))
9035 ;;;###autoload
9036 (defun turn-on-orgstruct ()
9037 "Unconditionally turn on `orgstruct-mode'."
9038 (orgstruct-mode 1))
9040 (defvar org-fb-vars nil)
9041 (make-variable-buffer-local 'org-fb-vars)
9042 (defun orgstruct++-mode (&optional arg)
9043 "Toggle `orgstruct-mode', the enhanced version of it.
9044 In addition to setting orgstruct-mode, this also exports all
9045 indentation and autofilling variables from org-mode into the
9046 buffer. It will also recognize item context in multiline items."
9047 (interactive "P")
9048 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9049 (if (< arg 1)
9050 (progn (orgstruct-mode -1)
9051 (mapc (lambda(v)
9052 (org-set-local (car v)
9053 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9054 org-fb-vars))
9055 (orgstruct-mode 1)
9056 (setq org-fb-vars nil)
9057 (unless org-local-vars
9058 (setq org-local-vars (org-get-local-variables)))
9059 (let (var val)
9060 (mapc
9061 (lambda (x)
9062 (when (string-match
9063 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9064 (symbol-name (car x)))
9065 (setq var (car x) val (nth 1 x))
9066 (push (list var `(quote ,(eval var))) org-fb-vars)
9067 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9068 org-local-vars)
9069 (org-set-local 'orgstruct-is-++ t))))
9071 (defvar orgstruct-is-++ nil
9072 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9073 (make-variable-buffer-local 'orgstruct-is-++)
9075 ;;;###autoload
9076 (defun turn-on-orgstruct++ ()
9077 "Unconditionally turn on `orgstruct++-mode'."
9078 (orgstruct++-mode 1))
9080 (defun orgstruct-error ()
9081 "Error when there is no default binding for a structure key."
9082 (interactive)
9083 (funcall (if (fboundp 'user-error)
9084 'user-error
9085 'error)
9086 "This key has no function outside structure elements"))
9088 (defun orgstruct-setup ()
9089 "Setup orgstruct keymap."
9090 (dolist (cell '((org-demote . t)
9091 (org-metaleft . t)
9092 (org-metaright . t)
9093 (org-promote . t)
9094 (org-shiftmetaleft . t)
9095 (org-shiftmetaright . t)
9096 org-backward-element
9097 org-backward-heading-same-level
9098 org-ctrl-c-ret
9099 org-ctrl-c-minus
9100 org-ctrl-c-star
9101 org-cycle
9102 org-forward-heading-same-level
9103 org-insert-heading
9104 org-insert-heading-respect-content
9105 org-kill-note-or-show-branches
9106 org-mark-subtree
9107 org-meta-return
9108 org-metadown
9109 org-metaup
9110 org-narrow-to-subtree
9111 org-promote-subtree
9112 org-reveal
9113 org-shiftdown
9114 org-shiftleft
9115 org-shiftmetadown
9116 org-shiftmetaup
9117 org-shiftright
9118 org-shifttab
9119 org-shifttab
9120 org-shiftup
9121 org-show-subtree
9122 org-sort
9123 org-up-element
9124 outline-demote
9125 outline-next-visible-heading
9126 outline-previous-visible-heading
9127 outline-promote
9128 outline-up-heading
9129 show-children))
9130 (let ((f (or (car-safe cell) cell))
9131 (disable-when-heading-prefix (cdr-safe cell)))
9132 (when (fboundp f)
9133 (let ((new-bindings))
9134 (dolist (binding (nconc (where-is-internal f org-mode-map)
9135 (where-is-internal f outline-mode-map)))
9136 (push binding new-bindings)
9137 ;; TODO use local-function-key-map
9138 (dolist (rep '(("<tab>" . "TAB")
9139 ("<return>" . "RET")
9140 ("<escape>" . "ESC")
9141 ("<delete>" . "DEL")))
9142 (setq binding (read-kbd-macro
9143 (let ((case-fold-search))
9144 (replace-regexp-in-string
9145 (regexp-quote (cdr rep))
9146 (car rep)
9147 (key-description binding)))))
9148 (pushnew binding new-bindings :test 'equal)))
9149 (dolist (binding new-bindings)
9150 (let ((key (lookup-key orgstruct-mode-map binding)))
9151 (when (or (not key) (numberp key))
9152 (condition-case nil
9153 (org-defkey orgstruct-mode-map
9154 binding
9155 (orgstruct-make-binding f binding disable-when-heading-prefix))
9156 (error nil)))))))))
9157 (run-hooks 'orgstruct-setup-hook))
9159 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9160 "Create a function for binding in the structure minor mode.
9161 FUN is the command to call inside a table. KEY is the key that
9162 should be checked in for a command to execute outside of tables.
9163 Non-nil `disable-when-heading-prefix' means to disable the command
9164 if `orgstruct-heading-prefix-regexp' is not empty."
9165 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9166 (let ((nname name)
9167 (i 0))
9168 (while (fboundp (intern nname))
9169 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9170 (setq name (intern nname)))
9171 (eval
9172 (let ((bindings '((org-heading-regexp
9173 (concat "^"
9174 orgstruct-heading-prefix-regexp
9175 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9176 (org-outline-regexp
9177 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9178 (org-outline-regexp-bol
9179 (concat "^" org-outline-regexp))
9180 (outline-regexp org-outline-regexp)
9181 (outline-heading-end-regexp "\n")
9182 (outline-level 'org-outline-level)
9183 (outline-heading-alist))))
9184 `(defun ,name (arg)
9185 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9186 "Outside of structure, run the binding of `"
9187 (key-description key) "'."
9188 (when disable-when-heading-prefix
9189 (concat
9190 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9191 "back to the default binding due to limitations of Org's implementation of\n"
9192 "`" (symbol-name fun) "'.")))
9193 (interactive "p")
9194 (let* ((disable
9195 ,(and disable-when-heading-prefix
9196 '(not (string= orgstruct-heading-prefix-regexp ""))))
9197 (fallback
9198 (or disable
9199 (not
9200 (let* ,bindings
9201 (org-context-p 'headline 'item
9202 ,(when (memq fun
9203 '(org-insert-heading
9204 org-insert-heading-respect-content
9205 org-meta-return))
9206 '(when orgstruct-is-++
9207 'item-body))))))))
9208 (if fallback
9209 (let* ((orgstruct-mode)
9210 (binding
9211 (loop with key = ,key
9212 for rep in
9213 '(nil
9214 ("<\\([^>]*\\)tab>" . "\\1TAB")
9215 ("<\\([^>]*\\)return>" . "\\1RET")
9216 ("<\\([^>]*\\)escape>" . "\\1ESC")
9217 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9219 (when rep
9220 (setq key (read-kbd-macro
9221 (let ((case-fold-search))
9222 (replace-regexp-in-string
9223 (car rep)
9224 (cdr rep)
9225 (key-description key))))))
9226 thereis (key-binding key))))
9227 (if (keymapp binding)
9228 (org-set-transient-map binding)
9229 (let ((func (or binding
9230 (unless disable
9231 'orgstruct-error))))
9232 (when func
9233 (call-interactively func)))))
9234 (org-run-like-in-org-mode
9235 (lambda ()
9236 (interactive)
9237 (let* ,bindings
9238 (call-interactively ',fun)))))))))
9239 name))
9241 (defun org-contextualize-keys (alist contexts)
9242 "Return valid elements in ALIST depending on CONTEXTS.
9244 `org-agenda-custom-commands' or `org-capture-templates' are the
9245 values used for ALIST, and `org-agenda-custom-commands-contexts'
9246 or `org-capture-templates-contexts' are the associated contexts
9247 definitions."
9248 (let ((contexts
9249 ;; normalize contexts
9250 (mapcar
9251 (lambda(c) (cond ((listp (cadr c))
9252 (list (car c) (car c) (cadr c)))
9253 ((string= "" (cadr c))
9254 (list (car c) (car c) (caddr c)))
9255 (t c))) contexts))
9256 (a alist) c r s)
9257 ;; loop over all commands or templates
9258 (while (setq c (pop a))
9259 (let (vrules repl)
9260 (cond
9261 ((not (assoc (car c) contexts))
9262 (push c r))
9263 ((and (assoc (car c) contexts)
9264 (setq vrules (org-contextualize-validate-key
9265 (car c) contexts)))
9266 (mapc (lambda (vr)
9267 (when (not (equal (car vr) (cadr vr)))
9268 (setq repl vr))) vrules)
9269 (if (not repl) (push c r)
9270 (push (cadr repl) s)
9271 (push
9272 (cons (car c)
9273 (cdr (or (assoc (cadr repl) alist)
9274 (error "Undefined key `%s' as contextual replacement for `%s'"
9275 (cadr repl) (car c)))))
9276 r))))))
9277 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9278 (delq
9280 (delete-dups
9281 (mapcar (lambda (x)
9282 (let ((tpl (car x)))
9283 (when (not (delq
9285 (mapcar (lambda(y)
9286 (equal y tpl)) s))) x)))
9287 (reverse r))))))
9289 (defun org-contextualize-validate-key (key contexts)
9290 "Check CONTEXTS for agenda or capture KEY."
9291 (let (r rr res)
9292 (while (setq r (pop contexts))
9293 (mapc
9294 (lambda (rr)
9295 (when
9296 (and (equal key (car r))
9297 (if (functionp rr) (funcall rr)
9298 (or (and (eq (car rr) 'in-file)
9299 (buffer-file-name)
9300 (string-match (cdr rr) (buffer-file-name)))
9301 (and (eq (car rr) 'in-mode)
9302 (string-match (cdr rr) (symbol-name major-mode)))
9303 (and (eq (car rr) 'in-buffer)
9304 (string-match (cdr rr) (buffer-name)))
9305 (when (and (eq (car rr) 'not-in-file)
9306 (buffer-file-name))
9307 (not (string-match (cdr rr) (buffer-file-name))))
9308 (when (eq (car rr) 'not-in-mode)
9309 (not (string-match (cdr rr) (symbol-name major-mode))))
9310 (when (eq (car rr) 'not-in-buffer)
9311 (not (string-match (cdr rr) (buffer-name)))))))
9312 (push r res)))
9313 (car (last r))))
9314 (delete-dups (delq nil res))))
9316 (defun org-context-p (&rest contexts)
9317 "Check if local context is any of CONTEXTS.
9318 Possible values in the list of contexts are `table', `headline', and `item'."
9319 (let ((pos (point)))
9320 (goto-char (point-at-bol))
9321 (prog1 (or (and (memq 'table contexts)
9322 (looking-at "[ \t]*|"))
9323 (and (memq 'headline contexts)
9324 (looking-at org-outline-regexp))
9325 (and (memq 'item contexts)
9326 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9327 (and (memq 'item-body contexts)
9328 (org-in-item-p)))
9329 (goto-char pos))))
9331 (defun org-get-local-variables ()
9332 "Return a list of all local variables in an Org mode buffer."
9333 (let (varlist)
9334 (with-current-buffer (get-buffer-create "*Org tmp*")
9335 (erase-buffer)
9336 (org-mode)
9337 (setq varlist (buffer-local-variables)))
9338 (kill-buffer "*Org tmp*")
9339 (delq nil
9340 (mapcar
9341 (lambda (x)
9342 (setq x
9343 (if (symbolp x)
9344 (list x)
9345 (list (car x) (cdr x))))
9346 (if (and (not (get (car x) 'org-state))
9347 (string-match
9348 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9349 (symbol-name (car x))))
9350 x nil))
9351 varlist))))
9353 (defun org-clone-local-variables (from-buffer &optional regexp)
9354 "Clone local variables from FROM-BUFFER.
9355 Optional argument REGEXP selects variables to clone."
9356 (mapc
9357 (lambda (pair)
9358 (and (symbolp (car pair))
9359 (or (null regexp)
9360 (string-match regexp (symbol-name (car pair))))
9361 (set (make-local-variable (car pair))
9362 (cdr pair))))
9363 (buffer-local-variables from-buffer)))
9365 ;;;###autoload
9366 (defun org-run-like-in-org-mode (cmd)
9367 "Run a command, pretending that the current buffer is in Org-mode.
9368 This will temporarily bind local variables that are typically bound in
9369 Org-mode to the values they have in Org-mode, and then interactively
9370 call CMD."
9371 (org-load-modules-maybe)
9372 (unless org-local-vars
9373 (setq org-local-vars (org-get-local-variables)))
9374 (let (binds)
9375 (dolist (var org-local-vars)
9376 (when (or (not (boundp (car var)))
9377 (eq (symbol-value (car var))
9378 (default-value (car var))))
9379 (push (list (car var) `(quote ,(cadr var))) binds)))
9380 (eval `(let ,binds
9381 (call-interactively (quote ,cmd))))))
9383 (defun org-get-category (&optional pos force-refresh)
9384 "Get the category applying to position POS."
9385 (save-match-data
9386 (if force-refresh (org-refresh-category-properties))
9387 (let ((pos (or pos (point))))
9388 (or (get-text-property pos 'org-category)
9389 (progn (org-refresh-category-properties)
9390 (get-text-property pos 'org-category))))))
9392 ;;; Refresh properties
9394 (defun org-refresh-category-properties ()
9395 "Refresh category text properties in the buffer."
9396 (let ((case-fold-search t)
9397 (inhibit-read-only t)
9398 (def-cat (cond
9399 ((null org-category)
9400 (if buffer-file-name
9401 (file-name-sans-extension
9402 (file-name-nondirectory buffer-file-name))
9403 "???"))
9404 ((symbolp org-category) (symbol-name org-category))
9405 (t org-category)))
9406 beg end cat pos optionp)
9407 (org-with-silent-modifications
9408 (save-excursion
9409 (save-restriction
9410 (widen)
9411 (goto-char (point-min))
9412 (put-text-property (point) (point-max) 'org-category def-cat)
9413 (while (re-search-forward
9414 "^[ \t]*\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9415 (setq pos (match-end 0)
9416 optionp (equal (char-after (match-beginning 0)) ?#)
9417 cat (org-trim (match-string 2)))
9418 (if optionp
9419 (setq beg (point-at-bol) end (point-max))
9420 (org-back-to-heading t)
9421 (setq beg (point) end (org-end-of-subtree t t)))
9422 (put-text-property beg end 'org-category cat)
9423 (goto-char pos)))))))
9425 (defun org-refresh-stats-properties ()
9426 "Refresh stats text properties in the buffer."
9427 (let (stats)
9428 (org-with-silent-modifications
9429 (save-excursion
9430 (save-restriction
9431 (widen)
9432 (goto-char (point-min))
9433 (while (re-search-forward
9434 (concat org-outline-regexp-bol ".*"
9435 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9436 nil t)
9437 (setq stats (cond ((equal (match-string 3) "0") 0)
9438 ((match-string 2)
9439 (/ (* (string-to-number (match-string 2)) 100)
9440 (string-to-number (match-string 3))))
9441 (t (string-to-number (match-string 1)))))
9442 (org-back-to-heading t)
9443 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9444 'org-stats stats)))))))
9446 (defun org-refresh-properties (dprop tprop)
9447 "Refresh buffer text properties.
9448 DPROP is the drawer property and TPROP is either the
9449 corresponding text property to set, or an alist with each element
9450 being a text property (as a symbol) and a function to apply to
9451 the value of the drawer property."
9452 (let ((case-fold-search t)
9453 (inhibit-read-only t) p)
9454 (org-with-silent-modifications
9455 (save-excursion
9456 (save-restriction
9457 (widen)
9458 (goto-char (point-min))
9459 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9460 (setq p (org-match-string-no-properties 1))
9461 (save-excursion
9462 (org-back-to-heading t)
9463 ;; tprop is a text property symbol
9464 (if (symbolp tprop)
9465 (put-text-property
9466 (point-at-bol) (or (outline-next-heading) (point-max)) tprop p)
9467 ;; tprop is an alist with (properties . function) elements
9468 (mapc (lambda(al)
9469 (save-excursion
9470 (put-text-property
9471 (point-at-bol) (or (outline-next-heading) (point-max))
9472 (car al)
9473 (funcall (cdr al) p))))
9474 tprop)))))))))
9476 ;;;; Link Stuff
9478 ;;; Link abbreviations
9480 (defun org-link-expand-abbrev (link)
9481 "Apply replacements as defined in `org-link-abbrev-alist'."
9482 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9483 (let* ((key (match-string 1 link))
9484 (as (or (assoc key org-link-abbrev-alist-local)
9485 (assoc key org-link-abbrev-alist)))
9486 (tag (and (match-end 2) (match-string 3 link)))
9487 rpl)
9488 (if (not as)
9489 link
9490 (setq rpl (cdr as))
9491 (cond
9492 ((symbolp rpl) (funcall rpl tag))
9493 ((string-match "%(\\([^)]+\\))" rpl)
9494 (replace-match
9495 (save-match-data
9496 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9497 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9498 ((string-match "%h" rpl)
9499 (replace-match (url-hexify-string (or tag "")) t t rpl))
9500 (t (concat rpl tag)))))
9501 link))
9503 ;;; Storing and inserting links
9505 (defvar org-insert-link-history nil
9506 "Minibuffer history for links inserted with `org-insert-link'.")
9508 (defvar org-stored-links nil
9509 "Contains the links stored with `org-store-link'.")
9511 (defvar org-store-link-plist nil
9512 "Plist with info about the most recently link created with `org-store-link'.")
9514 (defvar org-link-protocols nil
9515 "Link protocols added to Org-mode using `org-add-link-type'.")
9517 (defvar org-store-link-functions nil
9518 "List of functions that are called to create and store a link.
9519 Each function will be called in turn until one returns a non-nil
9520 value. Each function should check if it is responsible for creating
9521 this link (for example by looking at the major mode).
9522 If not, it must exit and return nil.
9523 If yes, it should return a non-nil value after a calling
9524 `org-store-link-props' with a list of properties and values.
9525 Special properties are:
9527 :type The link prefix, like \"http\". This must be given.
9528 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9529 This is obligatory as well.
9530 :description Optional default description for the second pair
9531 of brackets in an Org-mode link. The user can still change
9532 this when inserting this link into an Org-mode buffer.
9534 In addition to these, any additional properties can be specified
9535 and then used in capture templates.")
9537 (defun org-add-link-type (type &optional follow export)
9538 "Add TYPE to the list of `org-link-types'.
9539 Re-compute all regular expressions depending on `org-link-types'
9541 FOLLOW and EXPORT are two functions.
9543 FOLLOW should take the link path as the single argument and do whatever
9544 is necessary to follow the link, for example find a file or display
9545 a mail message.
9547 EXPORT should format the link path for export to one of the export formats.
9548 It should be a function accepting three arguments:
9550 path the path of the link, the text after the prefix (like \"http:\")
9551 desc the description of the link, if any, or a description added by
9552 org-export-normalize-links if there is none
9553 format the export format, a symbol like `html' or `latex' or `ascii'..
9555 The function may use the FORMAT information to return different values
9556 depending on the format. The return value will be put literally into
9557 the exported file. If the return value is nil, this means Org should
9558 do what it normally does with links which do not have EXPORT defined.
9560 Org-mode has a built-in default for exporting links. If you are happy with
9561 this default, there is no need to define an export function for the link
9562 type. For a simple example of an export function, see `org-bbdb.el'."
9563 (add-to-list 'org-link-types type t)
9564 (org-make-link-regexps)
9565 (if (assoc type org-link-protocols)
9566 (setcdr (assoc type org-link-protocols) (list follow export))
9567 (push (list type follow export) org-link-protocols)))
9569 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9570 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9572 ;;;###autoload
9573 (defun org-store-link (arg)
9574 "\\<org-mode-map>Store an org-link to the current location.
9575 This link is added to `org-stored-links' and can later be inserted
9576 into an org-buffer with \\[org-insert-link].
9578 For some link types, a prefix arg is interpreted.
9579 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9580 For file links, arg negates `org-context-in-file-links'.
9582 A double prefix arg force skipping storing functions that are not
9583 part of Org's core.
9585 A triple prefix arg force storing a link for each line in the
9586 active region."
9587 (interactive "P")
9588 (org-load-modules-maybe)
9589 (if (and (equal arg '(64)) (org-region-active-p))
9590 (save-excursion
9591 (let ((end (region-end)))
9592 (goto-char (region-beginning))
9593 (set-mark (point))
9594 (while (< (point-at-eol) end)
9595 (move-end-of-line 1) (activate-mark)
9596 (let (current-prefix-arg)
9597 (call-interactively 'org-store-link))
9598 (move-beginning-of-line 2)
9599 (set-mark (point)))))
9600 (org-with-limited-levels
9601 (setq org-store-link-plist nil)
9602 (let (link cpltxt desc description search
9603 txt custom-id agenda-link sfuns sfunsn)
9604 (cond
9606 ;; Store a link using an external link type
9607 ((and (not (equal arg '(16)))
9608 (setq sfuns
9609 (delq
9610 nil (mapcar (lambda (f)
9611 (let (fs) (if (funcall f) (push f fs))))
9612 org-store-link-functions))
9613 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9614 (or (and (cdr sfuns)
9615 (funcall (intern
9616 (completing-read
9617 "Which function for creating the link? "
9618 sfunsn nil t (car sfunsn)))))
9619 (funcall (caar sfuns)))
9620 (setq link (plist-get org-store-link-plist :link)
9621 desc (or (plist-get org-store-link-plist
9622 :description) link))))
9624 ;; Store a link from a source code buffer
9625 ((org-src-edit-buffer-p)
9626 (let (label gc)
9627 (while (or (not label)
9628 (save-excursion
9629 (save-restriction
9630 (widen)
9631 (goto-char (point-min))
9632 (re-search-forward
9633 (regexp-quote (format org-coderef-label-format label))
9634 nil t))))
9635 (when label (message "Label exists already") (sit-for 2))
9636 (setq label (read-string "Code line label: " label)))
9637 (end-of-line 1)
9638 (setq link (format org-coderef-label-format label))
9639 (setq gc (- 79 (length link)))
9640 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9641 (insert link)
9642 (setq link (concat "(" label ")") desc nil)))
9644 ;; We are in the agenda, link to referenced location
9645 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9646 (let ((m (or (get-text-property (point) 'org-hd-marker)
9647 (get-text-property (point) 'org-marker))))
9648 (when m
9649 (org-with-point-at m
9650 (setq agenda-link
9651 (if (org-called-interactively-p 'any)
9652 (call-interactively 'org-store-link)
9653 (org-store-link nil)))))))
9655 ((eq major-mode 'calendar-mode)
9656 (let ((cd (calendar-cursor-to-date)))
9657 (setq link
9658 (format-time-string
9659 (car org-time-stamp-formats)
9660 (apply 'encode-time
9661 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9662 nil nil nil))))
9663 (org-store-link-props :type "calendar" :date cd)))
9665 ((eq major-mode 'help-mode)
9666 (setq link (concat "help:" (save-excursion
9667 (goto-char (point-min))
9668 (looking-at "^[^ ]+")
9669 (match-string 0))))
9670 (org-store-link-props :type "help"))
9672 ((eq major-mode 'w3-mode)
9673 (setq cpltxt (if (and (buffer-name)
9674 (not (string-match "Untitled" (buffer-name))))
9675 (buffer-name)
9676 (url-view-url t))
9677 link (url-view-url t))
9678 (org-store-link-props :type "w3" :url (url-view-url t)))
9680 ((eq major-mode 'image-mode)
9681 (setq cpltxt (concat "file:"
9682 (abbreviate-file-name buffer-file-name))
9683 link cpltxt)
9684 (org-store-link-props :type "image" :file buffer-file-name))
9686 ;; In dired, store a link to the file of the current line
9687 ((derived-mode-p 'dired-mode)
9688 (let ((file (dired-get-filename nil t)))
9689 (setq file (if file
9690 (abbreviate-file-name
9691 (expand-file-name (dired-get-filename nil t)))
9692 ;; otherwise, no file so use current directory.
9693 default-directory))
9694 (setq cpltxt (concat "file:" file)
9695 link cpltxt)))
9697 ((setq search (run-hook-with-args-until-success
9698 'org-create-file-search-functions))
9699 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9700 "::" search))
9701 (setq cpltxt (or description link)))
9703 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9704 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9705 (cond
9706 ;; Store a link using the target at point
9707 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9708 (setq cpltxt
9709 (concat "file:"
9710 (abbreviate-file-name
9711 (buffer-file-name (buffer-base-buffer)))
9712 "::" (match-string 1))
9713 link cpltxt))
9714 ((and (featurep 'org-id)
9715 (or (eq org-id-link-to-org-use-id t)
9716 (and (org-called-interactively-p 'any)
9717 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9718 (and (eq org-id-link-to-org-use-id
9719 'create-if-interactive-and-no-custom-id)
9720 (not custom-id))))
9721 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9722 ;; Store a link using the ID at point
9723 (setq link (condition-case nil
9724 (prog1 (org-id-store-link)
9725 (setq desc (or (plist-get org-store-link-plist
9726 :description)
9727 "")))
9728 (error
9729 ;; Probably before first headline, link only to file
9730 (concat "file:"
9731 (abbreviate-file-name
9732 (buffer-file-name (buffer-base-buffer))))))))
9734 ;; Just link to current headline
9735 (setq cpltxt (concat "file:"
9736 (abbreviate-file-name
9737 (buffer-file-name (buffer-base-buffer)))))
9738 ;; Add a context search string
9739 (when (org-xor org-context-in-file-links arg)
9740 (let* ((ee (org-element-at-point))
9741 (et (org-element-type ee))
9742 (ev (plist-get (cadr ee) :value))
9743 (ek (plist-get (cadr ee) :key))
9744 (eok (and (stringp ek) (string-match "name" ek))))
9745 (setq txt (cond
9746 ((org-at-heading-p) nil)
9747 ((and (eq et 'keyword) eok) ev)
9748 ((org-region-active-p)
9749 (buffer-substring (region-beginning) (region-end)))))
9750 (when (or (null txt) (string-match "\\S-" txt))
9751 (setq cpltxt
9752 (concat cpltxt "::"
9753 (condition-case nil
9754 (org-make-org-heading-search-string txt)
9755 (error "")))
9756 desc (or (and (eq et 'keyword) eok ev)
9757 (nth 4 (ignore-errors (org-heading-components)))
9758 "NONE")))))
9759 (if (string-match "::\\'" cpltxt)
9760 (setq cpltxt (substring cpltxt 0 -2)))
9761 (setq link cpltxt))))
9763 ((buffer-file-name (buffer-base-buffer))
9764 ;; Just link to this file here.
9765 (setq cpltxt (concat "file:"
9766 (abbreviate-file-name
9767 (buffer-file-name (buffer-base-buffer)))))
9768 ;; Add a context string.
9769 (when (org-xor org-context-in-file-links arg)
9770 (setq txt (if (org-region-active-p)
9771 (buffer-substring (region-beginning) (region-end))
9772 (buffer-substring (point-at-bol) (point-at-eol))))
9773 ;; Only use search option if there is some text.
9774 (when (string-match "\\S-" txt)
9775 (setq cpltxt
9776 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9777 desc "NONE")))
9778 (setq link cpltxt))
9780 ((org-called-interactively-p 'interactive)
9781 (user-error "No method for storing a link from this buffer"))
9783 (t (setq link nil)))
9785 ;; We're done setting link and desc, clean up
9786 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9787 (setq link (or link cpltxt)
9788 desc (or desc cpltxt))
9789 (cond ((equal desc "NONE") (setq desc nil))
9790 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9791 (let ((d0 (match-string 3 desc))
9792 (p0 (match-string 5 desc)))
9793 (setq desc
9794 (replace-regexp-in-string
9795 org-bracket-link-regexp
9796 (concat (or p0 d0)
9797 (if (equal (length (match-string 0 desc))
9798 (length desc)) "*" "")) desc)))))
9800 ;; Return the link
9801 (if (not (and (or (org-called-interactively-p 'any)
9802 executing-kbd-macro) link))
9803 (or agenda-link (and link (org-make-link-string link desc)))
9804 (push (list link desc) org-stored-links)
9805 (message "Stored: %s" (or desc link))
9806 (when custom-id
9807 (setq link (concat "file:" (abbreviate-file-name
9808 (buffer-file-name)) "::#" custom-id))
9809 (push (list link desc) org-stored-links))
9810 (car org-stored-links))))))
9812 (defun org-store-link-props (&rest plist)
9813 "Store link properties, extract names and addresses."
9814 (let (x adr)
9815 (when (setq x (plist-get plist :from))
9816 (setq adr (mail-extract-address-components x))
9817 (setq plist (plist-put plist :fromname (car adr)))
9818 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9819 (when (setq x (plist-get plist :to))
9820 (setq adr (mail-extract-address-components x))
9821 (setq plist (plist-put plist :toname (car adr)))
9822 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9823 (let ((from (plist-get plist :from))
9824 (to (plist-get plist :to)))
9825 (when (and from to org-from-is-user-regexp)
9826 (setq plist
9827 (plist-put plist :fromto
9828 (if (string-match org-from-is-user-regexp from)
9829 (concat "to %t")
9830 (concat "from %f"))))))
9831 (setq org-store-link-plist plist))
9833 (defun org-add-link-props (&rest plist)
9834 "Add these properties to the link property list."
9835 (let (key value)
9836 (while plist
9837 (setq key (pop plist) value (pop plist))
9838 (setq org-store-link-plist
9839 (plist-put org-store-link-plist key value)))))
9841 (defun org-email-link-description (&optional fmt)
9842 "Return the description part of an email link.
9843 This takes information from `org-store-link-plist' and formats it
9844 according to FMT (default from `org-email-link-description-format')."
9845 (setq fmt (or fmt org-email-link-description-format))
9846 (let* ((p org-store-link-plist)
9847 (to (plist-get p :toaddress))
9848 (from (plist-get p :fromaddress))
9849 (table
9850 (list
9851 (cons "%c" (plist-get p :fromto))
9852 (cons "%F" (plist-get p :from))
9853 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9854 (cons "%T" (plist-get p :to))
9855 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9856 (cons "%s" (plist-get p :subject))
9857 (cons "%d" (plist-get p :date))
9858 (cons "%m" (plist-get p :message-id)))))
9859 (when (string-match "%c" fmt)
9860 ;; Check if the user wrote this message
9861 (if (and org-from-is-user-regexp from to
9862 (save-match-data (string-match org-from-is-user-regexp from)))
9863 (setq fmt (replace-match "to %t" t t fmt))
9864 (setq fmt (replace-match "from %f" t t fmt))))
9865 (org-replace-escapes fmt table)))
9867 (defun org-make-org-heading-search-string (&optional string)
9868 "Make search string for the current headline or STRING."
9869 (let ((s (or string
9870 (and (derived-mode-p 'org-mode)
9871 (save-excursion
9872 (org-back-to-heading t)
9873 (org-element-property :raw-value (org-element-at-point))))))
9874 (lines org-context-in-file-links))
9875 (or string (setq s (concat "*" s))) ; Add * for headlines
9876 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9877 (when (and string (integerp lines) (> lines 0))
9878 (let ((slines (org-split-string s "\n")))
9879 (when (< lines (length slines))
9880 (setq s (mapconcat
9881 'identity
9882 (reverse (nthcdr (- (length slines) lines)
9883 (reverse slines))) "\n")))))
9884 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9886 (defun org-make-link-string (link &optional description)
9887 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9888 (unless (string-match "\\S-" link)
9889 (error "Empty link"))
9890 (when (and description
9891 (stringp description)
9892 (not (string-match "\\S-" description)))
9893 (setq description nil))
9894 (when (stringp description)
9895 ;; Remove brackets from the description, they are fatal.
9896 (while (string-match "\\[" description)
9897 (setq description (replace-match "{" t t description)))
9898 (while (string-match "\\]" description)
9899 (setq description (replace-match "}" t t description))))
9900 (when (equal link description)
9901 ;; No description needed, it is identical
9902 (setq description nil))
9903 (when (and (not description)
9904 (not (string-match (org-image-file-name-regexp) link))
9905 (not (equal link (org-link-escape link))))
9906 (setq description (org-extract-attributes link)))
9907 (setq link
9908 (cond ((string-match (org-image-file-name-regexp) link) link)
9909 ((string-match org-link-types-re link)
9910 (concat (match-string 1 link)
9911 (org-link-escape (substring link (match-end 1)))))
9912 (t (org-link-escape link))))
9913 (concat "[[" link "]"
9914 (if description (concat "[" description "]") "")
9915 "]"))
9917 (defconst org-link-escape-chars
9918 ;;%20 %5B %5D
9919 '(?\ ?\[ ?\])
9920 "List of characters that should be escaped in a link when stored to Org.
9921 This is the list that is used for internal purposes.")
9923 (defconst org-link-escape-chars-browser
9924 ;;%20 %22
9925 '(?\ ?\")
9926 "List of characters to be escaped before handing over to the browser.
9927 If you consider using this constant then you probably want to use
9928 the function `org-link-escape-browser' instead. See there why
9929 this constant is a candidate to be removed once Org drops support
9930 for Emacs 24.1 and 24.2.")
9932 (defun org-link-escape (text &optional table merge)
9933 "Return percent escaped representation of TEXT.
9934 TEXT is a string with the text to escape.
9935 Optional argument TABLE is a list with characters that should be
9936 escaped. When nil, `org-link-escape-chars' is used.
9937 If optional argument MERGE is set, merge TABLE into
9938 `org-link-escape-chars'."
9939 ;; Don't escape chars in internal links
9940 (if (string-match "^\\*[[:alnum:]]+" text)
9941 text
9942 (cond
9943 ((and table merge)
9944 (mapc (lambda (defchr)
9945 (unless (member defchr table)
9946 (setq table (cons defchr table))))
9947 org-link-escape-chars))
9948 ((null table)
9949 (setq table org-link-escape-chars)))
9950 (mapconcat
9951 (lambda (char)
9952 (if (or (member char table)
9953 (and (or (< char 32) (= char ?\%) (> char 126))
9954 org-url-hexify-p))
9955 (mapconcat (lambda (sequence-element)
9956 (format "%%%.2X" sequence-element))
9957 (or (encode-coding-char char 'utf-8)
9958 (error "Unable to percent escape character: %s"
9959 (char-to-string char))) "")
9960 (char-to-string char))) text "")))
9962 (defun org-link-escape-browser (text)
9963 "Escape some characters before handing over to the browser.
9964 This function is a candidate to be removed together with the
9965 constant `org-link-escape-chars-browser' once Org drops support
9966 for Emacs 24.1 and 24.2. All calls to this function will have to
9967 be replaced with `url-encode-url' which is available since Emacs
9968 24.3.1."
9969 ;; Example with the Org link
9970 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
9971 ;; to open the browser with +subject:"Release 8.2" filled into the
9972 ;; query field: In this case the variable TEXT contains the
9973 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
9974 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
9975 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
9976 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
9977 (if (fboundp 'url-encode-url)
9978 (url-encode-url text)
9979 (if (org-string-match-p
9980 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9981 text)
9982 (org-link-escape text org-link-escape-chars-browser)
9983 text)))
9985 (defun org-link-unescape (str)
9986 "Unhex hexified Unicode strings as returned from the JavaScript function
9987 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9988 (unless (and (null str) (string= "" str))
9989 (let ((pos 0) (case-fold-search t) unhexed)
9990 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9991 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9992 (setq str (replace-match unhexed t t str))
9993 (setq pos (+ pos (length unhexed))))))
9994 str)
9996 (defun org-link-unescape-compound (hex)
9997 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9998 Note: this function also decodes single byte encodings like
9999 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10000 (save-match-data
10001 (let* ((bytes (cdr (split-string hex "%")))
10002 (ret "")
10003 (eat 0)
10004 (sum 0))
10005 (while bytes
10006 (let* ((val (string-to-number (pop bytes) 16))
10007 (shift-xor
10008 (if (= 0 eat)
10009 (cond
10010 ((>= val 252) (cons 6 252))
10011 ((>= val 248) (cons 5 248))
10012 ((>= val 240) (cons 4 240))
10013 ((>= val 224) (cons 3 224))
10014 ((>= val 192) (cons 2 192))
10015 (t (cons 0 0)))
10016 (cons 6 128))))
10017 (if (>= val 192) (setq eat (car shift-xor)))
10018 (setq val (logxor val (cdr shift-xor)))
10019 (setq sum (+ (lsh sum (car shift-xor)) val))
10020 (if (> eat 0) (setq eat (- eat 1)))
10021 (cond
10022 ((= 0 eat) ;multi byte
10023 (setq ret (concat ret (org-char-to-string sum)))
10024 (setq sum 0))
10025 ((not bytes) ; single byte(s)
10026 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10027 ret)))
10029 (defun org-link-unescape-single-byte-sequence (hex)
10030 "Unhexify hex-encoded single byte character sequences."
10031 (mapconcat (lambda (byte)
10032 (char-to-string (string-to-number byte 16)))
10033 (cdr (split-string hex "%")) ""))
10035 (defun org-xor (a b)
10036 "Exclusive or."
10037 (if a (not b) b))
10039 (defun org-fixup-message-id-for-http (s)
10040 "Replace special characters in a message id, so it can be used in an http query."
10041 (when (string-match "%" s)
10042 (setq s (mapconcat (lambda (c)
10043 (if (eq c ?%)
10044 "%25"
10045 (char-to-string c)))
10046 s "")))
10047 (while (string-match "<" s)
10048 (setq s (replace-match "%3C" t t s)))
10049 (while (string-match ">" s)
10050 (setq s (replace-match "%3E" t t s)))
10051 (while (string-match "@" s)
10052 (setq s (replace-match "%40" t t s)))
10055 (defun org-link-prettify (link)
10056 "Return a human-readable representation of LINK.
10057 The car of LINK must be a raw link.
10058 The cdr of LINK must be either a link description or nil."
10059 (let ((desc (or (cadr link) "<no description>")))
10060 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10061 "<" (car link) ">")))
10063 ;;;###autoload
10064 (defun org-insert-link-global ()
10065 "Insert a link like Org-mode does.
10066 This command can be called in any mode to insert a link in Org-mode syntax."
10067 (interactive)
10068 (org-load-modules-maybe)
10069 (org-run-like-in-org-mode 'org-insert-link))
10071 (defun org-insert-all-links (arg &optional pre post)
10072 "Insert all links in `org-stored-links'.
10073 When a universal prefix, do not delete the links from `org-stored-links'.
10074 When `ARG' is a number, insert the last N link(s).
10075 `PRE' and `POST' are optional arguments to define a string to
10076 prepend or to append."
10077 (interactive "P")
10078 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10079 (links (copy-seq org-stored-links))
10080 (pr (or pre "- "))
10081 (po (or post "\n"))
10082 (cnt 1) l)
10083 (if (null org-stored-links)
10084 (message "No link to insert")
10085 (while (and (or (listp arg) (>= arg cnt))
10086 (setq l (if (listp arg)
10087 (pop links)
10088 (pop org-stored-links))))
10089 (setq cnt (1+ cnt))
10090 (insert pr)
10091 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10092 (insert po)))))
10094 (defun org-insert-last-stored-link (arg)
10095 "Insert the last link stored in `org-stored-links'."
10096 (interactive "p")
10097 (org-insert-all-links arg "" "\n"))
10099 (defun org-link-fontify-links-to-this-file ()
10100 "Fontify links to the current file in `org-stored-links'."
10101 (let ((f (buffer-file-name)) a b)
10102 (setq a (mapcar (lambda(l)
10103 (let ((ll (car l)))
10104 (when (and (string-match "^file:\\(.+\\)::" ll)
10105 (equal f (expand-file-name (match-string 1 ll))))
10106 ll)))
10107 org-stored-links))
10108 (when (featurep 'org-id)
10109 (setq b (mapcar (lambda(l)
10110 (let ((ll (car l)))
10111 (when (and (string-match "^id:\\(.+\\)$" ll)
10112 (equal f (expand-file-name
10113 (or (org-id-find-id-file
10114 (match-string 1 ll)) ""))))
10115 ll)))
10116 org-stored-links)))
10117 (mapcar (lambda(l)
10118 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10119 (delq nil (append a b)))))
10121 (defvar org-link-links-in-this-file nil)
10122 (defun org-insert-link (&optional complete-file link-location default-description)
10123 "Insert a link. At the prompt, enter the link.
10125 Completion can be used to insert any of the link protocol prefixes like
10126 http or ftp in use.
10128 The history can be used to select a link previously stored with
10129 `org-store-link'. When the empty string is entered (i.e. if you just
10130 press RET at the prompt), the link defaults to the most recently
10131 stored link. As SPC triggers completion in the minibuffer, you need to
10132 use M-SPC or C-q SPC to force the insertion of a space character.
10134 You will also be prompted for a description, and if one is given, it will
10135 be displayed in the buffer instead of the link.
10137 If there is already a link at point, this command will allow you to edit link
10138 and description parts.
10140 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10141 be selected using completion. The path to the file will be relative to the
10142 current directory if the file is in the current directory or a subdirectory.
10143 Otherwise, the link will be the absolute path as completed in the minibuffer
10144 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10145 option `org-link-file-path-type'.
10147 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10148 the current directory or below.
10150 With three \\[universal-argument] prefixes, negate the meaning of
10151 `org-keep-stored-link-after-insertion'.
10153 If `org-make-link-description-function' is non-nil, this function will be
10154 called with the link target, and the result will be the default
10155 link description.
10157 If the LINK-LOCATION parameter is non-nil, this value will be
10158 used as the link location instead of reading one interactively.
10160 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10161 be used as the default description."
10162 (interactive "P")
10163 (let* ((wcf (current-window-configuration))
10164 (origbuf (current-buffer))
10165 (region (if (org-region-active-p)
10166 (buffer-substring (region-beginning) (region-end))))
10167 (remove (and region (list (region-beginning) (region-end))))
10168 (desc region)
10169 tmphist ; byte-compile incorrectly complains about this
10170 (link link-location)
10171 (abbrevs org-link-abbrev-alist-local)
10172 entry file all-prefixes auto-desc)
10173 (cond
10174 (link-location) ; specified by arg, just use it.
10175 ((org-in-regexp org-bracket-link-regexp 1)
10176 ;; We do have a link at point, and we are going to edit it.
10177 (setq remove (list (match-beginning 0) (match-end 0)))
10178 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10179 (setq link (read-string "Link: "
10180 (org-link-unescape
10181 (org-match-string-no-properties 1)))))
10182 ((or (org-in-regexp org-angle-link-re)
10183 (org-in-regexp org-plain-link-re))
10184 ;; Convert to bracket link
10185 (setq remove (list (match-beginning 0) (match-end 0))
10186 link (read-string "Link: "
10187 (org-remove-angle-brackets (match-string 0)))))
10188 ((member complete-file '((4) (16)))
10189 ;; Completing read for file names.
10190 (setq link (org-file-complete-link complete-file)))
10192 ;; Read link, with completion for stored links.
10193 (org-link-fontify-links-to-this-file)
10194 (org-switch-to-buffer-other-window "*Org Links*")
10195 (with-current-buffer "*Org Links*"
10196 (erase-buffer)
10197 (insert "Insert a link.
10198 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10199 (when org-stored-links
10200 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10201 (insert (mapconcat 'org-link-prettify
10202 (reverse org-stored-links) "\n")))
10203 (goto-char (point-min)))
10204 (let ((cw (selected-window)))
10205 (select-window (get-buffer-window "*Org Links*" 'visible))
10206 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10207 (unless (pos-visible-in-window-p (point-max))
10208 (org-fit-window-to-buffer))
10209 (and (window-live-p cw) (select-window cw)))
10210 ;; Fake a link history, containing the stored links.
10211 (setq tmphist (append (mapcar 'car org-stored-links)
10212 org-insert-link-history))
10213 (setq all-prefixes (append (mapcar 'car abbrevs)
10214 (mapcar 'car org-link-abbrev-alist)
10215 org-link-types))
10216 (unwind-protect
10217 (progn
10218 (setq link
10219 (org-completing-read
10220 "Link: "
10221 (append
10222 (mapcar (lambda (x) (concat x ":"))
10223 all-prefixes)
10224 (mapcar 'car org-stored-links))
10225 nil nil nil
10226 'tmphist
10227 (caar org-stored-links)))
10228 (if (not (string-match "\\S-" link))
10229 (user-error "No link selected"))
10230 (mapc (lambda(l)
10231 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10232 org-stored-links)
10233 (if (or (member link all-prefixes)
10234 (and (equal ":" (substring link -1))
10235 (member (substring link 0 -1) all-prefixes)
10236 (setq link (substring link 0 -1))))
10237 (setq link (with-current-buffer origbuf
10238 (org-link-try-special-completion link)))))
10239 (set-window-configuration wcf)
10240 (kill-buffer "*Org Links*"))
10241 (setq entry (assoc link org-stored-links))
10242 (or entry (push link org-insert-link-history))
10243 (setq desc (or desc (nth 1 entry)))))
10245 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10246 (not org-keep-stored-link-after-insertion))
10247 (setq org-stored-links (delq (assoc link org-stored-links)
10248 org-stored-links)))
10250 (if (and (string-match org-plain-link-re link)
10251 (not (string-match org-ts-regexp link)))
10252 ;; URL-like link, normalize the use of angular brackets.
10253 (setq link (org-remove-angle-brackets link)))
10255 ;; Check if we are linking to the current file with a search
10256 ;; option If yes, simplify the link by using only the search
10257 ;; option.
10258 (when (and buffer-file-name
10259 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10260 (let* ((path (match-string 1 link))
10261 (case-fold-search nil)
10262 (search (match-string 2 link)))
10263 (save-match-data
10264 (if (equal (file-truename buffer-file-name) (file-truename path))
10265 ;; We are linking to this same file, with a search option
10266 (setq link search)))))
10268 ;; Check if we can/should use a relative path. If yes, simplify the link
10269 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10270 (let* ((type (match-string 1 link))
10271 (path (match-string 2 link))
10272 (origpath path)
10273 (case-fold-search nil))
10274 (cond
10275 ((or (eq org-link-file-path-type 'absolute)
10276 (equal complete-file '(16)))
10277 (setq path (abbreviate-file-name (expand-file-name path))))
10278 ((eq org-link-file-path-type 'noabbrev)
10279 (setq path (expand-file-name path)))
10280 ((eq org-link-file-path-type 'relative)
10281 (setq path (file-relative-name path)))
10283 (save-match-data
10284 (if (string-match (concat "^" (regexp-quote
10285 (expand-file-name
10286 (file-name-as-directory
10287 default-directory))))
10288 (expand-file-name path))
10289 ;; We are linking a file with relative path name.
10290 (setq path (substring (expand-file-name path)
10291 (match-end 0)))
10292 (setq path (abbreviate-file-name (expand-file-name path)))))))
10293 (setq link (concat type path))
10294 (if (equal desc origpath)
10295 (setq desc path))))
10297 (if org-make-link-description-function
10298 (setq desc
10299 (or (condition-case nil
10300 (funcall org-make-link-description-function link desc)
10301 (error (progn (message "Can't get link description from `%s'"
10302 (symbol-name org-make-link-description-function))
10303 (sit-for 2) nil)))
10304 (read-string "Description: " default-description)))
10305 (if default-description (setq desc default-description)
10306 (setq desc (or (and auto-desc desc)
10307 (read-string "Description: " desc)))))
10309 (unless (string-match "\\S-" desc) (setq desc nil))
10310 (if remove (apply 'delete-region remove))
10311 (insert (org-make-link-string link desc))))
10313 (defun org-link-try-special-completion (type)
10314 "If there is completion support for link type TYPE, offer it."
10315 (let ((fun (intern (concat "org-" type "-complete-link"))))
10316 (if (functionp fun)
10317 (funcall fun)
10318 (read-string "Link (no completion support): " (concat type ":")))))
10320 (defun org-file-complete-link (&optional arg)
10321 "Create a file link using completion."
10322 (let (file link)
10323 (setq file (org-iread-file-name "File: "))
10324 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10325 (pwd1 (file-name-as-directory (abbreviate-file-name
10326 (expand-file-name ".")))))
10327 (cond
10328 ((equal arg '(16))
10329 (setq link (concat
10330 "file:"
10331 (abbreviate-file-name (expand-file-name file)))))
10332 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10333 (setq link (concat "file:" (match-string 1 file))))
10334 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10335 (expand-file-name file))
10336 (setq link (concat
10337 "file:" (match-string 1 (expand-file-name file)))))
10338 (t (setq link (concat "file:" file)))))
10339 link))
10341 (defun org-iread-file-name (&rest args)
10342 "Read-file-name using `ido-mode' speedup if available.
10343 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10344 See `read-file-name' for a description of parameters."
10345 (org-without-partial-completion
10346 (if (and org-completion-use-ido
10347 (fboundp 'ido-read-file-name)
10348 (boundp 'ido-mode) ido-mode
10349 (listp (second args)))
10350 (let ((ido-enter-matching-directory nil))
10351 (apply 'ido-read-file-name args))
10352 (apply 'read-file-name args))))
10354 (defun org-completing-read (&rest args)
10355 "Completing-read with SPACE being a normal character."
10356 (let ((enable-recursive-minibuffers t)
10357 (minibuffer-local-completion-map
10358 (copy-keymap minibuffer-local-completion-map)))
10359 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10360 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10361 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10362 (apply 'org-icompleting-read args)))
10364 (defun org-completing-read-no-i (&rest args)
10365 (let (org-completion-use-ido org-completion-use-iswitchb)
10366 (apply 'org-completing-read args)))
10368 (defun org-iswitchb-completing-read (prompt choices &rest args)
10369 "Use iswitch as a completing-read replacement to choose from choices.
10370 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10371 from."
10372 (let* ((iswitchb-use-virtual-buffers nil)
10373 (iswitchb-make-buflist-hook
10374 (lambda ()
10375 (setq iswitchb-temp-buflist choices))))
10376 (iswitchb-read-buffer prompt)))
10378 (defun org-icompleting-read (&rest args)
10379 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10380 (org-without-partial-completion
10381 (if (and org-completion-use-ido
10382 (fboundp 'ido-completing-read)
10383 (boundp 'ido-mode) ido-mode
10384 (listp (second args)))
10385 (let ((ido-enter-matching-directory nil))
10386 (apply 'ido-completing-read (concat (car args))
10387 (if (consp (car (nth 1 args)))
10388 (mapcar 'car (nth 1 args))
10389 (nth 1 args))
10390 (cddr args)))
10391 (if (and org-completion-use-iswitchb
10392 (boundp 'iswitchb-mode) iswitchb-mode
10393 (listp (second args)))
10394 (apply 'org-iswitchb-completing-read (concat (car args))
10395 (if (consp (car (nth 1 args)))
10396 (mapcar 'car (nth 1 args))
10397 (nth 1 args))
10398 (cddr args))
10399 (apply 'completing-read args)))))
10401 (defun org-extract-attributes (s)
10402 "Extract the attributes cookie from a string and set as text property."
10403 (let (a attr (start 0) key value)
10404 (save-match-data
10405 (when (string-match "{{\\([^}]+\\)}}$" s)
10406 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10407 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10408 (setq key (match-string 1 a) value (match-string 2 a)
10409 start (match-end 0)
10410 attr (plist-put attr (intern key) value))))
10411 (org-add-props s nil 'org-attr attr))
10414 ;;; Opening/following a link
10416 (defvar org-link-search-failed nil)
10418 (defvar org-open-link-functions nil
10419 "Hook for functions finding a plain text link.
10420 These functions must take a single argument, the link content.
10421 They will be called for links that look like [[link text][description]]
10422 when LINK TEXT does not have a protocol like \"http:\" and does not look
10423 like a filename (e.g. \"./blue.png\").
10425 These functions will be called *before* Org attempts to resolve the
10426 link by doing text searches in the current buffer - so if you want a
10427 link \"[[target]]\" to still find \"<<target>>\", your function should
10428 handle this as a special case.
10430 When the function does handle the link, it must return a non-nil value.
10431 If it decides that it is not responsible for this link, it must return
10432 nil to indicate that that Org-mode can continue with other options
10433 like exact and fuzzy text search.")
10435 (defun org-next-link (&optional search-backward)
10436 "Move forward to the next link.
10437 If the link is in hidden text, expose it."
10438 (interactive "P")
10439 (when (and org-link-search-failed (eq this-command last-command))
10440 (goto-char (point-min))
10441 (message "Link search wrapped back to beginning of buffer"))
10442 (setq org-link-search-failed nil)
10443 (let* ((pos (point))
10444 (ct (org-context))
10445 (a (assoc :link ct))
10446 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10447 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10448 ((looking-at org-any-link-re)
10449 ;; Don't stay stuck at link without an org-link face
10450 (forward-char (if search-backward -1 1))))
10451 (if (funcall srch-fun org-any-link-re nil t)
10452 (progn
10453 (goto-char (match-beginning 0))
10454 (if (outline-invisible-p) (org-show-context)))
10455 (goto-char pos)
10456 (setq org-link-search-failed t)
10457 (message "No further link found"))))
10459 (defun org-previous-link ()
10460 "Move backward to the previous link.
10461 If the link is in hidden text, expose it."
10462 (interactive)
10463 (funcall 'org-next-link t))
10465 (defun org-translate-link (s)
10466 "Translate a link string if a translation function has been defined."
10467 (if (and org-link-translation-function
10468 (fboundp org-link-translation-function)
10469 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10470 (progn
10471 (setq s (funcall org-link-translation-function
10472 (match-string 1 s) (match-string 2 s)))
10473 (concat (car s) ":" (cdr s)))
10476 (defun org-translate-link-from-planner (type path)
10477 "Translate a link from Emacs Planner syntax so that Org can follow it.
10478 This is still an experimental function, your mileage may vary."
10479 (cond
10480 ((member type '("http" "https" "news" "ftp"))
10481 ;; standard Internet links are the same.
10482 nil)
10483 ((and (equal type "irc") (string-match "^//" path))
10484 ;; Planner has two / at the beginning of an irc link, we have 1.
10485 ;; We should have zero, actually....
10486 (setq path (substring path 1)))
10487 ((and (equal type "lisp") (string-match "^/" path))
10488 ;; Planner has a slash, we do not.
10489 (setq type "elisp" path (substring path 1)))
10490 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10491 ;; A typical message link. Planner has the id after the final slash,
10492 ;; we separate it with a hash mark
10493 (setq path (concat (match-string 1 path) "#"
10494 (org-remove-angle-brackets (match-string 2 path))))))
10495 (cons type path))
10497 (defun org-find-file-at-mouse (ev)
10498 "Open file link or URL at mouse."
10499 (interactive "e")
10500 (mouse-set-point ev)
10501 (org-open-at-point 'in-emacs))
10503 (defun org-open-at-mouse (ev)
10504 "Open file link or URL at mouse.
10505 See the docstring of `org-open-file' for details."
10506 (interactive "e")
10507 (mouse-set-point ev)
10508 (if (eq major-mode 'org-agenda-mode)
10509 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10510 (org-open-at-point))
10512 (defvar org-window-config-before-follow-link nil
10513 "The window configuration before following a link.
10514 This is saved in case the need arises to restore it.")
10516 (defvar org-open-link-marker (make-marker)
10517 "Marker pointing to the location where `org-open-at-point' was called.")
10519 ;;;###autoload
10520 (defun org-open-at-point-global ()
10521 "Follow a link like Org-mode does.
10522 This command can be called in any mode to follow a link that has
10523 Org-mode syntax."
10524 (interactive)
10525 (org-run-like-in-org-mode 'org-open-at-point))
10527 ;;;###autoload
10528 (defun org-open-link-from-string (s &optional arg reference-buffer)
10529 "Open a link in the string S, as if it was in Org-mode."
10530 (interactive "sLink: \nP")
10531 (let ((reference-buffer (or reference-buffer (current-buffer))))
10532 (with-temp-buffer
10533 (let ((org-inhibit-startup (not reference-buffer)))
10534 (org-mode)
10535 (insert s)
10536 (goto-char (point-min))
10537 (when reference-buffer
10538 (setq org-link-abbrev-alist-local
10539 (with-current-buffer reference-buffer
10540 org-link-abbrev-alist-local)))
10541 (org-open-at-point arg reference-buffer)))))
10543 (defvar org-open-at-point-functions nil
10544 "Hook that is run when following a link at point.
10546 Functions in this hook must return t if they identify and follow
10547 a link at point. If they don't find anything interesting at point,
10548 they must return nil.")
10550 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10551 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10552 (defun org-open-at-point (&optional arg reference-buffer)
10553 "Open link, timestamp, footnote or tags at point.
10555 When point is on a link, follow it. Normally, files will be
10556 opened by an appropriate application. If the optional prefix
10557 argument ARG is non-nil, Emacs will visit the file. With
10558 a double prefix argument, try to open outside of Emacs, in the
10559 application the system uses for this file type.
10561 When point is on a timestamp, open the agenda at the day
10562 specified.
10564 When point is a footnote definition, move to the first reference
10565 found. If it is on a reference, move to the associated
10566 definition.
10568 When point is on a headline, display a list of every link in the
10569 entry, so it is possible to pick one, or all, of them. If point
10570 is on a tag, call `org-tags-view' instead.
10572 When optional argument REFERENCE-BUFFER is non-nil, it should
10573 specify a buffer from where the link search should happen. This
10574 is used internally by `org-open-link-from-string'.
10576 On top of syntactically correct links, this function will open
10577 the link at point in comments and the first link in a property
10578 drawer line."
10579 (interactive "P")
10580 ;; On a code block, open block's results.
10581 (unless (call-interactively #'org-babel-open-src-block-result)
10582 (org-load-modules-maybe)
10583 (move-marker org-open-link-marker (point))
10584 (setq org-window-config-before-follow-link (current-window-configuration))
10585 (org-remove-occur-highlights nil nil t)
10586 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10587 (let* ((context (org-element-context)) type value)
10588 ;; On an unsupported type, check if point is contained within
10589 ;; a support one.
10590 (while (and (not (memq (setq type (org-element-type context))
10591 '(comment headline inlinetask link
10592 footnote-definition footnote-reference
10593 node-property timestamp)))
10594 (setq context (org-element-property :parent context))))
10595 (setq value (org-element-property :value context))
10596 (cond
10597 ;; Blank lines at the beginning of buffer: bail out.
10598 ((not context) (user-error "No link found"))
10599 ;; Exception n°1: links in property drawers
10600 ((eq type 'node-property)
10601 (org-open-link-from-string
10602 (and (string-match org-any-link-re value)
10603 (match-string-no-properties 0 value))))
10604 ;; Exception n°2: links in comments.
10605 ((eq type 'comment)
10606 (let ((string-rear (replace-regexp-in-string
10607 "^[ \t]*# [ \t]*" ""
10608 (buffer-substring (point) (line-beginning-position))))
10609 (string-front (buffer-substring (point) (line-end-position))))
10610 (with-temp-buffer
10611 (let ((org-inhibit-startup t)) (org-mode))
10612 (insert value)
10613 (goto-char (point-min))
10614 (when (and (search-forward string-rear nil t)
10615 (search-forward string-front (line-end-position) t))
10616 (goto-char (match-beginning 0))
10617 (org-open-at-point)
10618 (when (string= string-rear "") (forward-char))))))
10619 ;; On a headline or an inlinetask, but not on a timestamp,
10620 ;; a link, a footnote reference or on tags.
10621 ((and (memq type '(headline inlinetask))
10622 ;; Not on tags.
10623 (progn (save-excursion (beginning-of-line)
10624 (looking-at org-complex-heading-regexp))
10625 (or (not (match-beginning 5))
10626 (< (point) (match-beginning 5)))))
10627 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10628 (links (car data))
10629 (links-end (cdr data)))
10630 (if links
10631 (dolist (link (if (stringp links) (list links) links))
10632 (search-forward link nil links-end)
10633 (goto-char (match-beginning 0))
10634 (org-open-at-point))
10635 (require 'org-attach)
10636 (org-attach-reveal 'if-exists))))
10637 ;; Do nothing on white spaces after an object, unless point
10638 ;; is right after it.
10639 ((> (point)
10640 (save-excursion
10641 (goto-char (org-element-property :end context))
10642 (skip-chars-backward " \t")
10643 (point)))
10644 (user-error "No link found"))
10645 ((eq type 'timestamp) (org-follow-timestamp-link))
10646 ;; On tags within a headline or an inlinetask.
10647 ((and (memq type '(headline inlinetask))
10648 (progn (save-excursion (beginning-of-line)
10649 (looking-at org-complex-heading-regexp))
10650 (and (match-beginning 5)
10651 (>= (point) (match-beginning 5)))))
10652 (org-tags-view arg (substring (match-string 5) 0 -1)))
10653 ((eq type 'link)
10654 (let ((type (org-element-property :type context))
10655 (path (org-link-unescape (org-element-property :path context))))
10656 ;; Switch back to REFERENCE-BUFFER needed when called in
10657 ;; a temporary buffer through `org-open-link-from-string'.
10658 (with-current-buffer (or reference-buffer (current-buffer))
10659 (cond
10660 ((equal type "file")
10661 (if (string-match "[*?{]" (file-name-nondirectory path))
10662 (dired path)
10663 ;; Look into `org-link-protocols' in order to find
10664 ;; a DEDICATED-FUNCTION to open file. The function
10665 ;; will be applied on raw link instead of parsed
10666 ;; link due to the limitation in `org-add-link-type'
10667 ;; ("open" function called with a single argument).
10668 ;; If no such function is found, fallback to
10669 ;; `org-open-file'.
10671 ;; Note : "file+emacs" and "file+sys" types are
10672 ;; hard-coded in order to escape the previous
10673 ;; limitation.
10674 (let* ((option (org-element-property :search-option context))
10675 (app (org-element-property :application context))
10676 (dedicated-function
10677 (nth 1 (assoc app org-link-protocols))))
10678 (if dedicated-function
10679 (funcall dedicated-function
10680 (concat path
10681 (and option (concat "::" option))))
10682 (apply #'org-open-file
10683 path
10684 (cond (arg)
10685 ((equal app "emacs") 'emacs)
10686 ((equal app "sys") 'system))
10687 (cond ((not option) nil)
10688 ((org-string-match-p "\\`[0-9]+\\'" option)
10689 (list (string-to-number option)))
10690 (t (list nil
10691 (org-link-unescape option)))))))))
10692 ((assoc type org-link-protocols)
10693 (funcall (nth 1 (assoc type org-link-protocols)) path))
10694 ((equal type "help")
10695 (let ((f-or-v (intern path)))
10696 (cond ((fboundp f-or-v) (describe-function f-or-v))
10697 ((boundp f-or-v) (describe-variable f-or-v))
10698 (t (error "Not a known function or variable")))))
10699 ((member type '("http" "https" "ftp" "mailto" "news"))
10700 (browse-url (org-link-escape-browser (concat type ":" path))))
10701 ((equal type "doi")
10702 (browse-url
10703 (org-link-escape-browser (concat org-doi-server-url path))))
10704 ((equal type "message") (browse-url (concat type ":" path)))
10705 ((equal type "shell")
10706 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10707 (cmd path))
10708 (if (or (and (org-string-nw-p
10709 org-confirm-shell-link-not-regexp)
10710 (string-match
10711 org-confirm-shell-link-not-regexp cmd))
10712 (not org-confirm-shell-link-function)
10713 (funcall org-confirm-shell-link-function
10714 (format "Execute \"%s\" in shell? "
10715 (org-add-props cmd nil
10716 'face 'org-warning))))
10717 (progn
10718 (message "Executing %s" cmd)
10719 (shell-command cmd buf)
10720 (when (featurep 'midnight)
10721 (setq clean-buffer-list-kill-buffer-names
10722 (cons buf
10723 clean-buffer-list-kill-buffer-names))))
10724 (user-error "Abort"))))
10725 ((equal type "elisp")
10726 (let ((cmd path))
10727 (if (or (and (org-string-nw-p
10728 org-confirm-elisp-link-not-regexp)
10729 (org-string-match-p
10730 org-confirm-elisp-link-not-regexp cmd))
10731 (not org-confirm-elisp-link-function)
10732 (funcall org-confirm-elisp-link-function
10733 (format "Execute \"%s\" as elisp? "
10734 (org-add-props cmd nil
10735 'face 'org-warning))))
10736 (message "%s => %s" cmd
10737 (if (eq (string-to-char cmd) ?\()
10738 (eval (read cmd))
10739 (call-interactively (read cmd))))
10740 (user-error "Abort"))))
10741 ((equal type "id")
10742 (require 'ord-id)
10743 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10744 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10745 (unless (run-hook-with-args-until-success
10746 'org-open-link-functions path)
10747 (if (not arg) (org-mark-ring-push)
10748 (switch-to-buffer-other-window
10749 (org-get-buffer-for-internal-link (current-buffer))))
10750 (let ((cmd `(org-link-search
10751 ,(if (member type '("custom-id" "coderef"))
10752 (org-element-property :raw-link context)
10753 path)
10754 ,(cond ((equal arg '(4)) 'occur)
10755 ((equal arg '(16)) 'org-occur))
10756 ,(org-element-property :begin context))))
10757 (condition-case nil
10758 (let ((org-link-search-inhibit-query t))
10759 (eval cmd))
10760 (error (progn (widen) (eval cmd)))))))
10761 (t (browse-url-at-point))))))
10762 ;; On a footnote reference or at a footnote definition's label.
10763 ((or (eq type 'footnote-reference)
10764 (and (eq type 'footnote-definition)
10765 (save-excursion
10766 ;; Do not validate action when point is on the
10767 ;; spaces right after the footnote label, in
10768 ;; order to be on par with behaviour on links.
10769 (skip-chars-forward " \t")
10770 (let ((begin
10771 (org-element-property :contents-begin context)))
10772 (if begin (< (point) begin)
10773 (= (org-element-property :post-affiliated context)
10774 (line-beginning-position)))))))
10775 (org-footnote-action))
10776 (t (user-error "No link found")))))
10777 (move-marker org-open-link-marker nil)
10778 (run-hook-with-args 'org-follow-link-hook)))
10780 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10781 "Offer links in the current entry and return the selected link.
10782 If there is only one link, return it.
10783 If NTH is an integer, return the NTH link found.
10784 If ZERO is a string, check also this string for a link, and if
10785 there is one, return it."
10786 (with-current-buffer buffer
10787 (save-excursion
10788 (save-restriction
10789 (widen)
10790 (goto-char marker)
10791 (let ((cnt ?0)
10792 (in-emacs (if (integerp nth) nil nth))
10793 have-zero end links link c)
10794 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10795 (push (match-string 0 zero) links)
10796 (setq cnt (1- cnt) have-zero t))
10797 (save-excursion
10798 (org-back-to-heading t)
10799 (setq end (save-excursion (outline-next-heading) (point)))
10800 (while (re-search-forward org-any-link-re end t)
10801 (push (match-string 0) links))
10802 (setq links (org-uniquify (reverse links))))
10803 (cond
10804 ((null links)
10805 (message "No links"))
10806 ((equal (length links) 1)
10807 (setq link (car links)))
10808 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10809 (setq link (nth (if have-zero nth (1- nth)) links)))
10810 (t ; we have to select a link
10811 (save-excursion
10812 (save-window-excursion
10813 (delete-other-windows)
10814 (with-output-to-temp-buffer "*Select Link*"
10815 (mapc (lambda (l)
10816 (if (not (string-match org-bracket-link-regexp l))
10817 (princ (format "[%c] %s\n" (incf cnt)
10818 (org-remove-angle-brackets l)))
10819 (if (match-end 3)
10820 (princ (format "[%c] %s (%s)\n" (incf cnt)
10821 (match-string 3 l) (match-string 1 l)))
10822 (princ (format "[%c] %s\n" (incf cnt)
10823 (match-string 1 l))))))
10824 links))
10825 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10826 (message "Select link to open, RET to open all:")
10827 (setq c (read-char-exclusive))
10828 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10829 (when (equal c ?q) (user-error "Abort"))
10830 (if (equal c ?\C-m)
10831 (setq link links)
10832 (setq nth (- c ?0))
10833 (if have-zero (setq nth (1+ nth)))
10834 (unless (and (integerp nth) (>= (length links) nth))
10835 (user-error "Invalid link selection"))
10836 (setq link (nth (1- nth) links)))))
10837 (cons link end))))))
10839 ;; TODO: These functions are deprecated since `org-open-at-point'
10840 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10841 (defun org-open-file-with-system (path)
10842 "Open file at PATH using the system way of opening it."
10843 (org-open-file path 'system))
10844 (defun org-open-file-with-emacs (path)
10845 "Open file at PATH in Emacs."
10846 (org-open-file path 'emacs))
10849 ;;; File search
10851 (defvar org-create-file-search-functions nil
10852 "List of functions to construct the right search string for a file link.
10853 These functions are called in turn with point at the location to
10854 which the link should point.
10856 A function in the hook should first test if it would like to
10857 handle this file type, for example by checking the `major-mode'
10858 or the file extension. If it decides not to handle this file, it
10859 should just return nil to give other functions a chance. If it
10860 does handle the file, it must return the search string to be used
10861 when following the link. The search string will be part of the
10862 file link, given after a double colon, and `org-open-at-point'
10863 will automatically search for it. If special measures must be
10864 taken to make the search successful, another function should be
10865 added to the companion hook `org-execute-file-search-functions',
10866 which see.
10868 A function in this hook may also use `setq' to set the variable
10869 `description' to provide a suggestion for the descriptive text to
10870 be used for this link when it gets inserted into an Org-mode
10871 buffer with \\[org-insert-link].")
10873 (defvar org-execute-file-search-functions nil
10874 "List of functions to execute a file search triggered by a link.
10876 Functions added to this hook must accept a single argument, the
10877 search string that was part of the file link, the part after the
10878 double colon. The function must first check if it would like to
10879 handle this search, for example by checking the `major-mode' or
10880 the file extension. If it decides not to handle this search, it
10881 should just return nil to give other functions a chance. If it
10882 does handle the search, it must return a non-nil value to keep
10883 other functions from trying.
10885 Each function can access the current prefix argument through the
10886 variable `current-prefix-arg'. Note that a single prefix is used
10887 to force opening a link in Emacs, so it may be good to only use a
10888 numeric or double prefix to guide the search function.
10890 In case this is needed, a function in this hook can also restore
10891 the window configuration before `org-open-at-point' was called using:
10893 (set-window-configuration org-window-config-before-follow-link)")
10895 (defun org-link-search (s &optional type avoid-pos stealth)
10896 "Search for a link search option.
10897 If S is surrounded by forward slashes, it is interpreted as a
10898 regular expression. In org-mode files, this will create an `org-occur'
10899 sparse tree. In ordinary files, `occur' will be used to list matches.
10900 If the current buffer is in `dired-mode', grep will be used to search
10901 in all files. If AVOID-POS is given, ignore matches near that position.
10903 When optional argument STEALTH is non-nil, do not modify
10904 visibility around point, thus ignoring
10905 `org-show-hierarchy-above', `org-show-following-heading' and
10906 `org-show-siblings' variables."
10907 (let ((case-fold-search t)
10908 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10909 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10910 (append '(("") (" ") ("\t") ("\n"))
10911 org-emphasis-alist)
10912 "\\|") "\\)"))
10913 (pos (point))
10914 (pre nil) (post nil)
10915 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10916 (cond
10917 ;; First check if there are any special search functions
10918 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10919 ;; Now try the builtin stuff
10920 ((and (equal (string-to-char s0) ?#)
10921 (> (length s0) 1)
10922 (save-excursion
10923 (goto-char (point-min))
10924 (and
10925 (re-search-forward
10926 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10927 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10928 (setq type 'dedicated
10929 pos (match-beginning 0))))
10930 ;; There is an exact target for this
10931 (goto-char pos)
10932 (org-back-to-heading t)))
10933 ((save-excursion
10934 (goto-char (point-min))
10935 (and
10936 (re-search-forward
10937 (concat "<<" (regexp-quote s0) ">>") nil t)
10938 (setq type 'dedicated
10939 pos (match-beginning 0))))
10940 ;; There is an exact target for this
10941 (goto-char pos))
10942 ((save-excursion
10943 (goto-char (point-min))
10944 (and
10945 (re-search-forward
10946 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10947 (setq type 'dedicated pos (match-beginning 0))))
10948 ;; Found an element with a matching #+name affiliated keyword.
10949 (goto-char pos))
10950 ((and (string-match "^(\\(.*\\))$" s0)
10951 (save-excursion
10952 (goto-char (point-min))
10953 (and
10954 (re-search-forward
10955 (concat "[^[]" (regexp-quote
10956 (format org-coderef-label-format
10957 (match-string 1 s0))))
10958 nil t)
10959 (setq type 'dedicated
10960 pos (1+ (match-beginning 0))))))
10961 ;; There is a coderef target for this
10962 (goto-char pos))
10963 ((string-match "^/\\(.*\\)/$" s)
10964 ;; A regular expression
10965 (cond
10966 ((derived-mode-p 'org-mode)
10967 (org-occur (match-string 1 s)))
10968 (t (org-do-occur (match-string 1 s)))))
10969 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10970 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10971 (goto-char (point-min))
10972 (cond
10973 ((let (case-fold-search)
10974 (re-search-forward (format org-complex-heading-regexp-format
10975 (regexp-quote s))
10976 nil t))
10977 ;; OK, found a match
10978 (setq type 'dedicated)
10979 (goto-char (match-beginning 0)))
10980 ((and (not org-link-search-inhibit-query)
10981 (eq org-link-search-must-match-exact-headline 'query-to-create)
10982 (y-or-n-p "No match - create this as a new heading? "))
10983 (goto-char (point-max))
10984 (or (bolp) (newline))
10985 (insert "* " s "\n")
10986 (beginning-of-line 0))
10988 (goto-char pos)
10989 (error "No match"))))
10991 ;; A normal search string
10992 (when (equal (string-to-char s) ?*)
10993 ;; Anchor on headlines, post may include tags.
10994 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10995 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10996 s (substring s 1)))
10997 (remove-text-properties
10998 0 (length s)
10999 '(face nil mouse-face nil keymap nil fontified nil) s)
11000 ;; Make a series of regular expressions to find a match
11001 (setq words (org-split-string s "[ \n\r\t]+")
11003 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11004 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11005 "\\)" markers)
11006 re2a_ (concat "\\(" (mapconcat 'downcase words
11007 "[ \t\r\n]+") "\\)[ \t\r\n]")
11008 re2a (concat "[ \t\r\n]" re2a_)
11009 re4_ (concat "\\(" (mapconcat 'downcase words
11010 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11011 re4 (concat "[^a-zA-Z_]" re4_)
11013 re1 (concat pre re2 post)
11014 re3 (concat pre (if pre re4_ re4) post)
11015 re5 (concat pre ".*" re4)
11016 re2 (concat pre re2)
11017 re2a (concat pre (if pre re2a_ re2a))
11018 re4 (concat pre (if pre re4_ re4))
11019 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11020 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11021 re5 "\\)"))
11022 (cond
11023 ((eq type 'org-occur) (org-occur reall))
11024 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11025 (t (goto-char (point-min))
11026 (setq type 'fuzzy)
11027 (if (or (and (org-search-not-self 1 re0 nil t)
11028 (setq type 'dedicated))
11029 (org-search-not-self 1 re1 nil t)
11030 (org-search-not-self 1 re2 nil t)
11031 (org-search-not-self 1 re2a nil t)
11032 (org-search-not-self 1 re3 nil t)
11033 (org-search-not-self 1 re4 nil t)
11034 (org-search-not-self 1 re5 nil t))
11035 (goto-char (match-beginning 1))
11036 (goto-char pos)
11037 (error "No match"))))))
11038 (and (derived-mode-p 'org-mode)
11039 (not stealth)
11040 (org-show-context 'link-search))
11041 type))
11043 (defun org-search-not-self (group &rest args)
11044 "Execute `re-search-forward', but only accept matches that do not
11045 enclose the position of `org-open-link-marker'."
11046 (let ((m org-open-link-marker))
11047 (catch 'exit
11048 (while (apply 're-search-forward args)
11049 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11050 (goto-char (match-end group))
11051 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11052 (> (match-beginning 0) (marker-position m))
11053 (< (match-end 0) (marker-position m)))
11054 (save-match-data
11055 (or (not (org-in-regexp
11056 org-bracket-link-analytic-regexp 1))
11057 (not (match-end 4)) ; no description
11058 (and (<= (match-beginning 4) (point))
11059 (>= (match-end 4) (point))))))
11060 (throw 'exit (point))))))))
11062 (defun org-get-buffer-for-internal-link (buffer)
11063 "Return a buffer to be used for displaying the link target of internal links."
11064 (cond
11065 ((not org-display-internal-link-with-indirect-buffer)
11066 buffer)
11067 ((string-match "(Clone)$" (buffer-name buffer))
11068 (message "Buffer is already a clone, not making another one")
11069 ;; we also do not modify visibility in this case
11070 buffer)
11071 (t ; make a new indirect buffer for displaying the link
11072 (let* ((bn (buffer-name buffer))
11073 (ibn (concat bn "(Clone)"))
11074 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11075 (with-current-buffer ib (org-overview))
11076 ib))))
11078 (defun org-do-occur (regexp &optional cleanup)
11079 "Call the Emacs command `occur'.
11080 If CLEANUP is non-nil, remove the printout of the regular expression
11081 in the *Occur* buffer. This is useful if the regex is long and not useful
11082 to read."
11083 (occur regexp)
11084 (when cleanup
11085 (let ((cwin (selected-window)) win beg end)
11086 (when (setq win (get-buffer-window "*Occur*"))
11087 (select-window win))
11088 (goto-char (point-min))
11089 (when (re-search-forward "match[a-z]+" nil t)
11090 (setq beg (match-end 0))
11091 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11092 (setq end (1- (match-beginning 0)))))
11093 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11094 (goto-char (point-min))
11095 (select-window cwin))))
11097 ;;; The mark ring for links jumps
11099 (defvar org-mark-ring nil
11100 "Mark ring for positions before jumps in Org-mode.")
11101 (defvar org-mark-ring-last-goto nil
11102 "Last position in the mark ring used to go back.")
11103 ;; Fill and close the ring
11104 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11105 (loop for i from 1 to org-mark-ring-length do
11106 (push (make-marker) org-mark-ring))
11107 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11108 org-mark-ring)
11110 (defun org-mark-ring-push (&optional pos buffer)
11111 "Put the current position or POS into the mark ring and rotate it."
11112 (interactive)
11113 (setq pos (or pos (point)))
11114 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11115 (move-marker (car org-mark-ring)
11116 (or pos (point))
11117 (or buffer (current-buffer)))
11118 (message "%s"
11119 (substitute-command-keys
11120 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11122 (defun org-mark-ring-goto (&optional n)
11123 "Jump to the previous position in the mark ring.
11124 With prefix arg N, jump back that many stored positions. When
11125 called several times in succession, walk through the entire ring.
11126 Org-mode commands jumping to a different position in the current file,
11127 or to another Org-mode file, automatically push the old position
11128 onto the ring."
11129 (interactive "p")
11130 (let (p m)
11131 (if (eq last-command this-command)
11132 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11133 (setq p org-mark-ring))
11134 (setq org-mark-ring-last-goto p)
11135 (setq m (car p))
11136 (org-pop-to-buffer-same-window (marker-buffer m))
11137 (goto-char m)
11138 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11140 (defun org-remove-angle-brackets (s)
11141 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11142 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11144 (defun org-add-angle-brackets (s)
11145 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11146 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11148 (defun org-remove-double-quotes (s)
11149 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11150 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11153 ;;; Following specific links
11155 (defun org-follow-timestamp-link ()
11156 "Open an agenda view for the time-stamp date/range at point."
11157 (cond
11158 ((org-at-date-range-p t)
11159 (let ((org-agenda-start-on-weekday)
11160 (t1 (match-string 1))
11161 (t2 (match-string 2)) tt1 tt2)
11162 (setq tt1 (time-to-days (org-time-string-to-time t1))
11163 tt2 (time-to-days (org-time-string-to-time t2)))
11164 (let ((org-agenda-buffer-tmp-name
11165 (format "*Org Agenda(a:%s)"
11166 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11167 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11168 ((org-at-timestamp-p t)
11169 (let ((org-agenda-buffer-tmp-name
11170 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11171 (org-agenda-list nil (time-to-days (org-time-string-to-time
11172 (substring (match-string 1) 0 10)))
11173 1)))
11174 (t (error "This should not happen"))))
11177 ;;; Following file links
11178 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11179 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11180 (declare-function mailcap-mime-info
11181 "mailcap" (string &optional request no-decode))
11182 (defvar org-wait nil)
11183 (defun org-open-file (path &optional in-emacs line search)
11184 "Open the file at PATH.
11185 First, this expands any special file name abbreviations. Then the
11186 configuration variable `org-file-apps' is checked if it contains an
11187 entry for this file type, and if yes, the corresponding command is launched.
11189 If no application is found, Emacs simply visits the file.
11191 With optional prefix argument IN-EMACS, Emacs will visit the file.
11192 With a double \\[universal-argument] \\[universal-argument] \
11193 prefix arg, Org tries to avoid opening in Emacs
11194 and to use an external application to visit the file.
11196 Optional LINE specifies a line to go to, optional SEARCH a string
11197 to search for. If LINE or SEARCH is given, the file will be
11198 opened in Emacs, unless an entry from org-file-apps that makes
11199 use of groups in a regexp matches.
11201 If you want to change the way frames are used when following a
11202 link, please customize `org-link-frame-setup'.
11204 If the file does not exist, an error is thrown."
11205 (let* ((file (if (equal path "")
11206 buffer-file-name
11207 (substitute-in-file-name (expand-file-name path))))
11208 (file-apps (append org-file-apps (org-default-apps)))
11209 (apps (org-remove-if
11210 'org-file-apps-entry-match-against-dlink-p file-apps))
11211 (apps-dlink (org-remove-if-not
11212 'org-file-apps-entry-match-against-dlink-p file-apps))
11213 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11214 (dirp (if remp nil (file-directory-p file)))
11215 (file (if (and dirp org-open-directory-means-index-dot-org)
11216 (concat (file-name-as-directory file) "index.org")
11217 file))
11218 (a-m-a-p (assq 'auto-mode apps))
11219 (dfile (downcase file))
11220 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11221 (link (cond ((and (eq line nil)
11222 (eq search nil))
11223 file)
11224 (line
11225 (concat file "::" (number-to-string line)))
11226 (search
11227 (concat file "::" search))))
11228 (dlink (downcase link))
11229 (old-buffer (current-buffer))
11230 (old-pos (point))
11231 (old-mode major-mode)
11232 ext cmd link-match-data)
11233 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11234 (setq ext (match-string 1 dfile))
11235 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11236 (setq ext (match-string 1 dfile))))
11237 (cond
11238 ((member in-emacs '((16) system))
11239 (setq cmd (cdr (assoc 'system apps))))
11240 (in-emacs (setq cmd 'emacs))
11242 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11243 (and dirp (cdr (assoc 'directory apps)))
11244 ; first, try matching against apps-dlink
11245 ; if we get a match here, store the match data for later
11246 (let ((match (assoc-default dlink apps-dlink
11247 'string-match)))
11248 (if match
11249 (progn (setq link-match-data (match-data))
11250 match)
11251 (progn (setq in-emacs (or in-emacs line search))
11252 nil))) ; if we have no match in apps-dlink,
11253 ; always open the file in emacs if line or search
11254 ; is given (for backwards compatibility)
11255 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11256 'string-match)
11257 (cdr (assoc ext apps))
11258 (cdr (assoc t apps))))))
11259 (when (eq cmd 'system)
11260 (setq cmd (cdr (assoc 'system apps))))
11261 (when (eq cmd 'default)
11262 (setq cmd (cdr (assoc t apps))))
11263 (when (eq cmd 'mailcap)
11264 (require 'mailcap)
11265 (mailcap-parse-mailcaps)
11266 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11267 (command (mailcap-mime-info mime-type)))
11268 (if (stringp command)
11269 (setq cmd command)
11270 (setq cmd 'emacs))))
11271 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11272 (not (file-exists-p file))
11273 (not org-open-non-existing-files))
11274 (user-error "No such file: %s" file))
11275 (cond
11276 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11277 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11278 (while (string-match "['\"]%s['\"]" cmd)
11279 (setq cmd (replace-match "%s" t t cmd)))
11280 (while (string-match "%s" cmd)
11281 (setq cmd (replace-match
11282 (save-match-data
11283 (shell-quote-argument
11284 (convert-standard-filename file)))
11285 t t cmd)))
11287 ;; Replace "%1", "%2" etc. in command with group matches from regex
11288 (save-match-data
11289 (let ((match-index 1)
11290 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11291 (set-match-data link-match-data)
11292 (while (<= match-index number-of-groups)
11293 (let ((regex (concat "%" (number-to-string match-index)))
11294 (replace-with (match-string match-index dlink)))
11295 (while (string-match regex cmd)
11296 (setq cmd (replace-match replace-with t t cmd))))
11297 (setq match-index (+ match-index 1)))))
11299 (save-window-excursion
11300 (message "Running %s...done" cmd)
11301 (start-process-shell-command cmd nil cmd)
11302 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11303 ((or (stringp cmd)
11304 (eq cmd 'emacs))
11305 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11306 (widen)
11307 (if line (progn (org-goto-line line)
11308 (if (derived-mode-p 'org-mode)
11309 (org-reveal)))
11310 (if search (org-link-search search))))
11311 ((consp cmd)
11312 (let ((file (convert-standard-filename file)))
11313 (save-match-data
11314 (set-match-data link-match-data)
11315 (eval cmd))))
11316 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11317 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11318 (or (not (equal old-buffer (current-buffer)))
11319 (not (equal old-pos (point))))
11320 (org-mark-ring-push old-pos old-buffer))))
11322 (defun org-file-apps-entry-match-against-dlink-p (entry)
11323 "This function returns non-nil if `entry' uses a regular
11324 expression which should be matched against the whole link by
11325 org-open-file.
11327 It assumes that is the case when the entry uses a regular
11328 expression which has at least one grouping construct and the
11329 action is either a lisp form or a command string containing
11330 '%1', i.e. using at least one subexpression match as a
11331 parameter."
11332 (let ((selector (car entry))
11333 (action (cdr entry)))
11334 (if (stringp selector)
11335 (and (> (regexp-opt-depth selector) 0)
11336 (or (and (stringp action)
11337 (string-match "%[0-9]" action))
11338 (consp action)))
11339 nil)))
11341 (defun org-default-apps ()
11342 "Return the default applications for this operating system."
11343 (cond
11344 ((eq system-type 'darwin)
11345 org-file-apps-defaults-macosx)
11346 ((eq system-type 'windows-nt)
11347 org-file-apps-defaults-windowsnt)
11348 (t org-file-apps-defaults-gnu)))
11350 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11351 "Convert extensions to regular expressions in the cars of LIST.
11352 Also, weed out any non-string entries, because the return value is used
11353 only for regexp matching.
11354 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11355 point to the symbol `emacs', indicating that the file should
11356 be opened in Emacs."
11357 (append
11358 (delq nil
11359 (mapcar (lambda (x)
11360 (if (not (stringp (car x)))
11362 (if (string-match "\\W" (car x))
11364 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11365 list))
11366 (if add-auto-mode
11367 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11369 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11370 (defun org-file-remote-p (file)
11371 "Test whether FILE specifies a location on a remote system.
11372 Return non-nil if the location is indeed remote.
11374 For example, the filename \"/user@host:/foo\" specifies a location
11375 on the system \"/user@host:\"."
11376 (cond ((fboundp 'file-remote-p)
11377 (file-remote-p file))
11378 ((fboundp 'tramp-handle-file-remote-p)
11379 (tramp-handle-file-remote-p file))
11380 ((and (boundp 'ange-ftp-name-format)
11381 (string-match (car ange-ftp-name-format) file))
11382 t)))
11385 ;;;; Refiling
11387 (defun org-get-org-file ()
11388 "Read a filename, with default directory `org-directory'."
11389 (let ((default (or org-default-notes-file remember-data-file)))
11390 (read-file-name (format "File name [%s]: " default)
11391 (file-name-as-directory org-directory)
11392 default)))
11394 (defun org-notes-order-reversed-p ()
11395 "Check if the current file should receive notes in reversed order."
11396 (cond
11397 ((not org-reverse-note-order) nil)
11398 ((eq t org-reverse-note-order) t)
11399 ((not (listp org-reverse-note-order)) nil)
11400 (t (catch 'exit
11401 (let ((all org-reverse-note-order)
11402 entry)
11403 (while (setq entry (pop all))
11404 (if (string-match (car entry) buffer-file-name)
11405 (throw 'exit (cdr entry))))
11406 nil)))))
11408 (defvar org-refile-target-table nil
11409 "The list of refile targets, created by `org-refile'.")
11411 (defvar org-agenda-new-buffers nil
11412 "Buffers created to visit agenda files.")
11414 (defvar org-refile-cache nil
11415 "Cache for refile targets.")
11417 (defvar org-refile-markers nil
11418 "All the markers used for caching refile locations.")
11420 (defun org-refile-marker (pos)
11421 "Get a new refile marker, but only if caching is in use."
11422 (if (not org-refile-use-cache)
11424 (let ((m (make-marker)))
11425 (move-marker m pos)
11426 (push m org-refile-markers)
11427 m)))
11429 (defun org-refile-cache-clear ()
11430 "Clear the refile cache and disable all the markers."
11431 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11432 (setq org-refile-markers nil)
11433 (setq org-refile-cache nil)
11434 (message "Refile cache has been cleared"))
11436 (defun org-refile-cache-check-set (set)
11437 "Check if all the markers in the cache still have live buffers."
11438 (let (marker)
11439 (catch 'exit
11440 (while (and set (setq marker (nth 3 (pop set))))
11441 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11442 (when (and marker (null (marker-buffer marker)))
11443 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11444 (sit-for 3)
11445 (throw 'exit nil)))
11446 t)))
11448 (defun org-refile-cache-put (set &rest identifiers)
11449 "Push the refile targets SET into the cache, under IDENTIFIERS."
11450 (let* ((key (sha1 (prin1-to-string identifiers)))
11451 (entry (assoc key org-refile-cache)))
11452 (if entry
11453 (setcdr entry set)
11454 (push (cons key set) org-refile-cache))))
11456 (defun org-refile-cache-get (&rest identifiers)
11457 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11458 (cond
11459 ((not org-refile-cache) nil)
11460 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11462 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11463 org-refile-cache))))
11464 (and set (org-refile-cache-check-set set) set)))))
11466 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11467 "Produce a table with refile targets."
11468 (let ((case-fold-search nil)
11469 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11470 (entries (or org-refile-targets '((nil . (:level . 1)))))
11471 targets tgs txt re files f desc descre fast-path-p level pos0)
11472 (message "Getting targets...")
11473 (with-current-buffer (or default-buffer (current-buffer))
11474 (while (setq entry (pop entries))
11475 (setq files (car entry) desc (cdr entry))
11476 (setq fast-path-p nil)
11477 (cond
11478 ((null files) (setq files (list (current-buffer))))
11479 ((eq files 'org-agenda-files)
11480 (setq files (org-agenda-files 'unrestricted)))
11481 ((and (symbolp files) (fboundp files))
11482 (setq files (funcall files)))
11483 ((and (symbolp files) (boundp files))
11484 (setq files (symbol-value files))))
11485 (if (stringp files) (setq files (list files)))
11486 (cond
11487 ((eq (car desc) :tag)
11488 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11489 ((eq (car desc) :todo)
11490 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11491 ((eq (car desc) :regexp)
11492 (setq descre (cdr desc)))
11493 ((eq (car desc) :level)
11494 (setq descre (concat "^\\*\\{" (number-to-string
11495 (if org-odd-levels-only
11496 (1- (* 2 (cdr desc)))
11497 (cdr desc)))
11498 "\\}[ \t]")))
11499 ((eq (car desc) :maxlevel)
11500 (setq fast-path-p t)
11501 (setq descre (concat "^\\*\\{1," (number-to-string
11502 (if org-odd-levels-only
11503 (1- (* 2 (cdr desc)))
11504 (cdr desc)))
11505 "\\}[ \t]")))
11506 (t (error "Bad refiling target description %s" desc)))
11507 (while (setq f (pop files))
11508 (with-current-buffer
11509 (if (bufferp f) f (org-get-agenda-file-buffer f))
11511 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11512 (progn
11513 (if (bufferp f) (setq f (buffer-file-name
11514 (buffer-base-buffer f))))
11515 (setq f (and f (expand-file-name f)))
11516 (if (eq org-refile-use-outline-path 'file)
11517 (push (list (file-name-nondirectory f) f nil nil) tgs))
11518 (save-excursion
11519 (save-restriction
11520 (widen)
11521 (goto-char (point-min))
11522 (while (re-search-forward descre nil t)
11523 (goto-char (setq pos0 (point-at-bol)))
11524 (catch 'next
11525 (when org-refile-target-verify-function
11526 (save-match-data
11527 (or (funcall org-refile-target-verify-function)
11528 (throw 'next t))))
11529 (when (and (looking-at org-complex-heading-regexp)
11530 (not (member (match-string 4) excluded-entries))
11531 (match-string 4))
11532 (setq level (org-reduced-level
11533 (- (match-end 1) (match-beginning 1)))
11534 txt (org-link-display-format (match-string 4))
11535 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11536 re (format org-complex-heading-regexp-format
11537 (regexp-quote (match-string 4))))
11538 (when org-refile-use-outline-path
11539 (setq txt (mapconcat
11540 'org-protect-slash
11541 (append
11542 (if (eq org-refile-use-outline-path
11543 'file)
11544 (list (file-name-nondirectory
11545 (buffer-file-name
11546 (buffer-base-buffer))))
11547 (if (eq org-refile-use-outline-path
11548 'full-file-path)
11549 (list (buffer-file-name
11550 (buffer-base-buffer)))))
11551 (org-get-outline-path fast-path-p
11552 level txt)
11553 (list txt))
11554 "/")))
11555 (push (list txt f re (org-refile-marker (point)))
11556 tgs)))
11557 (when (= (point) pos0)
11558 ;; verification function has not moved point
11559 (goto-char (point-at-eol))))))))
11560 (when org-refile-use-cache
11561 (org-refile-cache-put tgs (buffer-file-name) descre))
11562 (setq targets (append tgs targets))))))
11563 (message "Getting targets...done")
11564 (nreverse targets)))
11566 (defun org-protect-slash (s)
11567 (while (string-match "/" s)
11568 (setq s (replace-match "\\" t t s)))
11571 (defvar org-olpa (make-vector 20 nil))
11573 (defun org-get-outline-path (&optional fastp level heading)
11574 "Return the outline path to the current entry, as a list.
11576 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11577 routine which makes outline path derivations for an entire file,
11578 avoiding backtracing. Refile target collection makes use of that."
11579 (if fastp
11580 (progn
11581 (if (> level 19)
11582 (error "Outline path failure, more than 19 levels"))
11583 (loop for i from level upto 19 do
11584 (aset org-olpa i nil))
11585 (prog1
11586 (delq nil (append org-olpa nil))
11587 (aset org-olpa level heading)))
11588 (let (rtn case-fold-search)
11589 (save-excursion
11590 (save-restriction
11591 (widen)
11592 (while (org-up-heading-safe)
11593 (when (looking-at org-complex-heading-regexp)
11594 (push (org-trim
11595 (replace-regexp-in-string
11596 ;; Remove statistical/checkboxes cookies
11597 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11598 (org-match-string-no-properties 4)))
11599 rtn)))
11600 rtn)))))
11602 (defun org-format-outline-path (path &optional width prefix separator)
11603 "Format the outline path PATH for display.
11604 WIDTH is the maximum number of characters that is available.
11605 PREFIX is a prefix to be included in the returned string,
11606 such as the file name.
11607 SEPARATOR is inserted between the different parts of the path,
11608 the default is \"/\"."
11609 (setq width (or width 79))
11610 (if prefix (setq width (- width (length prefix))))
11611 (if (not path)
11612 (or prefix "")
11613 (let* ((nsteps (length path))
11614 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11615 (maxwidth (if (<= total-width width)
11616 10000 ;; everything fits
11617 ;; we need to shorten the level headings
11618 (/ (- width nsteps) nsteps)))
11619 (org-odd-levels-only nil)
11620 (n 0)
11621 (total (1+ (length prefix))))
11622 (setq maxwidth (max maxwidth 10))
11623 (concat prefix
11624 (if prefix (or separator "/"))
11625 (mapconcat
11626 (lambda (h)
11627 (setq n (1+ n))
11628 (if (and (= n nsteps) (< maxwidth 10000))
11629 (setq maxwidth (- total-width total)))
11630 (if (< (length h) maxwidth)
11631 (progn (setq total (+ total (length h) 1)) h)
11632 (setq h (substring h 0 (- maxwidth 2))
11633 total (+ total maxwidth 1))
11634 (if (string-match "[ \t]+\\'" h)
11635 (setq h (substring h 0 (match-beginning 0))))
11636 (setq h (concat h "..")))
11637 (org-add-props h nil 'face
11638 (nth (% (1- n) org-n-level-faces)
11639 org-level-faces))
11641 path (or separator "/"))))))
11643 (defun org-display-outline-path (&optional file current separator just-return-string)
11644 "Display the current outline path in the echo area.
11646 If FILE is non-nil, prepend the output with the file name.
11647 If CURRENT is non-nil, append the current heading to the output.
11648 SEPARATOR is passed through to `org-format-outline-path'. It separates
11649 the different parts of the path and defaults to \"/\".
11650 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11651 (interactive "P")
11652 (let* (case-fold-search
11653 (bfn (buffer-file-name (buffer-base-buffer)))
11654 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11655 res)
11656 (if current (setq path (append path
11657 (save-excursion
11658 (org-back-to-heading t)
11659 (if (looking-at org-complex-heading-regexp)
11660 (list (match-string 4)))))))
11661 (setq res
11662 (org-format-outline-path
11663 path
11664 (1- (frame-width))
11665 (and file bfn (concat (file-name-nondirectory bfn) separator))
11666 separator))
11667 (if just-return-string
11668 (org-no-properties res)
11669 (org-unlogged-message "%s" res))))
11671 (defvar org-refile-history nil
11672 "History for refiling operations.")
11674 (defvar org-after-refile-insert-hook nil
11675 "Hook run after `org-refile' has inserted its stuff at the new location.
11676 Note that this is still *before* the stuff will be removed from
11677 the *old* location.")
11679 (defvar org-capture-last-stored-marker)
11680 (defvar org-refile-keep nil
11681 "Non-nil means `org-refile' will copy instead of refile.")
11683 (defun org-copy ()
11684 "Like `org-refile', but copy."
11685 (interactive)
11686 (let ((org-refile-keep t))
11687 (funcall 'org-refile nil nil nil "Copy")))
11689 (defun org-refile (&optional arg default-buffer rfloc msg)
11690 "Move the entry or entries at point to another heading.
11691 The list of target headings is compiled using the information in
11692 `org-refile-targets', which see.
11694 At the target location, the entry is filed as a subitem of the
11695 target heading. Depending on `org-reverse-note-order', the new
11696 subitem will either be the first or the last subitem.
11698 If there is an active region, all entries in that region will be
11699 refiled. However, the region must fulfill the requirement that
11700 the first heading sets the top-level of the moved text.
11702 With prefix arg ARG, the command will only visit the target
11703 location and not actually move anything.
11705 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11706 refiling operation has put the subtree.
11708 With a numeric prefix argument of `2', refile to the running clock.
11710 With a numeric prefix argument of `3', emulate `org-refile-keep'
11711 being set to `t' and copy to the target location, don't move it.
11712 Beware that keeping refiled entries may result in duplicated ID
11713 properties.
11715 RFLOC can be a refile location obtained in a different way.
11717 MSG is a string to replace \"Refile\" in the default prompt with
11718 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11720 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11722 If you are using target caching (see `org-refile-use-cache'), you
11723 have to clear the target cache in order to find new targets.
11724 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11725 prefix argument (`C-u C-u C-u C-c C-w')."
11726 (interactive "P")
11727 (if (member arg '(0 (64)))
11728 (org-refile-cache-clear)
11729 (let* ((actionmsg (cond (msg msg)
11730 ((equal arg 3) "Refile (and keep)")
11731 (t "Refile")))
11732 (cbuf (current-buffer))
11733 (regionp (org-region-active-p))
11734 (region-start (and regionp (region-beginning)))
11735 (region-end (and regionp (region-end)))
11736 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11737 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11738 pos it nbuf file re level reversed)
11739 (setq last-command nil)
11740 (when regionp
11741 (goto-char region-start)
11742 (or (bolp) (goto-char (point-at-bol)))
11743 (setq region-start (point))
11744 (unless (or (org-kill-is-subtree-p
11745 (buffer-substring region-start region-end))
11746 (prog1 org-refile-active-region-within-subtree
11747 (let ((s (point-at-eol)))
11748 (org-toggle-heading)
11749 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11750 (user-error "The region is not a (sequence of) subtree(s)")))
11751 (if (equal arg '(16))
11752 (org-refile-goto-last-stored)
11753 (when (or
11754 (and (equal arg 2)
11755 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11756 (prog1
11757 (setq it (list (or org-clock-heading "running clock")
11758 (buffer-file-name
11759 (marker-buffer org-clock-hd-marker))
11761 (marker-position org-clock-hd-marker)))
11762 (setq arg nil)))
11763 (setq it (or rfloc
11764 (let (heading-text)
11765 (save-excursion
11766 (unless (and arg (listp arg))
11767 (org-back-to-heading t)
11768 (setq heading-text
11769 (replace-regexp-in-string
11770 org-bracket-link-regexp
11771 "\\3"
11772 (nth 4 (org-heading-components)))))
11773 (org-refile-get-location
11774 (cond ((and arg (listp arg)) "Goto")
11775 (regionp (concat actionmsg " region to"))
11776 (t (concat actionmsg " subtree \""
11777 heading-text "\" to")))
11778 default-buffer
11779 (and (not (equal '(4) arg))
11780 org-refile-allow-creating-parent-nodes)
11781 arg))))))
11782 (setq file (nth 1 it)
11783 re (nth 2 it)
11784 pos (nth 3 it))
11785 (if (and (not arg)
11787 (equal (buffer-file-name) file)
11788 (if regionp
11789 (and (>= pos region-start)
11790 (<= pos region-end))
11791 (and (>= pos (point))
11792 (< pos (save-excursion
11793 (org-end-of-subtree t t))))))
11794 (error "Cannot refile to position inside the tree or region"))
11795 (setq nbuf (or (find-buffer-visiting file)
11796 (find-file-noselect file)))
11797 (if (and arg (not (equal arg 3)))
11798 (progn
11799 (org-pop-to-buffer-same-window nbuf)
11800 (goto-char pos)
11801 (org-show-context 'org-goto))
11802 (if regionp
11803 (progn
11804 (org-kill-new (buffer-substring region-start region-end))
11805 (org-save-markers-in-region region-start region-end))
11806 (org-copy-subtree 1 nil t))
11807 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11808 (find-file-noselect file)))
11809 (setq reversed (org-notes-order-reversed-p))
11810 (save-excursion
11811 (save-restriction
11812 (widen)
11813 (if pos
11814 (progn
11815 (goto-char pos)
11816 (looking-at org-outline-regexp)
11817 (setq level (org-get-valid-level (funcall outline-level) 1))
11818 (goto-char
11819 (if reversed
11820 (or (outline-next-heading) (point-max))
11821 (or (save-excursion (org-get-next-sibling))
11822 (org-end-of-subtree t t)
11823 (point-max)))))
11824 (setq level 1)
11825 (if (not reversed)
11826 (goto-char (point-max))
11827 (goto-char (point-min))
11828 (or (outline-next-heading) (goto-char (point-max)))))
11829 (if (not (bolp)) (newline))
11830 (org-paste-subtree level)
11831 (when org-log-refile
11832 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11833 (unless (eq org-log-refile 'note)
11834 (save-excursion (org-add-log-note))))
11835 (and org-auto-align-tags
11836 (let ((org-loop-over-headlines-in-active-region nil))
11837 (org-set-tags nil t)))
11838 (let ((bookmark-name (plist-get org-bookmark-names-plist
11839 :last-refile)))
11840 (when bookmark-name
11841 (with-demoted-errors
11842 (bookmark-set bookmark-name))))
11843 ;; If we are refiling for capture, make sure that the
11844 ;; last-capture pointers point here
11845 (when (org-bound-and-true-p org-refile-for-capture)
11846 (let ((bookmark-name (plist-get org-bookmark-names-plist
11847 :last-capture-marker)))
11848 (when bookmark-name
11849 (with-demoted-errors
11850 (bookmark-set bookmark-name))))
11851 (move-marker org-capture-last-stored-marker (point)))
11852 (if (fboundp 'deactivate-mark) (deactivate-mark))
11853 (run-hooks 'org-after-refile-insert-hook))))
11854 (unless org-refile-keep
11855 (if regionp
11856 (delete-region (point) (+ (point) (- region-end region-start)))
11857 (delete-region
11858 (and (org-back-to-heading t) (point))
11859 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11860 (when (featurep 'org-inlinetask)
11861 (org-inlinetask-remove-END-maybe))
11862 (setq org-markers-to-move nil)
11863 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11865 (defun org-refile-goto-last-stored ()
11866 "Go to the location where the last refile was stored."
11867 (interactive)
11868 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11869 (message "This is the location of the last refile"))
11871 (defun org-refile--get-location (refloc tbl)
11872 "When user refile to REFLOC, find the associated target in TBL.
11873 Also check `org-refile-target-table'."
11874 (car (delq
11876 (mapcar
11877 (lambda (r) (or (assoc r tbl)
11878 (assoc r org-refile-target-table)))
11879 (list (replace-regexp-in-string "/$" "" refloc)
11880 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11882 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11883 no-exclude)
11884 "Prompt the user for a refile location, using PROMPT.
11885 PROMPT should not be suffixed with a colon and a space, because
11886 this function appends the default value from
11887 `org-refile-history' automatically, if that is not empty.
11888 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11889 this is used for the GOTO interface."
11890 (let ((org-refile-targets org-refile-targets)
11891 (org-refile-use-outline-path org-refile-use-outline-path)
11892 excluded-entries)
11893 (when (and (derived-mode-p 'org-mode)
11894 (not org-refile-use-cache)
11895 (not no-exclude))
11896 (org-map-tree
11897 (lambda()
11898 (setq excluded-entries
11899 (append excluded-entries (list (org-get-heading t t)))))))
11900 (setq org-refile-target-table
11901 (org-refile-get-targets default-buffer excluded-entries)))
11902 (unless org-refile-target-table
11903 (user-error "No refile targets"))
11904 (let* ((cbuf (current-buffer))
11905 (partial-completion-mode nil)
11906 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11907 (cfunc (if (and org-refile-use-outline-path
11908 org-outline-path-complete-in-steps)
11909 'org-olpath-completing-read
11910 'org-icompleting-read))
11911 (extra (if org-refile-use-outline-path "/" ""))
11912 (cbnex (concat (buffer-name) extra))
11913 (filename (and cfn (expand-file-name cfn)))
11914 (tbl (mapcar
11915 (lambda (x)
11916 (if (and (not (member org-refile-use-outline-path
11917 '(file full-file-path)))
11918 (not (equal filename (nth 1 x))))
11919 (cons (concat (car x) extra " ("
11920 (file-name-nondirectory (nth 1 x)) ")")
11921 (cdr x))
11922 (cons (concat (car x) extra) (cdr x))))
11923 org-refile-target-table))
11924 (completion-ignore-case t)
11925 cdef
11926 (prompt (concat prompt
11927 (or (and (car org-refile-history)
11928 (concat " (default " (car org-refile-history) ")"))
11929 (and (assoc cbnex tbl) (setq cdef cbnex)
11930 (concat " (default " cbnex ")"))) ": "))
11931 pa answ parent-target child parent old-hist)
11932 (setq old-hist org-refile-history)
11933 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11934 nil 'org-refile-history (or cdef (car org-refile-history))))
11935 (if (setq pa (org-refile--get-location answ tbl))
11936 (progn
11937 (org-refile-check-position pa)
11938 (when (or (not org-refile-history)
11939 (not (eq old-hist org-refile-history))
11940 (not (equal (car pa) (car org-refile-history))))
11941 (setq org-refile-history
11942 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11943 org-refile-history
11944 (cdr org-refile-history))))
11945 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11946 (pop org-refile-history)))
11948 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11949 (progn
11950 (setq parent (match-string 1 answ)
11951 child (match-string 2 answ))
11952 (setq parent-target (org-refile--get-location parent tbl))
11953 (when (and parent-target
11954 (or (eq new-nodes t)
11955 (and (eq new-nodes 'confirm)
11956 (y-or-n-p (format "Create new node \"%s\"? "
11957 child)))))
11958 (org-refile-new-child parent-target child)))
11959 (user-error "Invalid target location")))))
11961 (declare-function org-string-nw-p "org-macs" (s))
11962 (defun org-refile-check-position (refile-pointer)
11963 "Check if the refile pointer matches the headline to which it points."
11964 (let* ((file (nth 1 refile-pointer))
11965 (re (nth 2 refile-pointer))
11966 (pos (nth 3 refile-pointer))
11967 buffer)
11968 (if (and (not (markerp pos)) (not file))
11969 (user-error "Please indicate a target file in the refile path")
11970 (when (org-string-nw-p re)
11971 (setq buffer (if (markerp pos)
11972 (marker-buffer pos)
11973 (or (find-buffer-visiting file)
11974 (find-file-noselect file))))
11975 (with-current-buffer buffer
11976 (save-excursion
11977 (save-restriction
11978 (widen)
11979 (goto-char pos)
11980 (beginning-of-line 1)
11981 (unless (org-looking-at-p re)
11982 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11984 (defun org-refile-new-child (parent-target child)
11985 "Use refile target PARENT-TARGET to add new CHILD below it."
11986 (unless parent-target
11987 (error "Cannot find parent for new node"))
11988 (let ((file (nth 1 parent-target))
11989 (pos (nth 3 parent-target))
11990 level)
11991 (with-current-buffer (or (find-buffer-visiting file)
11992 (find-file-noselect file))
11993 (save-excursion
11994 (save-restriction
11995 (widen)
11996 (if pos
11997 (goto-char pos)
11998 (goto-char (point-max))
11999 (if (not (bolp)) (newline)))
12000 (when (looking-at org-outline-regexp)
12001 (setq level (funcall outline-level))
12002 (org-end-of-subtree t t))
12003 (org-back-over-empty-lines)
12004 (insert "\n" (make-string
12005 (if pos (org-get-valid-level level 1) 1) ?*)
12006 " " child "\n")
12007 (beginning-of-line 0)
12008 (list (concat (car parent-target) "/" child) file "" (point)))))))
12010 (defun org-olpath-completing-read (prompt collection &rest args)
12011 "Read an outline path like a file name."
12012 (let ((thetable collection)
12013 (org-completion-use-ido nil) ; does not work with ido.
12014 (org-completion-use-iswitchb nil)) ; or iswitchb
12015 (apply
12016 'org-icompleting-read prompt
12017 (lambda (string predicate &optional flag)
12018 (let (rtn r f (l (length string)))
12019 (cond
12020 ((eq flag nil)
12021 ;; try completion
12022 (try-completion string thetable))
12023 ((eq flag t)
12024 ;; all-completions
12025 (setq rtn (all-completions string thetable predicate))
12026 (mapcar
12027 (lambda (x)
12028 (setq r (substring x l))
12029 (if (string-match " ([^)]*)$" x)
12030 (setq f (match-string 0 x))
12031 (setq f ""))
12032 (if (string-match "/" r)
12033 (concat string (substring r 0 (match-end 0)) f)
12035 rtn))
12036 ((eq flag 'lambda)
12037 ;; exact match?
12038 (assoc string thetable)))))
12039 args)))
12041 ;;;; Dynamic blocks
12043 (defun org-find-dblock (name)
12044 "Find the first dynamic block with name NAME in the buffer.
12045 If not found, stay at current position and return nil."
12046 (let ((case-fold-search t) pos)
12047 (save-excursion
12048 (goto-char (point-min))
12049 (setq pos (and (re-search-forward
12050 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12051 (match-beginning 0))))
12052 (if pos (goto-char pos))
12053 pos))
12055 (defun org-create-dblock (plist)
12056 "Create a dynamic block section, with parameters taken from PLIST.
12057 PLIST must contain a :name entry which is used as the name of the block."
12058 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12059 (end-of-line 1)
12060 (newline))
12061 (let ((col (current-column))
12062 (name (plist-get plist :name)))
12063 (insert "#+BEGIN: " name)
12064 (while plist
12065 (if (eq (car plist) :name)
12066 (setq plist (cddr plist))
12067 (insert " " (prin1-to-string (pop plist)))))
12068 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12069 (beginning-of-line -2)))
12071 (defun org-prepare-dblock ()
12072 "Prepare dynamic block for refresh.
12073 This empties the block, puts the cursor at the insert position and returns
12074 the property list including an extra property :name with the block name."
12075 (unless (looking-at org-dblock-start-re)
12076 (user-error "Not at a dynamic block"))
12077 (let* ((begdel (1+ (match-end 0)))
12078 (name (org-no-properties (match-string 1)))
12079 (params (append (list :name name)
12080 (read (concat "(" (match-string 3) ")")))))
12081 (save-excursion
12082 (beginning-of-line 1)
12083 (skip-chars-forward " \t")
12084 (setq params (plist-put params :indentation-column (current-column))))
12085 (unless (re-search-forward org-dblock-end-re nil t)
12086 (error "Dynamic block not terminated"))
12087 (setq params
12088 (append params
12089 (list :content (buffer-substring
12090 begdel (match-beginning 0)))))
12091 (delete-region begdel (match-beginning 0))
12092 (goto-char begdel)
12093 (open-line 1)
12094 params))
12096 (defun org-map-dblocks (&optional command)
12097 "Apply COMMAND to all dynamic blocks in the current buffer.
12098 If COMMAND is not given, use `org-update-dblock'."
12099 (let ((cmd (or command 'org-update-dblock)))
12100 (save-excursion
12101 (goto-char (point-min))
12102 (while (re-search-forward org-dblock-start-re nil t)
12103 (goto-char (match-beginning 0))
12104 (save-excursion
12105 (condition-case nil
12106 (funcall cmd)
12107 (error (message "Error during update of dynamic block"))))
12108 (unless (re-search-forward org-dblock-end-re nil t)
12109 (error "Dynamic block not terminated"))))))
12111 (defun org-dblock-update (&optional arg)
12112 "User command for updating dynamic blocks.
12113 Update the dynamic block at point. With prefix ARG, update all dynamic
12114 blocks in the buffer."
12115 (interactive "P")
12116 (if arg
12117 (org-update-all-dblocks)
12118 (or (looking-at org-dblock-start-re)
12119 (org-beginning-of-dblock))
12120 (org-update-dblock)))
12122 (defun org-update-dblock ()
12123 "Update the dynamic block at point.
12124 This means to empty the block, parse for parameters and then call
12125 the correct writing function."
12126 (interactive)
12127 (save-excursion
12128 (let* ((win (selected-window))
12129 (pos (point))
12130 (line (org-current-line))
12131 (params (org-prepare-dblock))
12132 (name (plist-get params :name))
12133 (indent (plist-get params :indentation-column))
12134 (cmd (intern (concat "org-dblock-write:" name))))
12135 (message "Updating dynamic block `%s' at line %d..." name line)
12136 (funcall cmd params)
12137 (message "Updating dynamic block `%s' at line %d...done" name line)
12138 (goto-char pos)
12139 (when (and indent (> indent 0))
12140 (setq indent (make-string indent ?\ ))
12141 (save-excursion
12142 (select-window win)
12143 (org-beginning-of-dblock)
12144 (forward-line 1)
12145 (while (not (looking-at org-dblock-end-re))
12146 (insert indent)
12147 (beginning-of-line 2))
12148 (when (looking-at org-dblock-end-re)
12149 (and (looking-at "[ \t]+")
12150 (replace-match ""))
12151 (insert indent)))))))
12153 (defun org-beginning-of-dblock ()
12154 "Find the beginning of the dynamic block at point.
12155 Error if there is no such block at point."
12156 (let ((pos (point))
12157 beg)
12158 (end-of-line 1)
12159 (if (and (re-search-backward org-dblock-start-re nil t)
12160 (setq beg (match-beginning 0))
12161 (re-search-forward org-dblock-end-re nil t)
12162 (> (match-end 0) pos))
12163 (goto-char beg)
12164 (goto-char pos)
12165 (error "Not in a dynamic block"))))
12167 (defun org-update-all-dblocks ()
12168 "Update all dynamic blocks in the buffer.
12169 This function can be used in a hook."
12170 (interactive)
12171 (when (derived-mode-p 'org-mode)
12172 (org-map-dblocks 'org-update-dblock)))
12175 ;;;; Completion
12177 (declare-function org-export-backend-name "org-export" (cl-x))
12178 (declare-function org-export-backend-options "org-export" (cl-x))
12179 (defun org-get-export-keywords ()
12180 "Return a list of all currently understood export keywords.
12181 Export keywords include options, block names, attributes and
12182 keywords relative to each registered export back-end."
12183 (let (keywords)
12184 (dolist (backend
12185 (org-bound-and-true-p org-export--registered-backends)
12186 (delq nil keywords))
12187 ;; Back-end name (for keywords, like #+LATEX:)
12188 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12189 (dolist (option-entry (org-export-backend-options backend))
12190 ;; Back-end options.
12191 (push (nth 1 option-entry) keywords)))))
12193 (defconst org-options-keywords
12194 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12195 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12196 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12197 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12198 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12200 (defcustom org-structure-template-alist
12201 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12202 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12203 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12204 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12205 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12206 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12207 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12208 "<literal style=\"latex\">\n?\n</literal>")
12209 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12210 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12211 "<literal style=\"html\">\n?\n</literal>")
12212 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12213 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12214 ("A" "#+ASCII: " "")
12215 ("i" "#+INDEX: ?" "#+INDEX: ?")
12216 ("I" "#+INCLUDE: %file ?"
12217 "<include file=%file markup=\"?\">"))
12218 "Structure completion elements.
12219 This is a list of abbreviation keys and values. The value gets inserted
12220 if you type `<' followed by the key and then press the completion key,
12221 usually `M-TAB'. %file will be replaced by a file name after prompting
12222 for the file using completion. The cursor will be placed at the position
12223 of the `?` in the template.
12224 There are two templates for each key, the first uses the original Org syntax,
12225 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12226 the default when the /org-mtags.el/ module has been loaded. See also the
12227 variable `org-mtags-prefer-muse-templates'."
12228 :group 'org-completion
12229 :type '(repeat
12230 (list
12231 (string :tag "Key")
12232 (string :tag "Template")
12233 (string :tag "Muse Template"))))
12235 (defun org-try-structure-completion ()
12236 "Try to complete a structure template before point.
12237 This looks for strings like \"<e\" on an otherwise empty line and
12238 expands them."
12239 (let ((l (buffer-substring (point-at-bol) (point)))
12241 (when (and (looking-at "[ \t]*$")
12242 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12243 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12244 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12245 (match-beginning 1)) a)
12246 t)))
12248 (defun org-complete-expand-structure-template (start cell)
12249 "Expand a structure template."
12250 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12251 (rpl (nth (if musep 2 1) cell))
12252 (ind ""))
12253 (delete-region start (point))
12254 (when (string-match "\\`[ \t]*#\\+" rpl)
12255 (cond
12256 ((bolp))
12257 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12258 (setq ind (buffer-substring (point-at-bol) (point))))
12259 (t (newline))))
12260 (setq start (point))
12261 (if (string-match "%file" rpl)
12262 (setq rpl (replace-match
12263 (concat
12264 "\""
12265 (save-match-data
12266 (abbreviate-file-name (read-file-name "Include file: ")))
12267 "\"")
12268 t t rpl)))
12269 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12270 (concat "\n" ind)))
12271 (insert rpl)
12272 (if (re-search-backward "\\?" start t) (delete-char 1))))
12274 ;;;; TODO, DEADLINE, Comments
12276 (defun org-toggle-comment ()
12277 "Change the COMMENT state of an entry."
12278 (interactive)
12279 (save-excursion
12280 (org-back-to-heading)
12281 (looking-at org-complex-heading-regexp)
12282 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12283 (skip-chars-forward " \t")
12284 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12285 (if (org-in-commented-heading-p t)
12286 (delete-region (point)
12287 (progn (search-forward " " (line-end-position) 'move)
12288 (skip-chars-forward " \t")
12289 (point)))
12290 (insert org-comment-string)
12291 (unless (eolp) (insert " ")))))
12293 (defvar org-last-todo-state-is-todo nil
12294 "This is non-nil when the last TODO state change led to a TODO state.
12295 If the last change removed the TODO tag or switched to DONE, then
12296 this is nil.")
12298 (defvar org-setting-tags nil) ; dynamically skipped
12300 (defvar org-todo-setup-filter-hook nil
12301 "Hook for functions that pre-filter todo specs.
12302 Each function takes a todo spec and returns either nil or the spec
12303 transformed into canonical form." )
12305 (defvar org-todo-get-default-hook nil
12306 "Hook for functions that get a default item for todo.
12307 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12308 nil or a string to be used for the todo mark." )
12310 (defvar org-agenda-headline-snapshot-before-repeat)
12312 (defun org-current-effective-time ()
12313 "Return current time adjusted for `org-extend-today-until' variable."
12314 (let* ((ct (org-current-time))
12315 (dct (decode-time ct))
12316 (ct1
12317 (cond
12318 (org-use-last-clock-out-time-as-effective-time
12319 (or (org-clock-get-last-clock-out-time) ct))
12320 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12321 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12322 (t ct))))
12323 ct1))
12325 (defun org-todo-yesterday (&optional arg)
12326 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12327 (interactive "P")
12328 (if (eq major-mode 'org-agenda-mode)
12329 (apply 'org-agenda-todo-yesterday arg)
12330 (let* ((hour (third (decode-time
12331 (org-current-time))))
12332 (org-extend-today-until (1+ hour)))
12333 (org-todo arg))))
12335 (defvar org-block-entry-blocking ""
12336 "First entry preventing the TODO state change.")
12338 (defun org-cancel-repeater ()
12339 "Cancel a repeater by setting its numeric value to zero."
12340 (interactive)
12341 (save-excursion
12342 (org-back-to-heading t)
12343 (let ((bound1 (point))
12344 (bound0 (save-excursion (outline-next-heading) (point))))
12345 (when (re-search-forward
12346 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12347 org-deadline-time-regexp "\\)\\|\\("
12348 org-ts-regexp "\\)")
12349 bound0 t)
12350 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12351 (replace-match "0" t nil nil 1))))))
12353 (defun org-todo (&optional arg)
12354 "Change the TODO state of an item.
12355 The state of an item is given by a keyword at the start of the heading,
12356 like
12357 *** TODO Write paper
12358 *** DONE Call mom
12360 The different keywords are specified in the variable `org-todo-keywords'.
12361 By default the available states are \"TODO\" and \"DONE\".
12362 So for this example: when the item starts with TODO, it is changed to DONE.
12363 When it starts with DONE, the DONE is removed. And when neither TODO nor
12364 DONE are present, add TODO at the beginning of the heading.
12366 With \\[universal-argument] prefix arg, use completion to determine the new \
12367 state.
12368 With numeric prefix arg, switch to that state.
12369 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12370 keywords (nextset).
12371 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12372 With a numeric prefix arg of 0, inhibit note taking for the change.
12373 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12375 When called through ELisp, arg is also interpreted in the following way:
12376 'none -> empty state
12377 \"\"(empty string) -> switch to empty state
12378 'done -> switch to DONE
12379 'nextset -> switch to the next set of keywords
12380 'previousset -> switch to the previous set of keywords
12381 \"WAITING\" -> switch to the specified keyword, but only if it
12382 really is a member of `org-todo-keywords'."
12383 (interactive "P")
12384 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12385 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12386 'region-start-level 'region))
12387 org-loop-over-headlines-in-active-region)
12388 (org-map-entries
12389 `(org-todo ,arg)
12390 org-loop-over-headlines-in-active-region
12391 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12392 (if (equal arg '(16)) (setq arg 'nextset))
12393 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12394 (let ((org-blocker-hook org-blocker-hook)
12395 commentp
12396 case-fold-search)
12397 (when (equal arg '(64))
12398 (setq arg nil org-blocker-hook nil))
12399 (when (and org-blocker-hook
12400 (or org-inhibit-blocking
12401 (org-entry-get nil "NOBLOCKING")))
12402 (setq org-blocker-hook nil))
12403 (save-excursion
12404 (catch 'exit
12405 (org-back-to-heading t)
12406 (when (org-in-commented-heading-p t)
12407 (org-toggle-comment)
12408 (setq commentp t))
12409 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12410 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12411 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12412 (let* ((match-data (match-data))
12413 (startpos (point-at-bol))
12414 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12415 (org-log-done org-log-done)
12416 (org-log-repeat org-log-repeat)
12417 (org-todo-log-states org-todo-log-states)
12418 (org-inhibit-logging
12419 (if (equal arg 0)
12420 (progn (setq arg nil) 'note) org-inhibit-logging))
12421 (this (match-string 1))
12422 (hl-pos (match-beginning 0))
12423 (head (org-get-todo-sequence-head this))
12424 (ass (assoc head org-todo-kwd-alist))
12425 (interpret (nth 1 ass))
12426 (done-word (nth 3 ass))
12427 (final-done-word (nth 4 ass))
12428 (org-last-state (or this ""))
12429 (completion-ignore-case t)
12430 (member (member this org-todo-keywords-1))
12431 (tail (cdr member))
12432 (org-state (cond
12433 ((and org-todo-key-trigger
12434 (or (and (equal arg '(4))
12435 (eq org-use-fast-todo-selection 'prefix))
12436 (and (not arg) org-use-fast-todo-selection
12437 (not (eq org-use-fast-todo-selection
12438 'prefix)))))
12439 ;; Use fast selection
12440 (org-fast-todo-selection))
12441 ((and (equal arg '(4))
12442 (or (not org-use-fast-todo-selection)
12443 (not org-todo-key-trigger)))
12444 ;; Read a state with completion
12445 (org-icompleting-read
12446 "State: " (mapcar 'list org-todo-keywords-1)
12447 nil t))
12448 ((eq arg 'right)
12449 (if this
12450 (if tail (car tail) nil)
12451 (car org-todo-keywords-1)))
12452 ((eq arg 'left)
12453 (if (equal member org-todo-keywords-1)
12455 (if this
12456 (nth (- (length org-todo-keywords-1)
12457 (length tail) 2)
12458 org-todo-keywords-1)
12459 (org-last org-todo-keywords-1))))
12460 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12461 (setq arg nil))) ; hack to fall back to cycling
12462 (arg
12463 ;; user or caller requests a specific state
12464 (cond
12465 ((equal arg "") nil)
12466 ((eq arg 'none) nil)
12467 ((eq arg 'done) (or done-word (car org-done-keywords)))
12468 ((eq arg 'nextset)
12469 (or (car (cdr (member head org-todo-heads)))
12470 (car org-todo-heads)))
12471 ((eq arg 'previousset)
12472 (let ((org-todo-heads (reverse org-todo-heads)))
12473 (or (car (cdr (member head org-todo-heads)))
12474 (car org-todo-heads))))
12475 ((car (member arg org-todo-keywords-1)))
12476 ((stringp arg)
12477 (user-error "State `%s' not valid in this file" arg))
12478 ((nth (1- (prefix-numeric-value arg))
12479 org-todo-keywords-1))))
12480 ((null member) (or head (car org-todo-keywords-1)))
12481 ((equal this final-done-word) nil) ;; -> make empty
12482 ((null tail) nil) ;; -> first entry
12483 ((memq interpret '(type priority))
12484 (if (eq this-command last-command)
12485 (car tail)
12486 (if (> (length tail) 0)
12487 (or done-word (car org-done-keywords))
12488 nil)))
12490 (car tail))))
12491 (org-state (or
12492 (run-hook-with-args-until-success
12493 'org-todo-get-default-hook org-state org-last-state)
12494 org-state))
12495 (next (if org-state (concat " " org-state " ") " "))
12496 (change-plist (list :type 'todo-state-change :from this :to org-state
12497 :position startpos))
12498 dolog now-done-p)
12499 (when org-blocker-hook
12500 (setq org-last-todo-state-is-todo
12501 (not (member this org-done-keywords)))
12502 (unless (save-excursion
12503 (save-match-data
12504 (org-with-wide-buffer
12505 (run-hook-with-args-until-failure
12506 'org-blocker-hook change-plist))))
12507 (if (org-called-interactively-p 'interactive)
12508 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12509 this org-state org-block-entry-blocking)
12510 ;; fail silently
12511 (message "TODO state change from %s to %s blocked (by \"%s\")"
12512 this org-state org-block-entry-blocking)
12513 (throw 'exit nil))))
12514 (store-match-data match-data)
12515 (replace-match next t t)
12516 (unless (pos-visible-in-window-p hl-pos)
12517 (message "TODO state changed to %s" (org-trim next)))
12518 (unless head
12519 (setq head (org-get-todo-sequence-head org-state)
12520 ass (assoc head org-todo-kwd-alist)
12521 interpret (nth 1 ass)
12522 done-word (nth 3 ass)
12523 final-done-word (nth 4 ass)))
12524 (when (memq arg '(nextset previousset))
12525 (message "Keyword-Set %d/%d: %s"
12526 (- (length org-todo-sets) -1
12527 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12528 (length org-todo-sets)
12529 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12530 (setq org-last-todo-state-is-todo
12531 (not (member org-state org-done-keywords)))
12532 (setq now-done-p (and (member org-state org-done-keywords)
12533 (not (member this org-done-keywords))))
12534 (and logging (org-local-logging logging))
12535 (when (and (or org-todo-log-states org-log-done)
12536 (not (eq org-inhibit-logging t))
12537 (not (memq arg '(nextset previousset))))
12538 ;; we need to look at recording a time and note
12539 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12540 (nth 2 (assoc this org-todo-log-states))))
12541 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12542 (setq dolog 'time))
12543 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12544 (and org-state
12545 (member org-state org-not-done-keywords)
12546 (not (member this org-not-done-keywords))))
12547 ;; This is now a todo state and was not one before
12548 ;; If there was a CLOSED time stamp, get rid of it.
12549 (org-add-planning-info nil nil 'closed))
12550 (when (and now-done-p org-log-done)
12551 ;; It is now done, and it was not done before
12552 (org-add-planning-info 'closed (org-current-effective-time))
12553 (if (and (not dolog) (eq 'note org-log-done))
12554 (org-add-log-setup 'done org-state this 'findpos 'note)))
12555 (when (and org-state dolog)
12556 ;; This is a non-nil state, and we need to log it
12557 (org-add-log-setup 'state org-state this 'findpos dolog)))
12558 ;; Fixup tag positioning
12559 (org-todo-trigger-tag-changes org-state)
12560 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12561 (when org-provide-todo-statistics
12562 (org-update-parent-todo-statistics))
12563 (run-hooks 'org-after-todo-state-change-hook)
12564 (if (and arg (not (member org-state org-done-keywords)))
12565 (setq head (org-get-todo-sequence-head org-state)))
12566 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12567 ;; Do we need to trigger a repeat?
12568 (when now-done-p
12569 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12570 ;; This is for the agenda, take a snapshot of the headline.
12571 (save-match-data
12572 (setq org-agenda-headline-snapshot-before-repeat
12573 (org-get-heading))))
12574 (org-auto-repeat-maybe org-state))
12575 ;; Fixup cursor location if close to the keyword
12576 (if (and (outline-on-heading-p)
12577 (not (bolp))
12578 (save-excursion (beginning-of-line 1)
12579 (looking-at org-todo-line-regexp))
12580 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12581 (progn
12582 (goto-char (or (match-end 2) (match-end 1)))
12583 (and (looking-at " ") (just-one-space))))
12584 (when org-trigger-hook
12585 (save-excursion
12586 (run-hook-with-args 'org-trigger-hook change-plist)))
12587 (when commentp (org-toggle-comment))))))))
12589 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12590 "Block turning an entry into a TODO, using the hierarchy.
12591 This checks whether the current task should be blocked from state
12592 changes. Such blocking occurs when:
12594 1. The task has children which are not all in a completed state.
12596 2. A task has a parent with the property :ORDERED:, and there
12597 are siblings prior to the current task with incomplete
12598 status.
12600 3. The parent of the task is blocked because it has siblings that should
12601 be done first, or is child of a block grandparent TODO entry."
12603 (if (not org-enforce-todo-dependencies)
12604 t ; if locally turned off don't block
12605 (catch 'dont-block
12606 ;; If this is not a todo state change, or if this entry is already DONE,
12607 ;; do not block
12608 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12609 (member (plist-get change-plist :from)
12610 (cons 'done org-done-keywords))
12611 (member (plist-get change-plist :to)
12612 (cons 'todo org-not-done-keywords))
12613 (not (plist-get change-plist :to)))
12614 (throw 'dont-block t))
12615 ;; If this task has children, and any are undone, it's blocked
12616 (save-excursion
12617 (org-back-to-heading t)
12618 (let ((this-level (funcall outline-level)))
12619 (outline-next-heading)
12620 (let ((child-level (funcall outline-level)))
12621 (while (and (not (eobp))
12622 (> child-level this-level))
12623 ;; this todo has children, check whether they are all
12624 ;; completed
12625 (if (and (not (org-entry-is-done-p))
12626 (org-entry-is-todo-p))
12627 (progn (setq org-block-entry-blocking (org-get-heading))
12628 (throw 'dont-block nil)))
12629 (outline-next-heading)
12630 (setq child-level (funcall outline-level))))))
12631 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12632 ;; any previous siblings are undone, it's blocked
12633 (save-excursion
12634 (org-back-to-heading t)
12635 (let* ((pos (point))
12636 (parent-pos (and (org-up-heading-safe) (point))))
12637 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12638 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12639 (forward-line 1)
12640 (re-search-forward org-not-done-heading-regexp pos t))
12641 (setq org-block-entry-blocking (match-string 0))
12642 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12643 ;; Search further up the hierarchy, to see if an ancestor is blocked
12644 (while t
12645 (goto-char parent-pos)
12646 (if (not (looking-at org-not-done-heading-regexp))
12647 (throw 'dont-block t)) ; do not block, parent is not a TODO
12648 (setq pos (point))
12649 (setq parent-pos (and (org-up-heading-safe) (point)))
12650 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12651 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12652 (forward-line 1)
12653 (re-search-forward org-not-done-heading-regexp pos t)
12654 (setq org-block-entry-blocking (org-get-heading)))
12655 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12657 (defcustom org-track-ordered-property-with-tag nil
12658 "Should the ORDERED property also be shown as a tag?
12659 The ORDERED property decides if an entry should require subtasks to be
12660 completed in sequence. Since a property is not very visible, setting
12661 this option means that toggling the ORDERED property with the command
12662 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12663 not relevant for the behavior, but it makes things more visible.
12665 Note that toggling the tag with tags commands will not change the property
12666 and therefore not influence behavior!
12668 This can be t, meaning the tag ORDERED should be used, It can also be a
12669 string to select a different tag for this task."
12670 :group 'org-todo
12671 :type '(choice
12672 (const :tag "No tracking" nil)
12673 (const :tag "Track with ORDERED tag" t)
12674 (string :tag "Use other tag")))
12676 (defun org-toggle-ordered-property ()
12677 "Toggle the ORDERED property of the current entry.
12678 For better visibility, you can track the value of this property with a tag.
12679 See variable `org-track-ordered-property-with-tag'."
12680 (interactive)
12681 (let* ((t1 org-track-ordered-property-with-tag)
12682 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12683 (save-excursion
12684 (org-back-to-heading)
12685 (if (org-entry-get nil "ORDERED")
12686 (progn
12687 (org-delete-property "ORDERED")
12688 (and tag (org-toggle-tag tag 'off))
12689 (message "Subtasks can be completed in arbitrary order"))
12690 (org-entry-put nil "ORDERED" "t")
12691 (and tag (org-toggle-tag tag 'on))
12692 (message "Subtasks must be completed in sequence")))))
12694 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12695 (defun org-block-todo-from-checkboxes (change-plist)
12696 "Block turning an entry into a TODO, using checkboxes.
12697 This checks whether the current task should be blocked from state
12698 changes because there are unchecked boxes in this entry."
12699 (if (not org-enforce-todo-checkbox-dependencies)
12700 t ; if locally turned off don't block
12701 (catch 'dont-block
12702 ;; If this is not a todo state change, or if this entry is already DONE,
12703 ;; do not block
12704 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12705 (member (plist-get change-plist :from)
12706 (cons 'done org-done-keywords))
12707 (member (plist-get change-plist :to)
12708 (cons 'todo org-not-done-keywords))
12709 (not (plist-get change-plist :to)))
12710 (throw 'dont-block t))
12711 ;; If this task has checkboxes that are not checked, it's blocked
12712 (save-excursion
12713 (org-back-to-heading t)
12714 (let ((beg (point)) end)
12715 (outline-next-heading)
12716 (setq end (point))
12717 (goto-char beg)
12718 (if (org-list-search-forward
12719 (concat (org-item-beginning-re)
12720 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12721 "\\[[- ]\\]")
12722 end t)
12723 (progn
12724 (if (boundp 'org-blocked-by-checkboxes)
12725 (setq org-blocked-by-checkboxes t))
12726 (throw 'dont-block nil)))))
12727 t))) ; do not block
12729 (defun org-entry-blocked-p ()
12730 "Is the current entry blocked?"
12731 (org-with-silent-modifications
12732 (if (org-entry-get nil "NOBLOCKING")
12733 nil ;; Never block this entry
12734 (not (run-hook-with-args-until-failure
12735 'org-blocker-hook
12736 (list :type 'todo-state-change
12737 :position (point)
12738 :from 'todo
12739 :to 'done))))))
12741 (defun org-update-statistics-cookies (all)
12742 "Update the statistics cookie, either from TODO or from checkboxes.
12743 This should be called with the cursor in a line with a statistics cookie."
12744 (interactive "P")
12745 (if all
12746 (progn
12747 (org-update-checkbox-count 'all)
12748 (org-map-entries 'org-update-parent-todo-statistics))
12749 (if (not (org-at-heading-p))
12750 (org-update-checkbox-count)
12751 (let ((pos (point-marker))
12752 end l1 l2)
12753 (ignore-errors (org-back-to-heading t))
12754 (if (not (org-at-heading-p))
12755 (org-update-checkbox-count)
12756 (setq l1 (org-outline-level))
12757 (setq end (save-excursion
12758 (outline-next-heading)
12759 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12760 (point)))
12761 (if (and (save-excursion
12762 (re-search-forward
12763 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12764 (not (save-excursion (re-search-forward
12765 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12766 (org-update-checkbox-count)
12767 (if (and l2 (> l2 l1))
12768 (progn
12769 (goto-char end)
12770 (org-update-parent-todo-statistics))
12771 (goto-char pos)
12772 (beginning-of-line 1)
12773 (while (re-search-forward
12774 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12775 (point-at-eol) t)
12776 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12777 (goto-char pos)
12778 (move-marker pos nil)))))
12780 (defvar org-entry-property-inherited-from) ;; defined below
12781 (defun org-update-parent-todo-statistics ()
12782 "Update any statistics cookie in the parent of the current headline.
12783 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12784 the entire subtree and this will travel up the hierarchy and update
12785 statistics everywhere."
12786 (let* ((prop (save-excursion (org-up-heading-safe)
12787 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12788 (recursive (or (not org-hierarchical-todo-statistics)
12789 (and prop (string-match "\\<recursive\\>" prop))))
12790 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12792 (first t)
12793 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12794 level ltoggle l1 new ndel
12795 (cnt-all 0) (cnt-done 0) is-percent kwd
12796 checkbox-beg ov ovs ove cookie-present)
12797 (catch 'exit
12798 (save-excursion
12799 (beginning-of-line 1)
12800 (setq ltoggle (funcall outline-level))
12801 ;; Three situations are to consider:
12803 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12804 ;; to the top-level ancestor on the headline;
12806 ;; 2. If parent has "recursive" property, repeat up to the
12807 ;; headline setting that property, taking inheritance into
12808 ;; account;
12810 ;; 3. Else, move up to direct parent and proceed only once.
12811 (while (and (setq level (org-up-heading-safe))
12812 (or recursive first)
12813 (>= (point) lim))
12814 (setq first nil cookie-present nil)
12815 (unless (and level
12816 (not (string-match
12817 "\\<checkbox\\>"
12818 (downcase (or (org-entry-get nil "COOKIE_DATA")
12819 "")))))
12820 (throw 'exit nil))
12821 (while (re-search-forward box-re (point-at-eol) t)
12822 (setq cnt-all 0 cnt-done 0 cookie-present t)
12823 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12824 (save-match-data
12825 (unless (outline-next-heading) (throw 'exit nil))
12826 (while (and (looking-at org-complex-heading-regexp)
12827 (> (setq l1 (length (match-string 1))) level))
12828 (setq kwd (and (or recursive (= l1 ltoggle))
12829 (match-string 2)))
12830 (if (or (eq org-provide-todo-statistics 'all-headlines)
12831 (and (eq org-provide-todo-statistics t)
12832 (or (member kwd org-done-keywords)))
12833 (and (listp org-provide-todo-statistics)
12834 (stringp (car org-provide-todo-statistics))
12835 (or (member kwd org-provide-todo-statistics)
12836 (member kwd org-done-keywords)))
12837 (and (listp org-provide-todo-statistics)
12838 (listp (car org-provide-todo-statistics))
12839 (or (member kwd (car org-provide-todo-statistics))
12840 (and (member kwd org-done-keywords)
12841 (member kwd (cadr org-provide-todo-statistics))))))
12842 (setq cnt-all (1+ cnt-all))
12843 (if (eq org-provide-todo-statistics t)
12844 (and kwd (setq cnt-all (1+ cnt-all)))))
12845 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12846 (member kwd org-done-keywords))
12847 (and (listp org-provide-todo-statistics)
12848 (listp (car org-provide-todo-statistics))
12849 (member kwd org-done-keywords)
12850 (member kwd (cadr org-provide-todo-statistics)))
12851 (and (listp org-provide-todo-statistics)
12852 (stringp (car org-provide-todo-statistics))
12853 (member kwd org-done-keywords)))
12854 (setq cnt-done (1+ cnt-done)))
12855 (outline-next-heading)))
12856 (setq new
12857 (if is-percent
12858 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12859 (format "[%d/%d]" cnt-done cnt-all))
12860 ndel (- (match-end 0) checkbox-beg))
12861 ;; handle overlays when updating cookie from column view
12862 (when (setq ov (car (overlays-at checkbox-beg)))
12863 (setq ovs (overlay-start ov) ove (overlay-end ov))
12864 (delete-overlay ov))
12865 (goto-char checkbox-beg)
12866 (insert new)
12867 (delete-region (point) (+ (point) ndel))
12868 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12869 (when ov (move-overlay ov ovs ove)))
12870 (when cookie-present
12871 (run-hook-with-args 'org-after-todo-statistics-hook
12872 cnt-done (- cnt-all cnt-done))))))
12873 (run-hooks 'org-todo-statistics-hook)))
12875 (defvar org-after-todo-statistics-hook nil
12876 "Hook that is called after a TODO statistics cookie has been updated.
12877 Each function is called with two arguments: the number of not-done entries
12878 and the number of done entries.
12880 For example, the following function, when added to this hook, will switch
12881 an entry to DONE when all children are done, and back to TODO when new
12882 entries are set to a TODO status. Note that this hook is only called
12883 when there is a statistics cookie in the headline!
12885 (defun org-summary-todo (n-done n-not-done)
12886 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12887 (let (org-log-done org-log-states) ; turn off logging
12888 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12891 (defvar org-todo-statistics-hook nil
12892 "Hook that is run whenever Org thinks TODO statistics should be updated.
12893 This hook runs even if there is no statistics cookie present, in which case
12894 `org-after-todo-statistics-hook' would not run.")
12896 (defun org-todo-trigger-tag-changes (state)
12897 "Apply the changes defined in `org-todo-state-tags-triggers'."
12898 (let ((l org-todo-state-tags-triggers)
12899 changes)
12900 (when (or (not state) (equal state ""))
12901 (setq changes (append changes (cdr (assoc "" l)))))
12902 (when (and (stringp state) (> (length state) 0))
12903 (setq changes (append changes (cdr (assoc state l)))))
12904 (when (member state org-not-done-keywords)
12905 (setq changes (append changes (cdr (assoc 'todo l)))))
12906 (when (member state org-done-keywords)
12907 (setq changes (append changes (cdr (assoc 'done l)))))
12908 (dolist (c changes)
12909 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12911 (defun org-local-logging (value)
12912 "Get logging settings from a property VALUE."
12913 (let* (words w a)
12914 ;; directly set the variables, they are already local.
12915 (setq org-log-done nil
12916 org-log-repeat nil
12917 org-todo-log-states nil)
12918 (setq words (org-split-string value))
12919 (while (setq w (pop words))
12920 (cond
12921 ((setq a (assoc w org-startup-options))
12922 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12923 (set (nth 1 a) (nth 2 a))))
12924 ((setq a (org-extract-log-state-settings w))
12925 (and (member (car a) org-todo-keywords-1)
12926 (push a org-todo-log-states)))))))
12928 (defun org-get-todo-sequence-head (kwd)
12929 "Return the head of the TODO sequence to which KWD belongs.
12930 If KWD is not set, check if there is a text property remembering the
12931 right sequence."
12932 (let (p)
12933 (cond
12934 ((not kwd)
12935 (or (get-text-property (point-at-bol) 'org-todo-head)
12936 (progn
12937 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12938 nil (point-at-eol)))
12939 (get-text-property p 'org-todo-head))))
12940 ((not (member kwd org-todo-keywords-1))
12941 (car org-todo-keywords-1))
12942 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12944 (defun org-fast-todo-selection ()
12945 "Fast TODO keyword selection with single keys.
12946 Returns the new TODO keyword, or nil if no state change should occur."
12947 (let* ((fulltable org-todo-key-alist)
12948 (done-keywords org-done-keywords) ;; needed for the faces.
12949 (maxlen (apply 'max (mapcar
12950 (lambda (x)
12951 (if (stringp (car x)) (string-width (car x)) 0))
12952 fulltable)))
12953 (expert nil)
12954 (fwidth (+ maxlen 3 1 3))
12955 (ncol (/ (- (window-width) 4) fwidth))
12956 tg cnt e c tbl
12957 groups ingroup)
12958 (save-excursion
12959 (save-window-excursion
12960 (if expert
12961 (set-buffer (get-buffer-create " *Org todo*"))
12962 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12963 (erase-buffer)
12964 (org-set-local 'org-done-keywords done-keywords)
12965 (setq tbl fulltable cnt 0)
12966 (while (setq e (pop tbl))
12967 (cond
12968 ((equal e '(:startgroup))
12969 (push '() groups) (setq ingroup t)
12970 (when (not (= cnt 0))
12971 (setq cnt 0)
12972 (insert "\n"))
12973 (insert "{ "))
12974 ((equal e '(:endgroup))
12975 (setq ingroup nil cnt 0)
12976 (insert "}\n"))
12977 ((equal e '(:newline))
12978 (when (not (= cnt 0))
12979 (setq cnt 0)
12980 (insert "\n")
12981 (setq e (car tbl))
12982 (while (equal (car tbl) '(:newline))
12983 (insert "\n")
12984 (setq tbl (cdr tbl)))))
12986 (setq tg (car e) c (cdr e))
12987 (if ingroup (push tg (car groups)))
12988 (setq tg (org-add-props tg nil 'face
12989 (org-get-todo-face tg)))
12990 (if (and (= cnt 0) (not ingroup)) (insert " "))
12991 (insert "[" c "] " tg (make-string
12992 (- fwidth 4 (length tg)) ?\ ))
12993 (when (= (setq cnt (1+ cnt)) ncol)
12994 (insert "\n")
12995 (if ingroup (insert " "))
12996 (setq cnt 0)))))
12997 (insert "\n")
12998 (goto-char (point-min))
12999 (if (not expert) (org-fit-window-to-buffer))
13000 (message "[a-z..]:Set [SPC]:clear")
13001 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13002 (cond
13003 ((or (= c ?\C-g)
13004 (and (= c ?q) (not (rassoc c fulltable))))
13005 (setq quit-flag t))
13006 ((= c ?\ ) nil)
13007 ((setq e (rassoc c fulltable) tg (car e))
13009 (t (setq quit-flag t)))))))
13011 (defun org-entry-is-todo-p ()
13012 (member (org-get-todo-state) org-not-done-keywords))
13014 (defun org-entry-is-done-p ()
13015 (member (org-get-todo-state) org-done-keywords))
13017 (defun org-get-todo-state ()
13018 "Return the TODO keyword of the current subtree."
13019 (save-excursion
13020 (org-back-to-heading t)
13021 (and (looking-at org-todo-line-regexp)
13022 (match-end 2)
13023 (match-string 2))))
13025 (defun org-at-date-range-p (&optional inactive-ok)
13026 "Is the cursor inside a date range?"
13027 (interactive)
13028 (save-excursion
13029 (catch 'exit
13030 (let ((pos (point)))
13031 (skip-chars-backward "^[<\r\n")
13032 (skip-chars-backward "<[")
13033 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13034 (>= (match-end 0) pos)
13035 (throw 'exit t))
13036 (skip-chars-backward "^<[\r\n")
13037 (skip-chars-backward "<[")
13038 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13039 (>= (match-end 0) pos)
13040 (throw 'exit t)))
13041 nil)))
13043 (defun org-get-repeat (&optional tagline)
13044 "Check if there is a deadline/schedule with repeater in this entry."
13045 (save-match-data
13046 (save-excursion
13047 (org-back-to-heading t)
13048 (and (re-search-forward (if tagline
13049 (concat tagline "\\s-*" org-repeat-re)
13050 org-repeat-re)
13051 (org-entry-end-position) t)
13052 (match-string-no-properties 1)))))
13054 (defvar org-last-changed-timestamp)
13055 (defvar org-last-inserted-timestamp)
13056 (defvar org-log-post-message)
13057 (defvar org-log-note-purpose)
13058 (defvar org-log-note-how)
13059 (defvar org-log-note-extra)
13060 (defun org-auto-repeat-maybe (done-word)
13061 "Check if the current headline contains a repeated deadline/schedule.
13062 If yes, set TODO state back to what it was and change the base date
13063 of repeating deadline/scheduled time stamps to new date.
13064 This function is run automatically after each state change to a DONE state."
13065 ;; last-state is dynamically scoped into this function
13066 (let* ((repeat (org-get-repeat))
13067 (aa (assoc org-last-state org-todo-kwd-alist))
13068 (interpret (nth 1 aa))
13069 (head (nth 2 aa))
13070 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13071 (msg "Entry repeats: ")
13072 (org-log-done nil)
13073 (org-todo-log-states nil)
13074 re type n what ts time to-state)
13075 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13076 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13077 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13078 org-todo-repeat-to-state))
13079 (unless (and to-state (member to-state org-todo-keywords-1))
13080 (setq to-state (if (eq interpret 'type) org-last-state head)))
13081 (org-todo to-state)
13082 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13083 (org-entry-put nil "LAST_REPEAT" (format-time-string
13084 (org-time-stamp-format t t))))
13085 (when org-log-repeat
13086 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13087 (memq 'org-add-log-note post-command-hook))
13088 ;; OK, we are already setup for some record
13089 (if (eq org-log-repeat 'note)
13090 ;; make sure we take a note, not only a time stamp
13091 (setq org-log-note-how 'note))
13092 ;; Set up for taking a record
13093 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13094 org-last-state
13095 'findpos org-log-repeat)))
13096 (org-back-to-heading t)
13097 (org-add-planning-info nil nil 'closed)
13098 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13099 org-deadline-time-regexp "\\)\\|\\("
13100 org-ts-regexp "\\)"))
13101 (while (re-search-forward
13102 re (save-excursion (outline-next-heading) (point)) t)
13103 (setq type (if (match-end 1) org-scheduled-string
13104 (if (match-end 3) org-deadline-string "Plain:"))
13105 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13106 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13107 (setq n (string-to-number (match-string 2 ts))
13108 what (match-string 3 ts))
13109 (if (equal what "w") (setq n (* n 7) what "d"))
13110 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13111 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13112 ;; Preparation, see if we need to modify the start date for the change
13113 (when (match-end 1)
13114 (setq time (save-match-data (org-time-string-to-time ts)))
13115 (cond
13116 ((equal (match-string 1 ts) ".")
13117 ;; Shift starting date to today
13118 (org-timestamp-change
13119 (- (org-today) (time-to-days time))
13120 'day))
13121 ((equal (match-string 1 ts) "+")
13122 (let ((nshiftmax 10) (nshift 0))
13123 (while (or (= nshift 0)
13124 (<= (time-to-days time)
13125 (time-to-days (current-time))))
13126 (when (= (incf nshift) nshiftmax)
13127 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13128 (user-error "Abort")))
13129 (org-timestamp-change n (cdr (assoc what whata)))
13130 (org-at-timestamp-p t)
13131 (setq ts (match-string 1))
13132 (setq time (save-match-data (org-time-string-to-time ts)))))
13133 (org-timestamp-change (- n) (cdr (assoc what whata)))
13134 ;; rematch, so that we have everything in place for the real shift
13135 (org-at-timestamp-p t)
13136 (setq ts (match-string 1))
13137 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13138 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13139 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13140 (setq org-log-post-message msg)
13141 (message "%s" msg))))
13143 (defun org-show-todo-tree (arg)
13144 "Make a compact tree which shows all headlines marked with TODO.
13145 The tree will show the lines where the regexp matches, and all higher
13146 headlines above the match.
13147 With a \\[universal-argument] prefix, prompt for a regexp to match.
13148 With a numeric prefix N, construct a sparse tree for the Nth element
13149 of `org-todo-keywords-1'."
13150 (interactive "P")
13151 (let ((case-fold-search nil)
13152 (kwd-re
13153 (cond ((null arg) org-not-done-regexp)
13154 ((equal arg '(4))
13155 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13156 (mapcar 'list org-todo-keywords-1))))
13157 (concat "\\("
13158 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13159 "\\)\\>")))
13160 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13161 (regexp-quote (nth (1- (prefix-numeric-value arg))
13162 org-todo-keywords-1)))
13163 (t (user-error "Invalid prefix argument: %s" arg)))))
13164 (message "%d TODO entries found"
13165 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13167 (defun org-deadline (arg &optional time)
13168 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13169 With one universal prefix argument, remove any deadline from the item.
13170 With two universal prefix arguments, prompt for a warning delay.
13171 With argument TIME, set the deadline at the corresponding date. TIME
13172 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13173 (interactive "P")
13174 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13175 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13176 'region-start-level 'region))
13177 org-loop-over-headlines-in-active-region)
13178 (org-map-entries
13179 `(org-deadline ',arg ,time)
13180 org-loop-over-headlines-in-active-region
13181 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13182 (let* ((old-date (org-entry-get nil "DEADLINE"))
13183 (old-date-time (if old-date (org-time-string-to-time old-date)))
13184 (repeater (and old-date
13185 (string-match
13186 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13187 old-date)
13188 (match-string 1 old-date))))
13189 (cond
13190 ((equal arg '(4))
13191 (when (and old-date org-log-redeadline)
13192 (org-add-log-setup 'deldeadline nil old-date 'findpos
13193 org-log-redeadline))
13194 (org-remove-timestamp-with-keyword org-deadline-string)
13195 (message "Item no longer has a deadline."))
13196 ((equal arg '(16))
13197 (save-excursion
13198 (org-back-to-heading t)
13199 (if (re-search-forward
13200 org-deadline-time-regexp
13201 (save-excursion (outline-next-heading) (point)) t)
13202 (let* ((rpl0 (match-string 1))
13203 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13204 (replace-match
13205 (concat org-deadline-string
13206 " <" rpl
13207 (format " -%dd"
13208 (abs
13209 (- (time-to-days
13210 (save-match-data
13211 (org-read-date nil t nil "Warn starting from" old-date-time)))
13212 (time-to-days old-date-time))))
13213 ">") t t))
13214 (user-error "No deadline information to update"))))
13216 (org-add-planning-info 'deadline time 'closed)
13217 (when (and old-date org-log-redeadline
13218 (not (equal old-date
13219 (substring org-last-inserted-timestamp 1 -1))))
13220 (org-add-log-setup 'redeadline nil old-date 'findpos
13221 org-log-redeadline))
13222 (when repeater
13223 (save-excursion
13224 (org-back-to-heading t)
13225 (when (re-search-forward (concat org-deadline-string " "
13226 org-last-inserted-timestamp)
13227 (save-excursion
13228 (outline-next-heading) (point)) t)
13229 (goto-char (1- (match-end 0)))
13230 (insert " " repeater)
13231 (setq org-last-inserted-timestamp
13232 (concat (substring org-last-inserted-timestamp 0 -1)
13233 " " repeater
13234 (substring org-last-inserted-timestamp -1))))))
13235 (message "Deadline on %s" org-last-inserted-timestamp))))))
13237 (defun org-schedule (arg &optional time)
13238 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13239 With one universal prefix argument, remove any scheduling date from the item.
13240 With two universal prefix arguments, prompt for a delay cookie.
13241 With argument TIME, scheduled at the corresponding date. TIME can
13242 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13243 (interactive "P")
13244 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13245 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13246 'region-start-level 'region))
13247 org-loop-over-headlines-in-active-region)
13248 (org-map-entries
13249 `(org-schedule ',arg ,time)
13250 org-loop-over-headlines-in-active-region
13251 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13252 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13253 (old-date-time (if old-date (org-time-string-to-time old-date)))
13254 (repeater (and old-date
13255 (string-match
13256 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13257 old-date)
13258 (match-string 1 old-date))))
13259 (cond
13260 ((equal arg '(4))
13261 (progn
13262 (when (and old-date org-log-reschedule)
13263 (org-add-log-setup 'delschedule nil old-date 'findpos
13264 org-log-reschedule))
13265 (org-remove-timestamp-with-keyword org-scheduled-string)
13266 (message "Item is no longer scheduled.")))
13267 ((equal arg '(16))
13268 (save-excursion
13269 (org-back-to-heading t)
13270 (if (re-search-forward
13271 org-scheduled-time-regexp
13272 (save-excursion (outline-next-heading) (point)) t)
13273 (let* ((rpl0 (match-string 1))
13274 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13275 (replace-match
13276 (concat org-scheduled-string
13277 " <" rpl
13278 (format " -%dd"
13279 (abs
13280 (- (time-to-days
13281 (save-match-data
13282 (org-read-date nil t nil "Delay until" old-date-time)))
13283 (time-to-days old-date-time))))
13284 ">") t t))
13285 (user-error "No scheduled information to update"))))
13287 (org-add-planning-info 'scheduled time 'closed)
13288 (when (and old-date org-log-reschedule
13289 (not (equal old-date
13290 (substring org-last-inserted-timestamp 1 -1))))
13291 (org-add-log-setup 'reschedule nil old-date 'findpos
13292 org-log-reschedule))
13293 (when repeater
13294 (save-excursion
13295 (org-back-to-heading t)
13296 (when (re-search-forward (concat org-scheduled-string " "
13297 org-last-inserted-timestamp)
13298 (save-excursion
13299 (outline-next-heading) (point)) t)
13300 (goto-char (1- (match-end 0)))
13301 (insert " " repeater)
13302 (setq org-last-inserted-timestamp
13303 (concat (substring org-last-inserted-timestamp 0 -1)
13304 " " repeater
13305 (substring org-last-inserted-timestamp -1))))))
13306 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13308 (defun org-get-scheduled-time (pom &optional inherit)
13309 "Get the scheduled time as a time tuple, of a format suitable
13310 for calling org-schedule with, or if there is no scheduling,
13311 returns nil."
13312 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13313 (when time
13314 (apply 'encode-time (org-parse-time-string time)))))
13316 (defun org-get-deadline-time (pom &optional inherit)
13317 "Get the deadline as a time tuple, of a format suitable for
13318 calling org-deadline with, or if there is no scheduling, returns
13319 nil."
13320 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13321 (when time
13322 (apply 'encode-time (org-parse-time-string time)))))
13324 (defun org-remove-timestamp-with-keyword (keyword)
13325 "Remove all time stamps with KEYWORD in the current entry."
13326 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13327 beg)
13328 (save-excursion
13329 (org-back-to-heading t)
13330 (setq beg (point))
13331 (outline-next-heading)
13332 (while (re-search-backward re beg t)
13333 (replace-match "")
13334 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13335 (equal (char-before) ?\ ))
13336 (backward-delete-char 1)
13337 (if (string-match "^[ \t]*$" (buffer-substring
13338 (point-at-bol) (point-at-eol)))
13339 (delete-region (point-at-bol)
13340 (min (point-max) (1+ (point-at-eol))))))))))
13342 (defvar org-time-was-given) ; dynamically scoped parameter
13343 (defvar org-end-time-was-given) ; dynamically scoped parameter
13345 (defun org-add-planning-info (what &optional time &rest remove)
13346 "Insert new timestamp with keyword in the line directly after the headline.
13347 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13348 If non is given, the user is prompted for a date.
13349 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13350 be removed."
13351 (interactive)
13352 (let (org-time-was-given org-end-time-was-given ts
13353 end default-time default-input)
13355 (catch 'exit
13356 (when (and (memq what '(scheduled deadline))
13357 (or (not time)
13358 (and (stringp time)
13359 (string-match "^[-+]+[0-9]" time))))
13360 ;; Try to get a default date/time from existing timestamp
13361 (save-excursion
13362 (org-back-to-heading t)
13363 (setq end (save-excursion (outline-next-heading) (point)))
13364 (when (re-search-forward (if (eq what 'scheduled)
13365 org-scheduled-time-regexp
13366 org-deadline-time-regexp)
13367 end t)
13368 (setq ts (match-string 1)
13369 default-time
13370 (apply 'encode-time (org-parse-time-string ts))
13371 default-input (and ts (org-get-compact-tod ts))))))
13372 (when what
13373 (setq time
13374 (if (stringp time)
13375 ;; This is a string (relative or absolute), set proper date
13376 (apply 'encode-time
13377 (org-read-date-analyze
13378 time default-time (decode-time default-time)))
13379 ;; If necessary, get the time from the user
13380 (or time (org-read-date nil 'to-time nil nil
13381 default-time default-input)))))
13383 (when (and org-insert-labeled-timestamps-at-point
13384 (member what '(scheduled deadline)))
13385 (insert
13386 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13387 (org-insert-time-stamp time org-time-was-given
13388 nil nil nil (list org-end-time-was-given))
13389 (setq what nil))
13390 (save-excursion
13391 (save-restriction
13392 (let (col list elt ts buffer-invisibility-spec)
13393 (org-back-to-heading t)
13394 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13395 (goto-char (match-end 1))
13396 (setq col (current-column))
13397 (goto-char (match-end 0))
13398 (if (eobp) (insert "\n") (forward-char 1))
13399 (when (and (not what)
13400 (not (looking-at
13401 (concat "[ \t]*"
13402 org-keyword-time-not-clock-regexp))))
13403 ;; Nothing to add, nothing to remove...... :-)
13404 (throw 'exit nil))
13405 (if (and (not (looking-at org-outline-regexp))
13406 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13407 "[^\r\n]*"))
13408 (not (equal (match-string 1) org-clock-string)))
13409 (narrow-to-region (match-beginning 0) (match-end 0))
13410 (insert-before-markers "\n")
13411 (backward-char 1)
13412 (narrow-to-region (point) (point))
13413 (and org-adapt-indentation (org-indent-to-column col)))
13414 ;; Check if we have to remove something.
13415 (setq list (cons what remove))
13416 (while list
13417 (setq elt (pop list))
13418 (when (or (and (eq elt 'scheduled)
13419 (re-search-forward org-scheduled-time-regexp nil t))
13420 (and (eq elt 'deadline)
13421 (re-search-forward org-deadline-time-regexp nil t))
13422 (and (eq elt 'closed)
13423 (re-search-forward org-closed-time-regexp nil t)))
13424 (replace-match "")
13425 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13426 (and (looking-at "[ \t]+") (replace-match ""))
13427 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13428 (when what
13429 (insert
13430 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13431 (cond ((eq what 'scheduled) org-scheduled-string)
13432 ((eq what 'deadline) org-deadline-string)
13433 ((eq what 'closed) org-closed-string))
13434 " ")
13435 (setq ts (org-insert-time-stamp
13436 time
13437 (or org-time-was-given
13438 (and (eq what 'closed) org-log-done-with-time))
13439 (eq what 'closed)
13440 nil nil (list org-end-time-was-given)))
13441 (insert
13442 (if (not (or (bolp) (eq (char-before) ?\ )
13443 (memq (char-after) '(32 10))
13444 (eobp))) " " ""))
13445 (end-of-line 1))
13446 (goto-char (point-min))
13447 (widen)
13448 (if (and (looking-at "[ \t]*\n")
13449 (equal (char-before) ?\n))
13450 (delete-region (1- (point)) (point-at-eol)))
13451 ts))))))
13453 (defvar org-log-note-marker (make-marker))
13454 (defvar org-log-note-purpose nil)
13455 (defvar org-log-note-state nil)
13456 (defvar org-log-note-previous-state nil)
13457 (defvar org-log-note-how nil)
13458 (defvar org-log-note-extra nil)
13459 (defvar org-log-note-window-configuration nil)
13460 (defvar org-log-note-return-to (make-marker))
13461 (defvar org-log-note-effective-time nil
13462 "Remembered current time so that dynamically scoped
13463 `org-extend-today-until' affects tha timestamps in state change
13464 log")
13466 (defvar org-log-post-message nil
13467 "Message to be displayed after a log note has been stored.
13468 The auto-repeater uses this.")
13470 (defun org-add-note ()
13471 "Add a note to the current entry.
13472 This is done in the same way as adding a state change note."
13473 (interactive)
13474 (org-add-log-setup 'note nil nil 'findpos nil))
13476 (defvar org-property-end-re)
13477 (defun org-add-log-setup (&optional purpose state prev-state
13478 findpos how extra)
13479 "Set up the post command hook to take a note.
13480 If this is about to TODO state change, the new state is expected in STATE.
13481 When FINDPOS is non-nil, find the correct position for the note in
13482 the current entry. If not, assume that it can be inserted at point.
13483 HOW is an indicator what kind of note should be created.
13484 EXTRA is additional text that will be inserted into the notes buffer."
13485 (let* ((org-log-into-drawer (org-log-into-drawer))
13486 (drawer (cond ((stringp org-log-into-drawer)
13487 org-log-into-drawer)
13488 (org-log-into-drawer "LOGBOOK"))))
13489 (save-restriction
13490 (save-excursion
13491 (when findpos
13492 (org-back-to-heading t)
13493 (narrow-to-region (point) (save-excursion
13494 (outline-next-heading) (point)))
13495 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13496 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13497 "[^\r\n]*\\)?"))
13498 (goto-char (match-end 0))
13499 (cond
13500 (drawer
13501 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13502 nil t)
13503 (progn
13504 (goto-char (match-end 0))
13505 (or org-log-states-order-reversed
13506 (and (re-search-forward org-property-end-re nil t)
13507 (goto-char (1- (match-beginning 0))))))
13508 (insert "\n:" drawer ":\n:END:")
13509 (beginning-of-line 0)
13510 (org-indent-line)
13511 (beginning-of-line 2)
13512 (org-indent-line)
13513 (end-of-line 0)))
13514 ((and org-log-state-notes-insert-after-drawers
13515 (save-excursion
13516 (forward-line) (looking-at org-drawer-regexp)))
13517 (forward-line)
13518 (while (looking-at org-drawer-regexp)
13519 (goto-char (match-end 0))
13520 (re-search-forward org-property-end-re (point-max) t)
13521 (forward-line))
13522 (forward-line -1)))
13523 (unless org-log-states-order-reversed
13524 (and (= (char-after) ?\n) (forward-char 1))
13525 (org-skip-over-state-notes)
13526 (skip-chars-backward " \t\n\r")))
13527 (move-marker org-log-note-marker (point))
13528 (setq org-log-note-purpose purpose
13529 org-log-note-state state
13530 org-log-note-previous-state prev-state
13531 org-log-note-how how
13532 org-log-note-extra extra
13533 org-log-note-effective-time (org-current-effective-time))
13534 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13536 (defun org-skip-over-state-notes ()
13537 "Skip past the list of State notes in an entry."
13538 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13539 (when (ignore-errors (goto-char (org-in-item-p)))
13540 (let* ((struct (org-list-struct))
13541 (prevs (org-list-prevs-alist struct)))
13542 (while (looking-at "[ \t]*- State")
13543 (goto-char (or (org-list-get-next-item (point) struct prevs)
13544 (org-list-get-item-end (point) struct)))))))
13546 (defun org-add-log-note (&optional purpose)
13547 "Pop up a window for taking a note, and add this note later at point."
13548 (remove-hook 'post-command-hook 'org-add-log-note)
13549 (setq org-log-note-window-configuration (current-window-configuration))
13550 (delete-other-windows)
13551 (move-marker org-log-note-return-to (point))
13552 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13553 (goto-char org-log-note-marker)
13554 (org-switch-to-buffer-other-window "*Org Note*")
13555 (erase-buffer)
13556 (if (memq org-log-note-how '(time state))
13557 (let (current-prefix-arg) (org-store-log-note))
13558 (let ((org-inhibit-startup t)) (org-mode))
13559 (insert (format "# Insert note for %s.
13560 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13561 (cond
13562 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13563 ((eq org-log-note-purpose 'done) "closed todo item")
13564 ((eq org-log-note-purpose 'state)
13565 (format "state change from \"%s\" to \"%s\""
13566 (or org-log-note-previous-state "")
13567 (or org-log-note-state "")))
13568 ((eq org-log-note-purpose 'reschedule)
13569 "rescheduling")
13570 ((eq org-log-note-purpose 'delschedule)
13571 "no longer scheduled")
13572 ((eq org-log-note-purpose 'redeadline)
13573 "changing deadline")
13574 ((eq org-log-note-purpose 'deldeadline)
13575 "removing deadline")
13576 ((eq org-log-note-purpose 'refile)
13577 "refiling")
13578 ((eq org-log-note-purpose 'note)
13579 "this entry")
13580 (t (error "This should not happen")))))
13581 (if org-log-note-extra (insert org-log-note-extra))
13582 (org-set-local 'org-finish-function 'org-store-log-note)
13583 (run-hooks 'org-log-buffer-setup-hook)))
13585 (defvar org-note-abort nil) ; dynamically scoped
13586 (defun org-store-log-note ()
13587 "Finish taking a log note, and insert it to where it belongs."
13588 (let ((txt (buffer-string)))
13589 (kill-buffer (current-buffer))
13590 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13591 lines ind bul)
13592 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13593 (setq txt (replace-match "" t t txt)))
13594 (if (string-match "\\s-+\\'" txt)
13595 (setq txt (replace-match "" t t txt)))
13596 (setq lines (org-split-string txt "\n"))
13597 (when (and note (string-match "\\S-" note))
13598 (setq note
13599 (org-replace-escapes
13600 note
13601 (list (cons "%u" (user-login-name))
13602 (cons "%U" user-full-name)
13603 (cons "%t" (format-time-string
13604 (org-time-stamp-format 'long 'inactive)
13605 org-log-note-effective-time))
13606 (cons "%T" (format-time-string
13607 (org-time-stamp-format 'long nil)
13608 org-log-note-effective-time))
13609 (cons "%d" (format-time-string
13610 (org-time-stamp-format nil 'inactive)
13611 org-log-note-effective-time))
13612 (cons "%D" (format-time-string
13613 (org-time-stamp-format nil nil)
13614 org-log-note-effective-time))
13615 (cons "%s" (if org-log-note-state
13616 (concat "\"" org-log-note-state "\"")
13617 ""))
13618 (cons "%S" (if org-log-note-previous-state
13619 (concat "\"" org-log-note-previous-state "\"")
13620 "\"\"")))))
13621 (if lines (setq note (concat note " \\\\")))
13622 (push note lines))
13623 (when (or current-prefix-arg org-note-abort)
13624 (when org-log-into-drawer
13625 (org-remove-empty-drawer-at org-log-note-marker))
13626 (setq lines nil))
13627 (when lines
13628 (with-current-buffer (marker-buffer org-log-note-marker)
13629 (save-excursion
13630 (goto-char org-log-note-marker)
13631 (move-marker org-log-note-marker nil)
13632 (end-of-line 1)
13633 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13634 (setq ind (save-excursion
13635 (if (ignore-errors (goto-char (org-in-item-p)))
13636 (let ((struct (org-list-struct)))
13637 (org-list-get-ind
13638 (org-list-get-top-point struct) struct))
13639 (skip-chars-backward " \r\t\n")
13640 (cond
13641 ((and (org-at-heading-p)
13642 org-adapt-indentation)
13643 (1+ (org-current-level)))
13644 ((org-at-heading-p) 0)
13645 (t (org-get-indentation))))))
13646 (setq bul (org-list-bullet-string "-"))
13647 (org-indent-line-to ind)
13648 (insert bul (pop lines))
13649 (let ((ind-body (+ (length bul) ind)))
13650 (while lines
13651 (insert "\n")
13652 (org-indent-line-to ind-body)
13653 (insert (pop lines))))
13654 (message "Note stored")
13655 (org-back-to-heading t)
13656 (org-cycle-hide-drawers 'children))
13657 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13658 ;; from within `org-add-log-note' because `buffer-undo-list'
13659 ;; is then modified outside of `org-with-remote-undo'.
13660 (when (eq this-command 'org-agenda-todo)
13661 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13662 ;; Don't add undo information when called from `org-agenda-todo'
13663 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13664 (set-window-configuration org-log-note-window-configuration)
13665 (with-current-buffer (marker-buffer org-log-note-return-to)
13666 (goto-char org-log-note-return-to))
13667 (move-marker org-log-note-return-to nil)
13668 (and org-log-post-message (message "%s" org-log-post-message))))
13670 (defun org-remove-empty-drawer-at (pos)
13671 "Remove an empty drawer at position POS.
13672 POS may also be a marker."
13673 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13674 (org-with-wide-buffer
13675 (goto-char pos)
13676 (let ((drawer (org-element-at-point)))
13677 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13678 (not (org-element-property :contents-begin drawer)))
13679 (delete-region (org-element-property :begin drawer)
13680 (progn (goto-char (org-element-property :end drawer))
13681 (skip-chars-backward " \r\t\n")
13682 (forward-line)
13683 (point))))))))
13685 (defvar org-ts-type nil)
13686 (defun org-sparse-tree (&optional arg type)
13687 "Create a sparse tree, prompt for the details.
13688 This command can create sparse trees. You first need to select the type
13689 of match used to create the tree:
13691 t Show all TODO entries.
13692 T Show entries with a specific TODO keyword.
13693 m Show entries selected by a tags/property match.
13694 p Enter a property name and its value (both with completion on existing
13695 names/values) and show entries with that property.
13696 r Show entries matching a regular expression (`/' can be used as well).
13697 b Show deadlines and scheduled items before a date.
13698 a Show deadlines and scheduled items after a date.
13699 d Show deadlines due within `org-deadline-warning-days'.
13700 D Show deadlines and scheduled items between a date range."
13701 (interactive "P")
13702 (setq type (or type org-sparse-tree-default-date-type))
13703 (setq org-ts-type type)
13704 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13705 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13706 [c]ycle through date types: %s"
13707 (case type
13708 (all "all timestamps")
13709 (scheduled "only scheduled")
13710 (deadline "only deadline")
13711 (active "only active timestamps")
13712 (inactive "only inactive timestamps")
13713 (scheduled-or-deadline "scheduled/deadline")
13714 (closed "with a closed time-stamp")
13715 (otherwise "scheduled/deadline")))
13716 (let ((answer (read-char-exclusive)))
13717 (case answer
13719 (org-sparse-tree
13721 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13722 inactive closed)))))
13723 (?d (call-interactively #'org-check-deadlines))
13724 (?b (call-interactively #'org-check-before-date))
13725 (?a (call-interactively #'org-check-after-date))
13726 (?D (call-interactively #'org-check-dates-range))
13727 (?t (call-interactively #'org-show-todo-tree))
13728 (?T (org-show-todo-tree '(4)))
13729 (?m (call-interactively #'org-match-sparse-tree))
13730 ((?p ?P)
13731 (let* ((kwd (org-icompleting-read
13732 "Property: " (mapcar #'list (org-buffer-property-keys))))
13733 (value (org-icompleting-read
13734 "Value: " (mapcar #'list (org-property-values kwd)))))
13735 (unless (string-match "\\`{.*}\\'" value)
13736 (setq value (concat "\"" value "\"")))
13737 (org-match-sparse-tree arg (concat kwd "=" value))))
13738 ((?r ?R ?/) (call-interactively #'org-occur))
13739 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13741 (defvar org-occur-highlights nil
13742 "List of overlays used for occur matches.")
13743 (make-variable-buffer-local 'org-occur-highlights)
13744 (defvar org-occur-parameters nil
13745 "Parameters of the active org-occur calls.
13746 This is a list, each call to org-occur pushes as cons cell,
13747 containing the regular expression and the callback, onto the list.
13748 The list can contain several entries if `org-occur' has been called
13749 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13750 will only contain one set of parameters. When the highlights are
13751 removed (for example with `C-c C-c', or with the next edit (depending
13752 on `org-remove-highlights-with-change'), this variable is emptied
13753 as well.")
13754 (make-variable-buffer-local 'org-occur-parameters)
13756 (defun org-occur (regexp &optional keep-previous callback)
13757 "Make a compact tree which shows all matches of REGEXP.
13758 The tree will show the lines where the regexp matches, and all higher
13759 headlines above the match. It will also show the heading after the match,
13760 to make sure editing the matching entry is easy.
13761 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13762 call to `org-occur' will be kept, to allow stacking of calls to this
13763 command.
13764 If CALLBACK is non-nil, it is a function which is called to confirm
13765 that the match should indeed be shown."
13766 (interactive "sRegexp: \nP")
13767 (when (equal regexp "")
13768 (user-error "Regexp cannot be empty"))
13769 (unless keep-previous
13770 (org-remove-occur-highlights nil nil t))
13771 (push (cons regexp callback) org-occur-parameters)
13772 (let ((cnt 0))
13773 (save-excursion
13774 (goto-char (point-min))
13775 (if (or (not keep-previous) ; do not want to keep
13776 (not org-occur-highlights)) ; no previous matches
13777 ;; hide everything
13778 (org-overview))
13779 (while (re-search-forward regexp nil t)
13780 (when (or (not callback)
13781 (save-match-data (funcall callback)))
13782 (setq cnt (1+ cnt))
13783 (when org-highlight-sparse-tree-matches
13784 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13785 (org-show-context 'occur-tree))))
13786 (when org-remove-highlights-with-change
13787 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13788 nil 'local))
13789 (unless org-sparse-tree-open-archived-trees
13790 (org-hide-archived-subtrees (point-min) (point-max)))
13791 (run-hooks 'org-occur-hook)
13792 (if (org-called-interactively-p 'interactive)
13793 (message "%d match(es) for regexp %s" cnt regexp))
13794 cnt))
13796 (defun org-occur-next-match (&optional n reset)
13797 "Function for `next-error-function' to find sparse tree matches.
13798 N is the number of matches to move, when negative move backwards.
13799 RESET is entirely ignored - this function always goes back to the
13800 starting point when no match is found."
13801 (let* ((limit (if (< n 0) (point-min) (point-max)))
13802 (search-func (if (< n 0)
13803 'previous-single-char-property-change
13804 'next-single-char-property-change))
13805 (n (abs n))
13806 (pos (point))
13808 (catch 'exit
13809 (while (setq p1 (funcall search-func (point) 'org-type))
13810 (when (equal p1 limit)
13811 (goto-char pos)
13812 (user-error "No more matches"))
13813 (when (equal (get-char-property p1 'org-type) 'org-occur)
13814 (setq n (1- n))
13815 (when (= n 0)
13816 (goto-char p1)
13817 (throw 'exit (point))))
13818 (goto-char p1))
13819 (goto-char p1)
13820 (user-error "No more matches"))))
13822 (defun org-show-context (&optional key)
13823 "Make sure point and context are visible.
13824 How much context is shown depends upon the variables
13825 `org-show-hierarchy-above', `org-show-following-heading',
13826 `org-show-entry-below' and `org-show-siblings'."
13827 (let ((heading-p (org-at-heading-p t))
13828 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13829 (following-p (org-get-alist-option org-show-following-heading key))
13830 (entry-p (org-get-alist-option org-show-entry-below key))
13831 (siblings-p (org-get-alist-option org-show-siblings key)))
13832 ;; Show heading or entry text
13833 (if (and heading-p (not entry-p))
13834 (org-flag-heading nil) ; only show the heading
13835 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13836 (org-show-hidden-entry))) ; show entire entry
13837 (when following-p
13838 ;; Show next sibling, or heading below text
13839 (save-excursion
13840 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13841 (org-flag-heading nil))))
13842 (when siblings-p (org-show-siblings))
13843 (when hierarchy-p
13844 ;; show all higher headings, possibly with siblings
13845 (save-excursion
13846 (while (and (condition-case nil
13847 (progn (org-up-heading-all 1) t)
13848 (error nil))
13849 (not (bobp)))
13850 (org-flag-heading nil)
13851 (when siblings-p (org-show-siblings)))))
13852 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13854 (defvar org-reveal-start-hook nil
13855 "Hook run before revealing a location.")
13857 (defun org-reveal (&optional siblings)
13858 "Show current entry, hierarchy above it, and the following headline.
13859 This can be used to show a consistent set of context around locations
13860 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13861 not t for the search context.
13863 With optional argument SIBLINGS, on each level of the hierarchy all
13864 siblings are shown. This repairs the tree structure to what it would
13865 look like when opened with hierarchical calls to `org-cycle'.
13866 With double optional argument \\[universal-argument] \\[universal-argument], \
13867 go to the parent and show the
13868 entire tree."
13869 (interactive "P")
13870 (run-hooks 'org-reveal-start-hook)
13871 (let ((org-show-hierarchy-above t)
13872 (org-show-following-heading t)
13873 (org-show-siblings (if siblings t org-show-siblings)))
13874 (org-show-context nil))
13875 (when (equal siblings '(16))
13876 (save-excursion
13877 (when (org-up-heading-safe)
13878 (org-show-subtree)
13879 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13881 (defun org-highlight-new-match (beg end)
13882 "Highlight from BEG to END and mark the highlight is an occur headline."
13883 (let ((ov (make-overlay beg end)))
13884 (overlay-put ov 'face 'secondary-selection)
13885 (overlay-put ov 'org-type 'org-occur)
13886 (push ov org-occur-highlights)))
13888 (defun org-remove-occur-highlights (&optional beg end noremove)
13889 "Remove the occur highlights from the buffer.
13890 BEG and END are ignored. If NOREMOVE is nil, remove this function
13891 from the `before-change-functions' in the current buffer."
13892 (interactive)
13893 (unless org-inhibit-highlight-removal
13894 (mapc 'delete-overlay org-occur-highlights)
13895 (setq org-occur-highlights nil)
13896 (setq org-occur-parameters nil)
13897 (unless noremove
13898 (remove-hook 'before-change-functions
13899 'org-remove-occur-highlights 'local))))
13901 ;;;; Priorities
13903 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13904 "Regular expression matching the priority indicator.")
13906 (defvar org-remove-priority-next-time nil)
13908 (defun org-priority-up ()
13909 "Increase the priority of the current item."
13910 (interactive)
13911 (org-priority 'up))
13913 (defun org-priority-down ()
13914 "Decrease the priority of the current item."
13915 (interactive)
13916 (org-priority 'down))
13918 (defun org-priority (&optional action show)
13919 "Change the priority of an item.
13920 ACTION can be `set', `up', `down', or a character."
13921 (interactive "P")
13922 (if (equal action '(4))
13923 (org-show-priority)
13924 (unless org-enable-priority-commands
13925 (user-error "Priority commands are disabled"))
13926 (setq action (or action 'set))
13927 (let (current new news have remove)
13928 (save-excursion
13929 (org-back-to-heading t)
13930 (if (looking-at org-priority-regexp)
13931 (setq current (string-to-char (match-string 2))
13932 have t))
13933 (cond
13934 ((eq action 'remove)
13935 (setq remove t new ?\ ))
13936 ((or (eq action 'set)
13937 (if (featurep 'xemacs) (characterp action) (integerp action)))
13938 (if (not (eq action 'set))
13939 (setq new action)
13940 (message "Priority %c-%c, SPC to remove: "
13941 org-highest-priority org-lowest-priority)
13942 (save-match-data
13943 (setq new (read-char-exclusive))))
13944 (if (and (= (upcase org-highest-priority) org-highest-priority)
13945 (= (upcase org-lowest-priority) org-lowest-priority))
13946 (setq new (upcase new)))
13947 (cond ((equal new ?\ ) (setq remove t))
13948 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13949 (user-error "Priority must be between `%c' and `%c'"
13950 org-highest-priority org-lowest-priority))))
13951 ((eq action 'up)
13952 (setq new (if have
13953 (1- current) ; normal cycling
13954 ;; last priority was empty
13955 (if (eq last-command this-command)
13956 org-lowest-priority ; wrap around empty to lowest
13957 ;; default
13958 (if org-priority-start-cycle-with-default
13959 org-default-priority
13960 (1- org-default-priority))))))
13961 ((eq action 'down)
13962 (setq new (if have
13963 (1+ current) ; normal cycling
13964 ;; last priority was empty
13965 (if (eq last-command this-command)
13966 org-highest-priority ; wrap around empty to highest
13967 ;; default
13968 (if org-priority-start-cycle-with-default
13969 org-default-priority
13970 (1+ org-default-priority))))))
13971 (t (user-error "Invalid action")))
13972 (if (or (< (upcase new) org-highest-priority)
13973 (> (upcase new) org-lowest-priority))
13974 (if (and (memq action '(up down))
13975 (not have) (not (eq last-command this-command)))
13976 ;; `new' is from default priority
13977 (error
13978 "The default can not be set, see `org-default-priority' why")
13979 ;; normal cycling: `new' is beyond highest/lowest priority
13980 ;; and is wrapped around to the empty priority
13981 (setq remove t)))
13982 (setq news (format "%c" new))
13983 (if have
13984 (if remove
13985 (replace-match "" t t nil 1)
13986 (replace-match news t t nil 2))
13987 (if remove
13988 (user-error "No priority cookie found in line")
13989 (let ((case-fold-search nil))
13990 (looking-at org-todo-line-regexp))
13991 (if (match-end 2)
13992 (progn
13993 (goto-char (match-end 2))
13994 (insert " [#" news "]"))
13995 (goto-char (match-beginning 3))
13996 (insert "[#" news "] "))))
13997 (org-set-tags nil 'align))
13998 (if remove
13999 (message "Priority removed")
14000 (message "Priority of current item set to %s" news)))))
14002 (defun org-show-priority ()
14003 "Show the priority of the current item.
14004 This priority is composed of the main priority given with the [#A] cookies,
14005 and by additional input from the age of a schedules or deadline entry."
14006 (interactive)
14007 (let ((pri (if (eq major-mode 'org-agenda-mode)
14008 (org-get-at-bol 'priority)
14009 (save-excursion
14010 (save-match-data
14011 (beginning-of-line)
14012 (and (looking-at org-heading-regexp)
14013 (org-get-priority (match-string 0))))))))
14014 (message "Priority is %d" (if pri pri -1000))))
14016 (defun org-get-priority (s)
14017 "Find priority cookie and return priority."
14018 (save-match-data
14019 (if (functionp org-get-priority-function)
14020 (funcall org-get-priority-function)
14021 (if (not (string-match org-priority-regexp s))
14022 (* 1000 (- org-lowest-priority org-default-priority))
14023 (* 1000 (- org-lowest-priority
14024 (string-to-char (match-string 2 s))))))))
14026 ;;;; Tags
14028 (defvar org-agenda-archives-mode)
14029 (defvar org-map-continue-from nil
14030 "Position from where mapping should continue.
14031 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14033 (defvar org-scanner-tags nil
14034 "The current tag list while the tags scanner is running.")
14035 (defvar org-trust-scanner-tags nil
14036 "Should `org-get-tags-at' use the tags for the scanner.
14037 This is for internal dynamical scoping only.
14038 When this is non-nil, the function `org-get-tags-at' will return the value
14039 of `org-scanner-tags' instead of building the list by itself. This
14040 can lead to large speed-ups when the tags scanner is used in a file with
14041 many entries, and when the list of tags is retrieved, for example to
14042 obtain a list of properties. Building the tags list for each entry in such
14043 a file becomes an N^2 operation - but with this variable set, it scales
14044 as N.")
14046 (defun org-scan-tags (action matcher todo-only &optional start-level)
14047 "Sca headline tags with inheritance and produce output ACTION.
14049 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14050 or `agenda' to produce an entry list for an agenda view. It can also be
14051 a Lisp form or a function that should be called at each matched headline, in
14052 this case the return value is a list of all return values from these calls.
14054 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14055 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14056 only lines with a not-done TODO keyword are included in the output.
14057 This should be the same variable that was scoped into
14058 and set by `org-make-tags-matcher' when it constructed MATCHER.
14060 START-LEVEL can be a string with asterisks, reducing the scope to
14061 headlines matching this string."
14062 (require 'org-agenda)
14063 (let* ((re (concat "^"
14064 (if start-level
14065 ;; Get the correct level to match
14066 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14067 org-outline-regexp)
14068 " *\\(\\<\\("
14069 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14070 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14071 (props (list 'face 'default
14072 'done-face 'org-agenda-done
14073 'undone-face 'default
14074 'mouse-face 'highlight
14075 'org-not-done-regexp org-not-done-regexp
14076 'org-todo-regexp org-todo-regexp
14077 'org-complex-heading-regexp org-complex-heading-regexp
14078 'help-echo
14079 (format "mouse-2 or RET jump to org file %s"
14080 (abbreviate-file-name
14081 (or (buffer-file-name (buffer-base-buffer))
14082 (buffer-name (buffer-base-buffer)))))))
14083 (org-map-continue-from nil)
14084 lspos tags tags-list
14085 (tags-alist (list (cons 0 org-file-tags)))
14086 (llast 0) rtn rtn1 level category i txt
14087 todo marker entry priority)
14088 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14089 (setq action (list 'lambda nil action)))
14090 (save-excursion
14091 (goto-char (point-min))
14092 (when (eq action 'sparse-tree)
14093 (org-overview)
14094 (org-remove-occur-highlights))
14095 (while (let (case-fold-search)
14096 (re-search-forward re nil t))
14097 (setq org-map-continue-from nil)
14098 (catch :skip
14099 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14100 tags (if (match-end 4) (org-match-string-no-properties 4)))
14101 (goto-char (setq lspos (match-beginning 0)))
14102 (setq level (org-reduced-level (org-outline-level))
14103 category (org-get-category))
14104 (setq i llast llast level)
14105 ;; remove tag lists from same and sublevels
14106 (while (>= i level)
14107 (when (setq entry (assoc i tags-alist))
14108 (setq tags-alist (delete entry tags-alist)))
14109 (setq i (1- i)))
14110 ;; add the next tags
14111 (when tags
14112 (setq tags (org-split-string tags ":")
14113 tags-alist
14114 (cons (cons level tags) tags-alist)))
14115 ;; compile tags for current headline
14116 (setq tags-list
14117 (if org-use-tag-inheritance
14118 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14119 tags)
14120 org-scanner-tags tags-list)
14121 (when org-use-tag-inheritance
14122 (setcdr (car tags-alist)
14123 (mapcar (lambda (x)
14124 (setq x (copy-sequence x))
14125 (org-add-prop-inherited x))
14126 (cdar tags-alist))))
14127 (when (and tags org-use-tag-inheritance
14128 (or (not (eq t org-use-tag-inheritance))
14129 org-tags-exclude-from-inheritance))
14130 ;; selective inheritance, remove uninherited ones
14131 (setcdr (car tags-alist)
14132 (org-remove-uninherited-tags (cdar tags-alist))))
14133 (when (and
14135 ;; eval matcher only when the todo condition is OK
14136 (and (or (not todo-only) (member todo org-not-done-keywords))
14137 (let ((case-fold-search t) (org-trust-scanner-tags t))
14138 (eval matcher)))
14140 ;; Call the skipper, but return t if it does not skip,
14141 ;; so that the `and' form continues evaluating
14142 (progn
14143 (unless (eq action 'sparse-tree) (org-agenda-skip))
14146 ;; Check if timestamps are deselecting this entry
14147 (or (not todo-only)
14148 (and (member todo org-not-done-keywords)
14149 (or (not org-agenda-tags-todo-honor-ignore-options)
14150 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14152 ;; select this headline
14153 (cond
14154 ((eq action 'sparse-tree)
14155 (and org-highlight-sparse-tree-matches
14156 (org-get-heading) (match-end 0)
14157 (org-highlight-new-match
14158 (match-beginning 1) (match-end 1)))
14159 (org-show-context 'tags-tree))
14160 ((eq action 'agenda)
14161 (setq txt (org-agenda-format-item
14163 (concat
14164 (if (eq org-tags-match-list-sublevels 'indented)
14165 (make-string (1- level) ?.) "")
14166 (org-get-heading))
14167 level category
14168 tags-list)
14169 priority (org-get-priority txt))
14170 (goto-char lspos)
14171 (setq marker (org-agenda-new-marker))
14172 (org-add-props txt props
14173 'org-marker marker 'org-hd-marker marker 'org-category category
14174 'todo-state todo
14175 'priority priority 'type "tagsmatch")
14176 (push txt rtn))
14177 ((functionp action)
14178 (setq org-map-continue-from nil)
14179 (save-excursion
14180 (setq rtn1 (funcall action))
14181 (push rtn1 rtn)))
14182 (t (user-error "Invalid action")))
14184 ;; if we are to skip sublevels, jump to end of subtree
14185 (unless org-tags-match-list-sublevels
14186 (org-end-of-subtree t)
14187 (backward-char 1))))
14188 ;; Get the correct position from where to continue
14189 (if org-map-continue-from
14190 (goto-char org-map-continue-from)
14191 (and (= (point) lspos) (end-of-line 1)))))
14192 (when (and (eq action 'sparse-tree)
14193 (not org-sparse-tree-open-archived-trees))
14194 (org-hide-archived-subtrees (point-min) (point-max)))
14195 (nreverse rtn)))
14197 (defun org-remove-uninherited-tags (tags)
14198 "Remove all tags that are not inherited from the list TAGS."
14199 (cond
14200 ((eq org-use-tag-inheritance t)
14201 (if org-tags-exclude-from-inheritance
14202 (org-delete-all org-tags-exclude-from-inheritance tags)
14203 tags))
14204 ((not org-use-tag-inheritance) nil)
14205 ((stringp org-use-tag-inheritance)
14206 (delq nil (mapcar
14207 (lambda (x)
14208 (if (and (string-match org-use-tag-inheritance x)
14209 (not (member x org-tags-exclude-from-inheritance)))
14210 x nil))
14211 tags)))
14212 ((listp org-use-tag-inheritance)
14213 (delq nil (mapcar
14214 (lambda (x)
14215 (if (member x org-use-tag-inheritance) x nil))
14216 tags)))))
14218 (defun org-match-sparse-tree (&optional todo-only match)
14219 "Create a sparse tree according to tags string MATCH.
14220 MATCH can contain positive and negative selection of tags, like
14221 \"+WORK+URGENT-WITHBOSS\".
14222 If optional argument TODO-ONLY is non-nil, only select lines that are
14223 also TODO lines."
14224 (interactive "P")
14225 (org-agenda-prepare-buffers (list (current-buffer)))
14226 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14228 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14230 (defvar org-cached-props nil)
14231 (defun org-cached-entry-get (pom property)
14232 (if (or (eq t org-use-property-inheritance)
14233 (and (stringp org-use-property-inheritance)
14234 (string-match org-use-property-inheritance property))
14235 (and (listp org-use-property-inheritance)
14236 (member property org-use-property-inheritance)))
14237 ;; Caching is not possible, check it directly
14238 (org-entry-get pom property 'inherit)
14239 ;; Get all properties, so that we can do complicated checks easily
14240 (cdr (assoc property (or org-cached-props
14241 (setq org-cached-props
14242 (org-entry-properties pom)))))))
14244 (defun org-global-tags-completion-table (&optional files)
14245 "Return the list of all tags in all agenda buffer/files.
14246 Optional FILES argument is a list of files which can be used
14247 instead of the agenda files."
14248 (save-excursion
14249 (org-uniquify
14250 (delq nil
14251 (apply 'append
14252 (mapcar
14253 (lambda (file)
14254 (set-buffer (find-file-noselect file))
14255 (append (org-get-buffer-tags)
14256 (mapcar (lambda (x) (if (stringp (car-safe x))
14257 (list (car-safe x)) nil))
14258 org-tag-alist)))
14259 (if (and files (car files))
14260 files
14261 (org-agenda-files))))))))
14263 (defun org-make-tags-matcher (match)
14264 "Create the TAGS/TODO matcher form for the selection string MATCH.
14266 The variable `todo-only' is scoped dynamically into this function.
14267 It will be set to t if the matcher restricts matching to TODO entries,
14268 otherwise will not be touched.
14270 Returns a cons of the selection string MATCH and the constructed
14271 lisp form implementing the matcher. The matcher is to be evaluated
14272 at an Org entry, with point on the headline, and returns t if the
14273 entry matches the selection string MATCH. The returned lisp form
14274 references two variables with information about the entry, which
14275 must be bound around the form's evaluation: todo, the TODO keyword
14276 at the entry (or nil of none); and tags-list, the list of all tags
14277 at the entry including inherited ones. Additionally, the category
14278 of the entry (if any) must be specified as the text property
14279 'org-category on the headline.
14281 See also `org-scan-tags'.
14283 (declare (special todo-only))
14284 (unless (boundp 'todo-only)
14285 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14286 (unless match
14287 ;; Get a new match request, with completion against the global
14288 ;; tags table and the local tags in current buffer
14289 (let ((org-last-tags-completion-table
14290 (org-uniquify
14291 (delq nil (append (org-get-buffer-tags)
14292 (org-global-tags-completion-table))))))
14293 (setq match (org-completing-read-no-i
14294 "Match: " 'org-tags-completion-function nil nil nil
14295 'org-tags-history))))
14297 ;; Parse the string and create a lisp form
14298 (let ((match0 match)
14299 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14300 minus tag mm
14301 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14302 orterms term orlist re-p str-p level-p level-op time-p
14303 prop-p pn pv po gv rest (start 0) (ss 0))
14304 ;; Expand group tags
14305 (setq match (org-tags-expand match))
14307 ;; Check if there is a TODO part of this match, which would be the
14308 ;; part after a "/". TO make sure that this slash is not part of
14309 ;; a property value to be matched against, we also check that there
14310 ;; is no " after that slash.
14311 ;; First, find the last slash
14312 (while (string-match "/+" match ss)
14313 (setq start (match-beginning 0) ss (match-end 0)))
14314 (if (and (string-match "/+" match start)
14315 (not (save-match-data (string-match "\"" match start))))
14316 ;; match contains also a todo-matching request
14317 (progn
14318 (setq tagsmatch (substring match 0 (match-beginning 0))
14319 todomatch (substring match (match-end 0)))
14320 (if (string-match "^!" todomatch)
14321 (setq todo-only t todomatch (substring todomatch 1)))
14322 (if (string-match "^\\s-*$" todomatch)
14323 (setq todomatch nil)))
14324 ;; only matching tags
14325 (setq tagsmatch match todomatch nil))
14327 ;; Make the tags matcher
14328 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14329 (setq tagsmatcher t)
14330 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14331 (while (setq term (pop orterms))
14332 (while (and (equal (substring term -1) "\\") orterms)
14333 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14334 (while (string-match re term)
14335 (setq rest (substring term (match-end 0))
14336 minus (and (match-end 1)
14337 (equal (match-string 1 term) "-"))
14338 tag (save-match-data (replace-regexp-in-string
14339 "\\\\-" "-"
14340 (match-string 2 term)))
14341 re-p (equal (string-to-char tag) ?{)
14342 level-p (match-end 4)
14343 prop-p (match-end 5)
14344 mm (cond
14345 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14346 (level-p
14347 (setq level-op (org-op-to-function (match-string 3 term)))
14348 `(,level-op level ,(string-to-number
14349 (match-string 4 term))))
14350 (prop-p
14351 (setq pn (match-string 5 term)
14352 po (match-string 6 term)
14353 pv (match-string 7 term)
14354 re-p (equal (string-to-char pv) ?{)
14355 str-p (equal (string-to-char pv) ?\")
14356 time-p (save-match-data
14357 (string-match "^\"[[<].*[]>]\"$" pv))
14358 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14359 (if time-p (setq pv (org-matcher-time pv)))
14360 (setq po (org-op-to-function po (if time-p 'time str-p)))
14361 (cond
14362 ((equal pn "CATEGORY")
14363 (setq gv '(get-text-property (point) 'org-category)))
14364 ((equal pn "TODO")
14365 (setq gv 'todo))
14367 (setq gv `(org-cached-entry-get nil ,pn))))
14368 (if re-p
14369 (if (eq po 'org<>)
14370 `(not (string-match ,pv (or ,gv "")))
14371 `(string-match ,pv (or ,gv "")))
14372 (if str-p
14373 `(,po (or ,gv "") ,pv)
14374 `(,po (string-to-number (or ,gv ""))
14375 ,(string-to-number pv) ))))
14376 (t `(member ,tag tags-list)))
14377 mm (if minus (list 'not mm) mm)
14378 term rest)
14379 (push mm tagsmatcher))
14380 (push (if (> (length tagsmatcher) 1)
14381 (cons 'and tagsmatcher)
14382 (car tagsmatcher))
14383 orlist)
14384 (setq tagsmatcher nil))
14385 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14386 (setq tagsmatcher
14387 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14388 ;; Make the todo matcher
14389 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14390 (setq todomatcher t)
14391 (setq orterms (org-split-string todomatch "|") orlist nil)
14392 (while (setq term (pop orterms))
14393 (while (string-match re term)
14394 (setq minus (and (match-end 1)
14395 (equal (match-string 1 term) "-"))
14396 kwd (match-string 2 term)
14397 re-p (equal (string-to-char kwd) ?{)
14398 term (substring term (match-end 0))
14399 mm (if re-p
14400 `(string-match ,(substring kwd 1 -1) todo)
14401 (list 'equal 'todo kwd))
14402 mm (if minus (list 'not mm) mm))
14403 (push mm todomatcher))
14404 (push (if (> (length todomatcher) 1)
14405 (cons 'and todomatcher)
14406 (car todomatcher))
14407 orlist)
14408 (setq todomatcher nil))
14409 (setq todomatcher (if (> (length orlist) 1)
14410 (cons 'or orlist) (car orlist))))
14412 ;; Return the string and lisp forms of the matcher
14413 (setq matcher (if todomatcher
14414 (list 'and tagsmatcher todomatcher)
14415 tagsmatcher))
14416 (when todo-only
14417 (setq matcher (list 'and '(member todo org-not-done-keywords)
14418 matcher)))
14419 (cons match0 matcher)))
14421 (defun org-tags-expand (match &optional single-as-list downcased)
14422 "Expand group tags in MATCH.
14424 This replaces every group tag in MATCH with a regexp tag search.
14425 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14426 will be replaced like this:
14428 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14429 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14430 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14432 Replacing by a regexp preserves the structure of the match.
14433 E.g., this expansion
14435 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14437 will match anything tagged with \"Lab\" and \"Home\", or tagged
14438 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14440 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14441 assumed to be a single group tag, and the function will return
14442 the list of tags in this group.
14444 When DOWNCASE is non-nil, expand downcased TAGS."
14445 (if org-group-tags
14446 (let* ((case-fold-search t)
14447 (stable org-mode-syntax-table)
14448 (tal (or org-tag-groups-alist-for-agenda
14449 org-tag-groups-alist))
14450 (tal (if downcased
14451 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14452 (tml (mapcar 'car tal))
14453 (rtnmatch match) rpl)
14454 ;; @ and _ are allowed as word-components in tags
14455 (modify-syntax-entry ?@ "w" stable)
14456 (modify-syntax-entry ?_ "w" stable)
14457 (while (and tml
14458 (with-syntax-table stable
14459 (string-match
14460 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14461 (regexp-opt tml) "\\>\\)") rtnmatch)))
14462 (let* ((dir (match-string 1 rtnmatch))
14463 (tag (match-string 2 rtnmatch))
14464 (tag (if downcased (downcase tag) tag)))
14465 (setq tml (delete tag tml))
14466 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14467 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14468 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14469 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14470 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14471 (if single-as-list
14472 (or (reverse rpl) (list rtnmatch))
14473 rtnmatch))
14474 (if single-as-list (list (if downcased (downcase match) match))
14475 match)))
14477 (defun org-op-to-function (op &optional stringp)
14478 "Turn an operator into the appropriate function."
14479 (setq op
14480 (cond
14481 ((equal op "<" ) '(< string< org-time<))
14482 ((equal op ">" ) '(> org-string> org-time>))
14483 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14484 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14485 ((member op '("=" "==")) '(= string= org-time=))
14486 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14487 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14489 (defun org<> (a b) (not (= a b)))
14490 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14491 (defun org-string>= (a b) (not (string< a b)))
14492 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14493 (defun org-string<> (a b) (not (string= a b)))
14494 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14495 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14496 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14497 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14498 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14499 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14500 (defun org-2ft (s)
14501 "Convert S to a floating point time.
14502 If S is already a number, just return it. If it is a string, parse
14503 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14504 (cond
14505 ((numberp s) s)
14506 ((stringp s)
14507 (condition-case nil
14508 (float-time (apply 'encode-time (org-parse-time-string s)))
14509 (error 0.)))
14510 (t 0.)))
14512 (defun org-time-today ()
14513 "Time in seconds today at 0:00.
14514 Returns the float number of seconds since the beginning of the
14515 epoch to the beginning of today (00:00)."
14516 (float-time (apply 'encode-time
14517 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14519 (defun org-matcher-time (s)
14520 "Interpret a time comparison value."
14521 (save-match-data
14522 (cond
14523 ((string= s "<now>") (float-time))
14524 ((string= s "<today>") (org-time-today))
14525 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14526 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14527 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14528 (+ (org-time-today)
14529 (* (string-to-number (match-string 1 s))
14530 (cdr (assoc (match-string 2 s)
14531 '(("d" . 86400.0) ("w" . 604800.0)
14532 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14533 (t (org-2ft s)))))
14535 (defun org-match-any-p (re list)
14536 "Does re match any element of list?"
14537 (setq list (mapcar (lambda (x) (string-match re x)) list))
14538 (delq nil list))
14540 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14541 (defvar org-tags-overlay (make-overlay 1 1))
14542 (org-detach-overlay org-tags-overlay)
14544 (defun org-get-local-tags-at (&optional pos)
14545 "Get a list of tags defined in the current headline."
14546 (org-get-tags-at pos 'local))
14548 (defun org-get-local-tags ()
14549 "Get a list of tags defined in the current headline."
14550 (org-get-tags-at nil 'local))
14552 (defun org-get-tags-at (&optional pos local)
14553 "Get a list of all headline tags applicable at POS.
14554 POS defaults to point. If tags are inherited, the list contains
14555 the targets in the same sequence as the headlines appear, i.e.
14556 the tags of the current headline come last.
14557 When LOCAL is non-nil, only return tags from the current headline,
14558 ignore inherited ones."
14559 (interactive)
14560 (if (and org-trust-scanner-tags
14561 (or (not pos) (equal pos (point)))
14562 (not local))
14563 org-scanner-tags
14564 (let (tags ltags lastpos parent)
14565 (save-excursion
14566 (save-restriction
14567 (widen)
14568 (goto-char (or pos (point)))
14569 (save-match-data
14570 (catch 'done
14571 (condition-case nil
14572 (progn
14573 (org-back-to-heading t)
14574 (while (not (equal lastpos (point)))
14575 (setq lastpos (point))
14576 (when (looking-at
14577 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14578 (setq ltags (org-split-string
14579 (org-match-string-no-properties 1) ":"))
14580 (when parent
14581 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14582 (setq tags (append
14583 (if parent
14584 (org-remove-uninherited-tags ltags)
14585 ltags)
14586 tags)))
14587 (or org-use-tag-inheritance (throw 'done t))
14588 (if local (throw 'done t))
14589 (or (org-up-heading-safe) (error nil))
14590 (setq parent t)))
14591 (error nil)))))
14592 (if local
14593 tags
14594 (reverse (delete-dups
14595 (reverse (append
14596 (org-remove-uninherited-tags
14597 org-file-tags) tags)))))))))
14599 (defun org-add-prop-inherited (s)
14600 (add-text-properties 0 (length s) '(inherited t) s)
14603 (defun org-toggle-tag (tag &optional onoff)
14604 "Toggle the tag TAG for the current line.
14605 If ONOFF is `on' or `off', don't toggle but set to this state."
14606 (let (res current)
14607 (save-excursion
14608 (org-back-to-heading t)
14609 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14610 (point-at-eol) t)
14611 (progn
14612 (setq current (match-string 1))
14613 (replace-match ""))
14614 (setq current ""))
14615 (setq current (nreverse (org-split-string current ":")))
14616 (cond
14617 ((eq onoff 'on)
14618 (setq res t)
14619 (or (member tag current) (push tag current)))
14620 ((eq onoff 'off)
14621 (or (not (member tag current)) (setq current (delete tag current))))
14622 (t (if (member tag current)
14623 (setq current (delete tag current))
14624 (setq res t)
14625 (push tag current))))
14626 (end-of-line 1)
14627 (if current
14628 (progn
14629 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14630 (org-set-tags nil t))
14631 (delete-horizontal-space))
14632 (run-hooks 'org-after-tags-change-hook))
14633 res))
14635 (defun org-align-tags-here (to-col)
14636 ;; Assumes that this is a headline
14637 "Align tags on the current headline to TO-COL."
14638 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14639 (beginning-of-line 1)
14640 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14641 (< pos (match-beginning 2)))
14642 (progn
14643 (setq tags-l (- (match-end 2) (match-beginning 2)))
14644 (goto-char (match-beginning 1))
14645 (insert " ")
14646 (delete-region (point) (1+ (match-beginning 2)))
14647 (setq ncol (max (current-column)
14648 (1+ col)
14649 (if (> to-col 0)
14650 to-col
14651 (- (abs to-col) tags-l))))
14652 (setq p (point))
14653 (insert (make-string (- ncol (current-column)) ?\ ))
14654 (setq ncol (current-column))
14655 (when indent-tabs-mode (tabify p (point-at-eol)))
14656 (org-move-to-column (min ncol col)))
14657 (goto-char pos))))
14659 (defun org-set-tags-command (&optional arg just-align)
14660 "Call the set-tags command for the current entry."
14661 (interactive "P")
14662 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14663 (org-set-tags arg just-align)
14664 (save-excursion
14665 (unless (and (org-region-active-p)
14666 org-loop-over-headlines-in-active-region)
14667 (org-back-to-heading t))
14668 (org-set-tags arg just-align))))
14670 (defun org-set-tags-to (data)
14671 "Set the tags of the current entry to DATA, replacing the current tags.
14672 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14673 If DATA is nil or the empty string, any tags will be removed."
14674 (interactive "sTags: ")
14675 (setq data
14676 (cond
14677 ((eq data nil) "")
14678 ((equal data "") "")
14679 ((stringp data)
14680 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14681 ":"))
14682 ((listp data)
14683 (concat ":" (mapconcat 'identity data ":") ":"))))
14684 (when data
14685 (save-excursion
14686 (org-back-to-heading t)
14687 (when (looking-at org-complex-heading-regexp)
14688 (if (match-end 5)
14689 (progn
14690 (goto-char (match-beginning 5))
14691 (insert data)
14692 (delete-region (point) (point-at-eol))
14693 (org-set-tags nil 'align))
14694 (goto-char (point-at-eol))
14695 (insert " " data)
14696 (org-set-tags nil 'align)))
14697 (beginning-of-line 1)
14698 (if (looking-at ".*?\\([ \t]+\\)$")
14699 (delete-region (match-beginning 1) (match-end 1))))))
14701 (defun org-align-all-tags ()
14702 "Align the tags i all headings."
14703 (interactive)
14704 (save-excursion
14705 (or (ignore-errors (org-back-to-heading t))
14706 (outline-next-heading))
14707 (if (org-at-heading-p)
14708 (org-set-tags t)
14709 (message "No headings"))))
14711 (defvar org-indent-indentation-per-level)
14712 (defun org-set-tags (&optional arg just-align)
14713 "Set the tags for the current headline.
14714 With prefix ARG, realign all tags in headings in the current buffer.
14715 When JUST-ALIGN is non-nil, only align tags."
14716 (interactive "P")
14717 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14718 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14719 'region-start-level 'region))
14720 org-loop-over-headlines-in-active-region)
14721 (org-map-entries
14722 ;; We don't use ARG and JUST-ALIGN here because these args
14723 ;; are not useful when looping over headlines.
14724 `(org-set-tags)
14725 org-loop-over-headlines-in-active-region
14726 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14727 (let* ((re org-outline-regexp-bol)
14728 (current (unless arg (org-get-tags-string)))
14729 (col (current-column))
14730 (org-setting-tags t)
14731 table current-tags inherited-tags ; computed below when needed
14732 tags p0 c0 c1 rpl di tc level)
14733 (if arg
14734 (save-excursion
14735 (goto-char (point-min))
14736 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14737 (while (re-search-forward re nil t)
14738 (org-set-tags nil t)
14739 (end-of-line 1)))
14740 (message "All tags realigned to column %d" org-tags-column))
14741 (if just-align
14742 (setq tags current)
14743 ;; Get a new set of tags from the user
14744 (save-excursion
14745 (setq table (append org-tag-persistent-alist
14746 (or org-tag-alist (org-get-buffer-tags))
14747 (and
14748 org-complete-tags-always-offer-all-agenda-tags
14749 (org-global-tags-completion-table
14750 (org-agenda-files))))
14751 org-last-tags-completion-table table
14752 current-tags (org-split-string current ":")
14753 inherited-tags (nreverse
14754 (nthcdr (length current-tags)
14755 (nreverse (org-get-tags-at))))
14756 tags
14757 (if (or (eq t org-use-fast-tag-selection)
14758 (and org-use-fast-tag-selection
14759 (delq nil (mapcar 'cdr table))))
14760 (org-fast-tag-selection
14761 current-tags inherited-tags table
14762 (if org-fast-tag-selection-include-todo
14763 org-todo-key-alist))
14764 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14765 (org-trim
14766 (org-icompleting-read "Tags: "
14767 'org-tags-completion-function
14768 nil nil current 'org-tags-history))))))
14769 (while (string-match "[-+&]+" tags)
14770 ;; No boolean logic, just a list
14771 (setq tags (replace-match ":" t t tags))))
14773 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14775 (if org-tags-sort-function
14776 (setq tags (mapconcat 'identity
14777 (sort (org-split-string
14778 tags (org-re "[^[:alnum:]_@#%]+"))
14779 org-tags-sort-function) ":")))
14781 (if (string-match "\\`[\t ]*\\'" tags)
14782 (setq tags "")
14783 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14784 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14786 ;; Insert new tags at the correct column
14787 (beginning-of-line 1)
14788 (setq level (or (and (looking-at org-outline-regexp)
14789 (- (match-end 0) (point) 1))
14791 (cond
14792 ((and (equal current "") (equal tags "")))
14793 ((re-search-forward
14794 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14795 (point-at-eol) t)
14796 (if (equal tags "")
14797 (setq rpl "")
14798 (goto-char (match-beginning 0))
14799 (setq c0 (current-column)
14800 ;; compute offset for the case of org-indent-mode active
14801 di (if (org-bound-and-true-p org-indent-mode)
14802 (* (1- org-indent-indentation-per-level) (1- level))
14804 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14805 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14806 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14807 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14808 (replace-match rpl t t)
14809 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14810 tags)
14811 (t (error "Tags alignment failed")))
14812 (org-move-to-column col)
14813 (unless just-align
14814 (run-hooks 'org-after-tags-change-hook))))))
14816 (defun org-change-tag-in-region (beg end tag off)
14817 "Add or remove TAG for each entry in the region.
14818 This works in the agenda, and also in an org-mode buffer."
14819 (interactive
14820 (list (region-beginning) (region-end)
14821 (let ((org-last-tags-completion-table
14822 (if (derived-mode-p 'org-mode)
14823 (org-uniquify
14824 (delq nil (append (org-get-buffer-tags)
14825 (org-global-tags-completion-table))))
14826 (org-global-tags-completion-table))))
14827 (org-icompleting-read
14828 "Tag: " 'org-tags-completion-function nil nil nil
14829 'org-tags-history))
14830 (progn
14831 (message "[s]et or [r]emove? ")
14832 (equal (read-char-exclusive) ?r))))
14833 (if (fboundp 'deactivate-mark) (deactivate-mark))
14834 (let ((agendap (equal major-mode 'org-agenda-mode))
14835 l1 l2 m buf pos newhead (cnt 0))
14836 (goto-char end)
14837 (setq l2 (1- (org-current-line)))
14838 (goto-char beg)
14839 (setq l1 (org-current-line))
14840 (loop for l from l1 to l2 do
14841 (org-goto-line l)
14842 (setq m (get-text-property (point) 'org-hd-marker))
14843 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14844 (and agendap m))
14845 (setq buf (if agendap (marker-buffer m) (current-buffer))
14846 pos (if agendap m (point)))
14847 (with-current-buffer buf
14848 (save-excursion
14849 (save-restriction
14850 (goto-char pos)
14851 (setq cnt (1+ cnt))
14852 (org-toggle-tag tag (if off 'off 'on))
14853 (setq newhead (org-get-heading)))))
14854 (and agendap (org-agenda-change-all-lines newhead m))))
14855 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14857 (defun org-tags-completion-function (string predicate &optional flag)
14858 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14859 (confirm (lambda (x) (stringp (car x)))))
14860 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14861 (setq s1 (match-string 1 string)
14862 s2 (match-string 2 string))
14863 (setq s1 "" s2 string))
14864 (cond
14865 ((eq flag nil)
14866 ;; try completion
14867 (setq rtn (try-completion s2 ctable confirm))
14868 (if (stringp rtn)
14869 (setq rtn
14870 (concat s1 s2 (substring rtn (length s2))
14871 (if (and org-add-colon-after-tag-completion
14872 (assoc rtn ctable))
14873 ":" ""))))
14874 rtn)
14875 ((eq flag t)
14876 ;; all-completions
14877 (all-completions s2 ctable confirm))
14878 ((eq flag 'lambda)
14879 ;; exact match?
14880 (assoc s2 ctable)))))
14882 (defun org-fast-tag-insert (kwd tags face &optional end)
14883 "Insert KDW, and the TAGS, the latter with face FACE.
14884 Also insert END."
14885 (insert (format "%-12s" (concat kwd ":"))
14886 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14887 (or end "")))
14889 (defun org-fast-tag-show-exit (flag)
14890 (save-excursion
14891 (org-goto-line 3)
14892 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14893 (replace-match ""))
14894 (when flag
14895 (end-of-line 1)
14896 (org-move-to-column (- (window-width) 19) t)
14897 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14899 (defun org-set-current-tags-overlay (current prefix)
14900 "Add an overlay to CURRENT tag with PREFIX."
14901 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14902 (if (featurep 'xemacs)
14903 (org-overlay-display org-tags-overlay (concat prefix s)
14904 'secondary-selection)
14905 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14906 (org-overlay-display org-tags-overlay (concat prefix s)))))
14908 (defvar org-last-tag-selection-key nil)
14909 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14910 "Fast tag selection with single keys.
14911 CURRENT is the current list of tags in the headline, INHERITED is the
14912 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14913 possibly with grouping information. TODO-TABLE is a similar table with
14914 TODO keywords, should these have keys assigned to them.
14915 If the keys are nil, a-z are automatically assigned.
14916 Returns the new tags string, or nil to not change the current settings."
14917 (let* ((fulltable (append table todo-table))
14918 (maxlen (apply 'max (mapcar
14919 (lambda (x)
14920 (if (stringp (car x)) (string-width (car x)) 0))
14921 fulltable)))
14922 (buf (current-buffer))
14923 (expert (eq org-fast-tag-selection-single-key 'expert))
14924 (buffer-tags nil)
14925 (fwidth (+ maxlen 3 1 3))
14926 (ncol (/ (- (window-width) 4) fwidth))
14927 (i-face 'org-done)
14928 (c-face 'org-todo)
14929 tg cnt e c char c1 c2 ntable tbl rtn
14930 ov-start ov-end ov-prefix
14931 (exit-after-next org-fast-tag-selection-single-key)
14932 (done-keywords org-done-keywords)
14933 groups ingroup)
14934 (save-excursion
14935 (beginning-of-line 1)
14936 (if (looking-at
14937 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14938 (setq ov-start (match-beginning 1)
14939 ov-end (match-end 1)
14940 ov-prefix "")
14941 (setq ov-start (1- (point-at-eol))
14942 ov-end (1+ ov-start))
14943 (skip-chars-forward "^\n\r")
14944 (setq ov-prefix
14945 (concat
14946 (buffer-substring (1- (point)) (point))
14947 (if (> (current-column) org-tags-column)
14949 (make-string (- org-tags-column (current-column)) ?\ ))))))
14950 (move-overlay org-tags-overlay ov-start ov-end)
14951 (save-window-excursion
14952 (if expert
14953 (set-buffer (get-buffer-create " *Org tags*"))
14954 (delete-other-windows)
14955 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14956 (org-switch-to-buffer-other-window " *Org tags*"))
14957 (erase-buffer)
14958 (org-set-local 'org-done-keywords done-keywords)
14959 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14960 (org-fast-tag-insert "Current" current c-face "\n\n")
14961 (org-fast-tag-show-exit exit-after-next)
14962 (org-set-current-tags-overlay current ov-prefix)
14963 (setq tbl fulltable char ?a cnt 0)
14964 (while (setq e (pop tbl))
14965 (cond
14966 ((equal (car e) :startgroup)
14967 (push '() groups) (setq ingroup t)
14968 (when (not (= cnt 0))
14969 (setq cnt 0)
14970 (insert "\n"))
14971 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14972 ((equal (car e) :endgroup)
14973 (setq ingroup nil cnt 0)
14974 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14975 ((equal e '(:newline))
14976 (when (not (= cnt 0))
14977 (setq cnt 0)
14978 (insert "\n")
14979 (setq e (car tbl))
14980 (while (equal (car tbl) '(:newline))
14981 (insert "\n")
14982 (setq tbl (cdr tbl)))))
14983 ((equal e '(:grouptags)) nil)
14985 (setq tg (copy-sequence (car e)) c2 nil)
14986 (if (cdr e)
14987 (setq c (cdr e))
14988 ;; automatically assign a character.
14989 (setq c1 (string-to-char
14990 (downcase (substring
14991 tg (if (= (string-to-char tg) ?@) 1 0)))))
14992 (if (or (rassoc c1 ntable) (rassoc c1 table))
14993 (while (or (rassoc char ntable) (rassoc char table))
14994 (setq char (1+ char)))
14995 (setq c2 c1))
14996 (setq c (or c2 char)))
14997 (if ingroup (push tg (car groups)))
14998 (setq tg (org-add-props tg nil 'face
14999 (cond
15000 ((not (assoc tg table))
15001 (org-get-todo-face tg))
15002 ((member tg current) c-face)
15003 ((member tg inherited) i-face))))
15004 (if (equal (caar tbl) :grouptags)
15005 (org-add-props tg nil 'face 'org-tag-group))
15006 (if (and (= cnt 0) (not ingroup)) (insert " "))
15007 (insert "[" c "] " tg (make-string
15008 (- fwidth 4 (length tg)) ?\ ))
15009 (push (cons tg c) ntable)
15010 (when (= (setq cnt (1+ cnt)) ncol)
15011 (insert "\n")
15012 (if ingroup (insert " "))
15013 (setq cnt 0)))))
15014 (setq ntable (nreverse ntable))
15015 (insert "\n")
15016 (goto-char (point-min))
15017 (if (not expert) (org-fit-window-to-buffer))
15018 (setq rtn
15019 (catch 'exit
15020 (while t
15021 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15022 (if (not groups) "no " "")
15023 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15024 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15025 (setq org-last-tag-selection-key c)
15026 (cond
15027 ((= c ?\r) (throw 'exit t))
15028 ((= c ?!)
15029 (setq groups (not groups))
15030 (goto-char (point-min))
15031 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15032 ((= c ?\C-c)
15033 (if (not expert)
15034 (org-fast-tag-show-exit
15035 (setq exit-after-next (not exit-after-next)))
15036 (setq expert nil)
15037 (delete-other-windows)
15038 (set-window-buffer (split-window-vertically) " *Org tags*")
15039 (org-switch-to-buffer-other-window " *Org tags*")
15040 (org-fit-window-to-buffer)))
15041 ((or (= c ?\C-g)
15042 (and (= c ?q) (not (rassoc c ntable))))
15043 (org-detach-overlay org-tags-overlay)
15044 (setq quit-flag t))
15045 ((= c ?\ )
15046 (setq current nil)
15047 (if exit-after-next (setq exit-after-next 'now)))
15048 ((= c ?\t)
15049 (condition-case nil
15050 (setq tg (org-icompleting-read
15051 "Tag: "
15052 (or buffer-tags
15053 (with-current-buffer buf
15054 (org-get-buffer-tags)))))
15055 (quit (setq tg "")))
15056 (when (string-match "\\S-" tg)
15057 (add-to-list 'buffer-tags (list tg))
15058 (if (member tg current)
15059 (setq current (delete tg current))
15060 (push tg current)))
15061 (if exit-after-next (setq exit-after-next 'now)))
15062 ((setq e (rassoc c todo-table) tg (car e))
15063 (with-current-buffer buf
15064 (save-excursion (org-todo tg)))
15065 (if exit-after-next (setq exit-after-next 'now)))
15066 ((setq e (rassoc c ntable) tg (car e))
15067 (if (member tg current)
15068 (setq current (delete tg current))
15069 (loop for g in groups do
15070 (if (member tg g)
15071 (mapc (lambda (x)
15072 (setq current (delete x current)))
15073 g)))
15074 (push tg current))
15075 (if exit-after-next (setq exit-after-next 'now))))
15077 ;; Create a sorted list
15078 (setq current
15079 (sort current
15080 (lambda (a b)
15081 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15082 (if (eq exit-after-next 'now) (throw 'exit t))
15083 (goto-char (point-min))
15084 (beginning-of-line 2)
15085 (delete-region (point) (point-at-eol))
15086 (org-fast-tag-insert "Current" current c-face)
15087 (org-set-current-tags-overlay current ov-prefix)
15088 (while (re-search-forward
15089 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15090 (setq tg (match-string 1))
15091 (add-text-properties
15092 (match-beginning 1) (match-end 1)
15093 (list 'face
15094 (cond
15095 ((member tg current) c-face)
15096 ((member tg inherited) i-face)
15097 (t (get-text-property (match-beginning 1) 'face))))))
15098 (goto-char (point-min)))))
15099 (org-detach-overlay org-tags-overlay)
15100 (if rtn
15101 (mapconcat 'identity current ":")
15102 nil))))
15104 (defun org-get-tags-string ()
15105 "Get the TAGS string in the current headline."
15106 (unless (org-at-heading-p t)
15107 (user-error "Not on a heading"))
15108 (save-excursion
15109 (beginning-of-line 1)
15110 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15111 (org-match-string-no-properties 1)
15112 "")))
15114 (defun org-get-tags ()
15115 "Get the list of tags specified in the current headline."
15116 (org-split-string (org-get-tags-string) ":"))
15118 (defun org-get-buffer-tags ()
15119 "Get a table of all tags used in the buffer, for completion."
15120 (let (tags)
15121 (save-excursion
15122 (goto-char (point-min))
15123 (while (re-search-forward
15124 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15125 (when (equal (char-after (point-at-bol 0)) ?*)
15126 (mapc (lambda (x) (add-to-list 'tags x))
15127 (org-split-string (org-match-string-no-properties 1) ":")))))
15128 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15129 (mapcar 'list tags)))
15131 ;;;; The mapping API
15133 (defun org-map-entries (func &optional match scope &rest skip)
15134 "Call FUNC at each headline selected by MATCH in SCOPE.
15136 FUNC is a function or a lisp form. The function will be called without
15137 arguments, with the cursor positioned at the beginning of the headline.
15138 The return values of all calls to the function will be collected and
15139 returned as a list.
15141 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15142 does not need to preserve point. After evaluation, the cursor will be
15143 moved to the end of the line (presumably of the headline of the
15144 processed entry) and search continues from there. Under some
15145 circumstances, this may not produce the wanted results. For example,
15146 if you have removed (e.g. archived) the current (sub)tree it could
15147 mean that the next entry will be skipped entirely. In such cases, you
15148 can specify the position from where search should continue by making
15149 FUNC set the variable `org-map-continue-from' to the desired buffer
15150 position.
15152 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15153 Only headlines that are matched by this query will be considered during
15154 the iteration. When MATCH is nil or t, all headlines will be
15155 visited by the iteration.
15157 SCOPE determines the scope of this command. It can be any of:
15159 nil The current buffer, respecting the restriction if any
15160 tree The subtree started with the entry at point
15161 region The entries within the active region, if any
15162 region-start-level
15163 The entries within the active region, but only those at
15164 the same level than the first one.
15165 file The current buffer, without restriction
15166 file-with-archives
15167 The current buffer, and any archives associated with it
15168 agenda All agenda files
15169 agenda-with-archives
15170 All agenda files with any archive files associated with them
15171 \(file1 file2 ...)
15172 If this is a list, all files in the list will be scanned
15174 The remaining args are treated as settings for the skipping facilities of
15175 the scanner. The following items can be given here:
15177 archive skip trees with the archive tag
15178 comment skip trees with the COMMENT keyword
15179 function or Emacs Lisp form:
15180 will be used as value for `org-agenda-skip-function', so
15181 whenever the function returns a position, FUNC will not be
15182 called for that entry and search will continue from the
15183 position returned
15185 If your function needs to retrieve the tags including inherited tags
15186 at the *current* entry, you can use the value of the variable
15187 `org-scanner-tags' which will be much faster than getting the value
15188 with `org-get-tags-at'. If your function gets properties with
15189 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15190 to t around the call to `org-entry-properties' to get the same speedup.
15191 Note that if your function moves around to retrieve tags and properties at
15192 a *different* entry, you cannot use these techniques."
15193 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15194 (not (org-region-active-p)))
15195 (let* ((org-agenda-archives-mode nil) ; just to make sure
15196 (org-agenda-skip-archived-trees (memq 'archive skip))
15197 (org-agenda-skip-comment-trees (memq 'comment skip))
15198 (org-agenda-skip-function
15199 (car (org-delete-all '(comment archive) skip)))
15200 (org-tags-match-list-sublevels t)
15201 (start-level (eq scope 'region-start-level))
15202 matcher file res
15203 org-todo-keywords-for-agenda
15204 org-done-keywords-for-agenda
15205 org-todo-keyword-alist-for-agenda
15206 org-tag-alist-for-agenda
15207 todo-only)
15209 (cond
15210 ((eq match t) (setq matcher t))
15211 ((eq match nil) (setq matcher t))
15212 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15214 (save-excursion
15215 (save-restriction
15216 (cond ((eq scope 'tree)
15217 (org-back-to-heading t)
15218 (org-narrow-to-subtree)
15219 (setq scope nil))
15220 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15221 (org-region-active-p))
15222 ;; If needed, set start-level to a string like "2"
15223 (when start-level
15224 (save-excursion
15225 (goto-char (region-beginning))
15226 (unless (org-at-heading-p) (outline-next-heading))
15227 (setq start-level (org-current-level))))
15228 (narrow-to-region (region-beginning)
15229 (save-excursion
15230 (goto-char (region-end))
15231 (unless (and (bolp) (org-at-heading-p))
15232 (outline-next-heading))
15233 (point)))
15234 (setq scope nil)))
15236 (if (not scope)
15237 (progn
15238 (org-agenda-prepare-buffers
15239 (list (buffer-file-name (current-buffer))))
15240 (setq res (org-scan-tags func matcher todo-only start-level)))
15241 ;; Get the right scope
15242 (cond
15243 ((and scope (listp scope) (symbolp (car scope)))
15244 (setq scope (eval scope)))
15245 ((eq scope 'agenda)
15246 (setq scope (org-agenda-files t)))
15247 ((eq scope 'agenda-with-archives)
15248 (setq scope (org-agenda-files t))
15249 (setq scope (org-add-archive-files scope)))
15250 ((eq scope 'file)
15251 (setq scope (list (buffer-file-name))))
15252 ((eq scope 'file-with-archives)
15253 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15254 (org-agenda-prepare-buffers scope)
15255 (while (setq file (pop scope))
15256 (with-current-buffer (org-find-base-buffer-visiting file)
15257 (save-excursion
15258 (save-restriction
15259 (widen)
15260 (goto-char (point-min))
15261 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15262 res)))
15264 ;;;; Properties
15266 ;;; Setting and retrieving properties
15268 (defconst org-special-properties
15269 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15270 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15271 "The special properties valid in Org-mode.
15273 These are properties that are not defined in the property drawer,
15274 but in some other way.")
15276 (defconst org-default-properties
15277 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15278 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15279 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15280 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15281 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15282 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15283 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15284 "Some properties that are used by Org-mode for various purposes.
15285 Being in this list makes sure that they are offered for completion.")
15287 (defun org-property-action ()
15288 "Do an action on properties."
15289 (interactive)
15290 (let (c)
15291 (org-at-property-p)
15292 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15293 (setq c (read-char-exclusive))
15294 (cond
15295 ((equal c ?s)
15296 (call-interactively 'org-set-property))
15297 ((equal c ?d)
15298 (call-interactively 'org-delete-property))
15299 ((equal c ?D)
15300 (call-interactively 'org-delete-property-globally))
15301 ((equal c ?c)
15302 (call-interactively 'org-compute-property-at-point))
15303 (t (user-error "No such property action %c" c)))))
15305 (defun org-inc-effort ()
15306 "Increment the value of the effort property in the current entry."
15307 (interactive)
15308 (org-set-effort nil t))
15310 (defvar org-clock-effort) ;; Defined in org-clock.el
15311 (defvar org-clock-current-task) ;; Defined in org-clock.el
15312 (defun org-set-effort (&optional value increment)
15313 "Set the effort property of the current entry.
15314 With numerical prefix arg, use the nth allowed value, 0 stands for the
15315 10th allowed value.
15317 When INCREMENT is non-nil, set the property to the next allowed value."
15318 (interactive "P")
15319 (if (equal value 0) (setq value 10))
15320 (let* ((completion-ignore-case t)
15321 (prop org-effort-property)
15322 (cur (org-entry-get nil prop))
15323 (allowed (org-property-get-allowed-values nil prop 'table))
15324 (existing (mapcar 'list (org-property-values prop)))
15325 (heading (nth 4 (org-heading-components)))
15327 (val (cond
15328 ((stringp value) value)
15329 ((and allowed (integerp value))
15330 (or (car (nth (1- value) allowed))
15331 (car (org-last allowed))))
15332 ((and allowed increment)
15333 (or (caadr (member (list cur) allowed))
15334 (user-error "Allowed effort values are not set")))
15335 (allowed
15336 (message "Select 1-9,0, [RET%s]: %s"
15337 (if cur (concat "=" cur) "")
15338 (mapconcat 'car allowed " "))
15339 (setq rpl (read-char-exclusive))
15340 (if (equal rpl ?\r)
15342 (setq rpl (- rpl ?0))
15343 (if (equal rpl 0) (setq rpl 10))
15344 (if (and (> rpl 0) (<= rpl (length allowed)))
15345 (car (nth (1- rpl) allowed))
15346 (org-completing-read "Effort: " allowed nil))))
15348 (let (org-completion-use-ido org-completion-use-iswitchb)
15349 (org-completing-read
15350 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15351 (concat "[" cur "]") "")
15352 ": ")
15353 existing nil nil "" nil cur))))))
15354 (unless (equal (org-entry-get nil prop) val)
15355 (org-entry-put nil prop val))
15356 (save-excursion
15357 (org-back-to-heading t)
15358 (put-text-property (point-at-bol) (point-at-eol) 'effort val))
15359 (when (string= heading org-clock-current-task)
15360 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15361 (org-clock-update-mode-line))
15362 (message "%s is now %s" prop val)))
15364 (defun org-at-property-p ()
15365 "Non-nil when point is inside a property drawer.
15366 See `org-property-re' for match data, if applicable."
15367 (when (eq (org-element-type (org-element-at-point)) 'node-property)
15368 (save-excursion
15369 (beginning-of-line)
15370 (looking-at org-property-re))))
15372 (defun org-get-property-block (&optional beg end force)
15373 "Return the (beg . end) range of the body of the property drawer.
15374 BEG and END are the beginning and end of the current subtree, or of
15375 the part before the first headline. If they are not given, they will
15376 be found. If the drawer does not exist and FORCE is non-nil, create
15377 the drawer."
15378 (catch 'exit
15379 (save-excursion
15380 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15381 (progn (org-back-to-heading t) (point))))
15382 (end (or end (and (not (outline-next-heading)) (point-max))
15383 (point))))
15384 (goto-char beg)
15385 (if (re-search-forward org-property-start-re end t)
15386 (setq beg (1+ (match-end 0)))
15387 (if force
15388 (save-excursion
15389 (org-insert-property-drawer)
15390 (setq end (progn (outline-next-heading) (point))))
15391 (throw 'exit nil))
15392 (goto-char beg)
15393 (if (re-search-forward org-property-start-re end t)
15394 (setq beg (1+ (match-end 0)))))
15395 (if (re-search-forward org-property-end-re end t)
15396 (setq end (match-beginning 0))
15397 (or force (throw 'exit nil))
15398 (goto-char beg)
15399 (setq end beg)
15400 (org-indent-line)
15401 (insert ":END:\n"))
15402 (cons beg end)))))
15404 (defun org-entry-properties (&optional pom which specific)
15405 "Get all properties of the entry at point-or-marker POM.
15406 This includes the TODO keyword, the tags, time strings for deadline,
15407 scheduled, and clocking, and any additional properties defined in the
15408 entry. The return value is an alist, keys may occur multiple times
15409 if the property key was used several times.
15410 POM may also be nil, in which case the current entry is used.
15411 If WHICH is nil or `all', get all properties. If WHICH is
15412 `special' or `standard', only get that subclass. If WHICH
15413 is a string only get exactly this property. SPECIFIC can be a string, the
15414 specific property we are interested in. Specifying it can speed
15415 things up because then unnecessary parsing is avoided."
15416 (setq which (or which 'all))
15417 (org-with-wide-buffer
15418 (org-with-point-at pom
15419 (let ((clockstr (substring org-clock-string 0 -1))
15420 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15421 (case-fold-search nil)
15422 beg end range props sum-props key key1 value string clocksum clocksumt)
15423 (when (and (derived-mode-p 'org-mode)
15424 (ignore-errors (org-back-to-heading t)))
15425 (setq beg (point))
15426 (setq sum-props (get-text-property (point) 'org-summaries))
15427 (setq clocksum (get-text-property (point) :org-clock-minutes)
15428 clocksumt (get-text-property (point) :org-clock-minutes-today))
15429 (outline-next-heading)
15430 (setq end (point))
15431 (when (memq which '(all special))
15432 ;; Get the special properties, like TODO and tags
15433 (goto-char beg)
15434 (when (and (or (not specific) (string= specific "TODO"))
15435 (looking-at org-todo-line-regexp) (match-end 2))
15436 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15437 (when (and (or (not specific) (string= specific "PRIORITY"))
15438 (looking-at org-priority-regexp))
15439 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15440 (when (or (not specific) (string= specific "FILE"))
15441 (push (cons "FILE" buffer-file-name) props))
15442 (when (and (or (not specific) (string= specific "TAGS"))
15443 (setq value (org-get-tags-string))
15444 (string-match "\\S-" value))
15445 (push (cons "TAGS" value) props))
15446 (when (and (or (not specific) (string= specific "ALLTAGS"))
15447 (setq value (org-get-tags-at)))
15448 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15449 ":"))
15450 props))
15451 (when (or (not specific) (string= specific "BLOCKED"))
15452 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15453 (when (or (not specific)
15454 (member specific
15455 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15456 "TIMESTAMP" "TIMESTAMP_IA")))
15457 (catch 'match
15458 (while (and (re-search-forward org-maybe-keyword-time-regexp end t)
15459 (not (text-property-any 0 (length (match-string 0))
15460 'face 'font-lock-comment-face
15461 (match-string 0))))
15462 (setq key (if (match-end 1)
15463 (substring (org-match-string-no-properties 1)
15464 0 -1))
15465 string (if (equal key clockstr)
15466 (org-trim
15467 (buffer-substring-no-properties
15468 (match-beginning 3) (goto-char
15469 (point-at-eol))))
15470 (substring (org-match-string-no-properties 3)
15471 1 -1)))
15472 ;; Get the correct property name from the key. This is
15473 ;; necessary if the user has configured time keywords.
15474 (setq key1 (concat key ":"))
15475 (cond
15476 ((not key)
15477 (setq key
15478 (if (= (char-after (match-beginning 3)) ?\[)
15479 "TIMESTAMP_IA" "TIMESTAMP")))
15480 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15481 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15482 ((equal key1 org-closed-string) (setq key "CLOSED"))
15483 ((equal key1 org-clock-string) (setq key "CLOCK")))
15484 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15485 (progn
15486 (push (cons key string) props)
15487 ;; no need to search further if match is found
15488 (throw 'match t))
15489 (when (or (equal key "CLOCK") (not (assoc key props)))
15490 (push (cons key string) props)))))))
15492 (when (memq which '(all standard))
15493 ;; Get the standard properties, like :PROP: ...
15494 (setq range (org-get-property-block beg end))
15495 (when range
15496 (goto-char (car range))
15497 (while (re-search-forward org-property-re
15498 (cdr range) t)
15499 (setq key (org-match-string-no-properties 2)
15500 value (org-trim (or (org-match-string-no-properties 3) "")))
15501 (unless (member key excluded)
15502 (push (cons key (or value "")) props)))))
15503 (if clocksum
15504 (push (cons "CLOCKSUM"
15505 (org-columns-number-to-string (/ (float clocksum) 60.)
15506 'add_times))
15507 props))
15508 (if clocksumt
15509 (push (cons "CLOCKSUM_T"
15510 (org-columns-number-to-string (/ (float clocksumt) 60.)
15511 'add_times))
15512 props))
15513 (unless (assoc "CATEGORY" props)
15514 (push (cons "CATEGORY" (org-get-category)) props))
15515 (append sum-props (nreverse props)))))))
15517 (defun org-entry-get (pom property &optional inherit literal-nil)
15518 "Get value of PROPERTY for entry or content at point-or-marker POM.
15519 If INHERIT is non-nil and the entry does not have the property,
15520 then also check higher levels of the hierarchy.
15521 If INHERIT is the symbol `selective', use inheritance only if the setting
15522 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15523 If the property is present but empty, the return value is the empty string.
15524 If the property is not present at all, nil is returned.
15526 Return the value as a string.
15528 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15529 do not interpret it as the list atom nil. This is used for inheritance
15530 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15531 (org-with-point-at pom
15532 (if (and inherit (if (eq inherit 'selective)
15533 (org-property-inherit-p property)
15535 (org-entry-get-with-inheritance property literal-nil)
15536 (if (member property org-special-properties)
15537 ;; We need a special property. Use `org-entry-properties'
15538 ;; to retrieve it, but specify the wanted property
15539 (cdr (assoc property (org-entry-properties nil 'special property)))
15540 (org-with-wide-buffer
15541 (let ((range (org-get-property-block)))
15542 (when (and range (not (eq (car range) (cdr range)))
15543 (save-excursion
15544 (goto-char (car range))
15545 (re-search-forward
15546 (concat (org-re-property property) "\\|"
15547 (org-re-property (concat property "+")))
15548 (cdr range) t)))
15549 (let* ((props
15550 (list (or (assoc property org-file-properties)
15551 (assoc property org-global-properties)
15552 (assoc property org-global-properties-fixed))))
15553 (ap (lambda (key)
15554 (when (re-search-forward
15555 (org-re-property key) (cdr range) t)
15556 (setq props
15557 (org-update-property-plist
15559 (if (match-end 3)
15560 (org-match-string-no-properties 3) "")
15561 props)))))
15562 val)
15563 (goto-char (car range))
15564 (funcall ap property)
15565 (goto-char (car range))
15566 (while (funcall ap (concat property "+")))
15567 (setq val (cdr (assoc property props)))
15568 (when val (if literal-nil val (org-not-nil val)))))))))))
15570 (defun org-property-or-variable-value (var &optional inherit)
15571 "Check if there is a property fixing the value of VAR.
15572 If yes, return this value. If not, return the current value of the variable."
15573 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15574 (if (and prop (stringp prop) (string-match "\\S-" prop))
15575 (read prop)
15576 (symbol-value var))))
15578 (defun org-entry-delete (pom property)
15579 "Delete the property PROPERTY from entry at point-or-marker POM."
15580 (unless (member property org-special-properties)
15581 (org-with-point-at pom
15582 (let ((range (org-get-property-block)))
15583 (if (and range
15584 (goto-char (car range))
15585 (re-search-forward
15586 (org-re-property property)
15587 (cdr range) t))
15588 (progn
15589 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15590 (org-remove-empty-drawer-at (car range))
15592 nil)))))
15594 ;; Multi-values properties are properties that contain multiple values
15595 ;; These values are assumed to be single words, separated by whitespace.
15596 (defun org-entry-add-to-multivalued-property (pom property value)
15597 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15598 (let* ((old (org-entry-get pom property))
15599 (values (and old (org-split-string old "[ \t]"))))
15600 (setq value (org-entry-protect-space value))
15601 (unless (member value values)
15602 (setq values (append values (list value)))
15603 (org-entry-put pom property
15604 (mapconcat 'identity values " ")))))
15606 (defun org-entry-remove-from-multivalued-property (pom property value)
15607 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15608 (let* ((old (org-entry-get pom property))
15609 (values (and old (org-split-string old "[ \t]"))))
15610 (setq value (org-entry-protect-space value))
15611 (when (member value values)
15612 (setq values (delete value values))
15613 (org-entry-put pom property
15614 (mapconcat 'identity values " ")))))
15616 (defun org-entry-member-in-multivalued-property (pom property value)
15617 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15618 (let* ((old (org-entry-get pom property))
15619 (values (and old (org-split-string old "[ \t]"))))
15620 (setq value (org-entry-protect-space value))
15621 (member value values)))
15623 (defun org-entry-get-multivalued-property (pom property)
15624 "Return a list of values in a multivalued property."
15625 (let* ((value (org-entry-get pom property))
15626 (values (and value (org-split-string value "[ \t]"))))
15627 (mapcar 'org-entry-restore-space values)))
15629 (defun org-entry-put-multivalued-property (pom property &rest values)
15630 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15631 VALUES should be a list of strings. Spaces will be protected."
15632 (org-entry-put pom property
15633 (mapconcat 'org-entry-protect-space values " "))
15634 (let* ((value (org-entry-get pom property))
15635 (values (and value (org-split-string value "[ \t]"))))
15636 (mapcar 'org-entry-restore-space values)))
15638 (defun org-entry-protect-space (s)
15639 "Protect spaces and newline in string S."
15640 (while (string-match " " s)
15641 (setq s (replace-match "%20" t t s)))
15642 (while (string-match "\n" s)
15643 (setq s (replace-match "%0A" t t s)))
15646 (defun org-entry-restore-space (s)
15647 "Restore spaces and newline in string S."
15648 (while (string-match "%20" s)
15649 (setq s (replace-match " " t t s)))
15650 (while (string-match "%0A" s)
15651 (setq s (replace-match "\n" t t s)))
15654 (defvar org-entry-property-inherited-from (make-marker)
15655 "Marker pointing to the entry from where a property was inherited.
15656 Each call to `org-entry-get-with-inheritance' will set this marker to the
15657 location of the entry where the inheritance search matched. If there was
15658 no match, the marker will point nowhere.
15659 Note that also `org-entry-get' calls this function, if the INHERIT flag
15660 is set.")
15662 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15663 "Get PROPERTY of entry or content at point, search higher levels if needed.
15664 The search will stop at the first ancestor which has the property defined.
15665 If the value found is \"nil\", return nil to show that the property
15666 should be considered as undefined (this is the meaning of nil here).
15667 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15668 (move-marker org-entry-property-inherited-from nil)
15669 (let (tmp)
15670 (save-excursion
15671 (save-restriction
15672 (widen)
15673 (catch 'ex
15674 (while t
15675 (when (setq tmp (org-entry-get nil property nil literal-nil))
15676 (or (ignore-errors (org-back-to-heading t))
15677 (goto-char (point-min)))
15678 (move-marker org-entry-property-inherited-from (point))
15679 (throw 'ex tmp))
15680 (or (ignore-errors (org-up-heading-safe))
15681 (throw 'ex nil))))))
15682 (setq tmp (or tmp
15683 (cdr (assoc property org-file-properties))
15684 (cdr (assoc property org-global-properties))
15685 (cdr (assoc property org-global-properties-fixed))))
15686 (if literal-nil tmp (org-not-nil tmp))))
15688 (defvar org-property-changed-functions nil
15689 "Hook called when the value of a property has changed.
15690 Each hook function should accept two arguments, the name of the property
15691 and the new value.")
15693 (defun org-entry-put (pom property value)
15694 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15695 If the value is `nil', it is converted to the empty string.
15696 If it is not a string, an error is raised."
15697 (cond ((null value) (setq value ""))
15698 ((not (stringp value))
15699 (error "Properties values should be strings.")))
15700 (org-with-point-at pom
15701 (org-back-to-heading t)
15702 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15703 range)
15704 (cond
15705 ((equal property "TODO")
15706 (when (and (string-match "\\S-" value)
15707 (not (member value org-todo-keywords-1)))
15708 (user-error "\"%s\" is not a valid TODO state" value))
15709 (if (or (not value)
15710 (not (string-match "\\S-" value)))
15711 (setq value 'none))
15712 (org-todo value)
15713 (org-set-tags nil 'align))
15714 ((equal property "PRIORITY")
15715 (org-priority (if (and value (string-match "\\S-" value))
15716 (string-to-char value) ?\ ))
15717 (org-set-tags nil 'align))
15718 ((equal property "CLOCKSUM")
15719 (if (not (re-search-forward
15720 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15721 (error "Cannot find a clock log")
15722 (goto-char (- (match-end 1) 2))
15723 (cond
15724 ((eq value 'earlier) (org-timestamp-down))
15725 ((eq value 'later) (org-timestamp-up)))
15726 (org-clock-sum-current-item)))
15727 ((equal property "SCHEDULED")
15728 (if (re-search-forward org-scheduled-time-regexp end t)
15729 (cond
15730 ((eq value 'earlier) (org-timestamp-change -1 'day))
15731 ((eq value 'later) (org-timestamp-change 1 'day))
15732 (t (call-interactively 'org-schedule)))
15733 (call-interactively 'org-schedule)))
15734 ((equal property "DEADLINE")
15735 (if (re-search-forward org-deadline-time-regexp end t)
15736 (cond
15737 ((eq value 'earlier) (org-timestamp-change -1 'day))
15738 ((eq value 'later) (org-timestamp-change 1 'day))
15739 (t (call-interactively 'org-deadline)))
15740 (call-interactively 'org-deadline)))
15741 ((member property org-special-properties)
15742 (error "The %s property can not yet be set with `org-entry-put'"
15743 property))
15744 (t ; a non-special property
15745 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15746 (setq range (org-get-property-block beg end 'force))
15747 (goto-char (car range))
15748 (if (re-search-forward
15749 (org-re-property property) (cdr range) t)
15750 (progn
15751 (delete-region (match-beginning 0) (match-end 0))
15752 (goto-char (match-beginning 0)))
15753 (goto-char (cdr range))
15754 (insert "\n")
15755 (backward-char 1)
15756 (org-indent-line))
15757 (insert ":" property ":")
15758 (and value (insert " " value))
15759 (org-indent-line)))))
15760 (run-hook-with-args 'org-property-changed-functions property value)))
15762 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15763 "Get all property keys in the current buffer.
15764 With INCLUDE-SPECIALS, also list the special properties that reflect things
15765 like tags and TODO state.
15766 With INCLUDE-DEFAULTS, also include properties that has special meaning
15767 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15768 and others.
15769 With INCLUDE-COLUMNS, also include property names given in COLUMN
15770 formats in the current buffer."
15771 (let (rtn range cfmt s p)
15772 (save-excursion
15773 (save-restriction
15774 (widen)
15775 (goto-char (point-min))
15776 (while (re-search-forward org-property-start-re nil t)
15777 (catch 'cont
15778 (setq range (or (org-get-property-block)
15779 (if (y-or-n-p
15780 (format "Malformed drawer at %d, repair?" (point)))
15781 (org-get-property-block nil nil t)
15782 (throw 'cont nil))))
15783 (goto-char (car range))
15784 (while (re-search-forward org-property-re
15785 (cdr range) t)
15786 (add-to-list 'rtn (org-match-string-no-properties 2)))
15787 (outline-next-heading)))))
15789 (when include-specials
15790 (setq rtn (append org-special-properties rtn)))
15792 (when include-defaults
15793 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15794 (add-to-list 'rtn org-effort-property))
15796 (when include-columns
15797 (save-excursion
15798 (save-restriction
15799 (widen)
15800 (goto-char (point-min))
15801 (while (re-search-forward
15802 "^[ \t]*\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15803 nil t)
15804 (setq cfmt (match-string 2) s 0)
15805 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15806 cfmt s)
15807 (setq s (match-end 0)
15808 p (match-string 1 cfmt))
15809 (unless (or (equal p "ITEM")
15810 (member p org-special-properties))
15811 (add-to-list 'rtn (match-string 1 cfmt))))))))
15813 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15815 (defun org-property-values (key)
15816 "Return a list of all values of property KEY in the current buffer."
15817 (save-excursion
15818 (save-restriction
15819 (widen)
15820 (goto-char (point-min))
15821 (let ((re (org-re-property key))
15822 values)
15823 (while (re-search-forward re nil t)
15824 (add-to-list 'values (org-trim (match-string 3))))
15825 (delete "" values)))))
15827 (defun org-insert-property-drawer ()
15828 "Insert a property drawer into the current entry."
15829 (org-back-to-heading t)
15830 (looking-at org-outline-regexp)
15831 (let ((indent (if org-adapt-indentation
15832 (- (match-end 0) (match-beginning 0))
15834 (beg (point))
15835 (re (concat "^[ \t]*" org-keyword-time-regexp))
15836 end hiddenp)
15837 (outline-next-heading)
15838 (setq end (point))
15839 (goto-char beg)
15840 (while (re-search-forward re end t))
15841 (setq hiddenp (outline-invisible-p))
15842 (end-of-line 1)
15843 (and (equal (char-after) ?\n) (forward-char 1))
15844 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15845 (if (member (match-string 1) '("CLOCK:" ":END:"))
15846 ;; just skip this line
15847 (beginning-of-line 2)
15848 ;; Drawer start, find the end
15849 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15850 (beginning-of-line 1)))
15851 (org-skip-over-state-notes)
15852 (skip-chars-backward " \t\n\r")
15853 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15854 (forward-char 1))
15855 (goto-char (point-at-eol))
15856 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15857 (beginning-of-line 0)
15858 (org-indent-to-column indent)
15859 (beginning-of-line 2)
15860 (org-indent-to-column indent)
15861 (beginning-of-line 0)
15862 (if hiddenp
15863 (save-excursion
15864 (org-back-to-heading t)
15865 (hide-entry))
15866 (org-flag-drawer t))))
15868 (defun org-insert-drawer (&optional arg drawer)
15869 "Insert a drawer at point.
15871 Optional argument DRAWER, when non-nil, is a string representing
15872 drawer's name. Otherwise, the user is prompted for a name.
15874 If a region is active, insert the drawer around that region
15875 instead.
15877 Point is left between drawer's boundaries."
15878 (interactive "P")
15879 (let* ((drawer (if arg "PROPERTIES"
15880 (or drawer (read-from-minibuffer "Drawer: ")))))
15881 (cond
15882 ;; With C-u, fall back on `org-insert-property-drawer'
15883 (arg (org-insert-property-drawer))
15885 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15886 (user-error "Invalid drawer name"))
15887 ;; With an active region, insert a drawer at point.
15888 ((not (org-region-active-p))
15889 (progn
15890 (unless (bolp) (insert "\n"))
15891 (insert (format ":%s:\n\n:END:\n" drawer))
15892 (forward-line -2)))
15893 ;; Otherwise, insert the drawer at point
15895 (let ((rbeg (region-beginning))
15896 (rend (copy-marker (region-end))))
15897 (unwind-protect
15898 (progn
15899 (goto-char rbeg)
15900 (beginning-of-line)
15901 (when (save-excursion
15902 (re-search-forward org-outline-regexp-bol rend t))
15903 (user-error "Drawers cannot contain headlines"))
15904 ;; Position point at the beginning of the first
15905 ;; non-blank line in region. Insert drawer's opening
15906 ;; there, then indent it.
15907 (org-skip-whitespace)
15908 (beginning-of-line)
15909 (insert ":" drawer ":\n")
15910 (forward-line -1)
15911 (indent-for-tab-command)
15912 ;; Move point to the beginning of the first blank line
15913 ;; after the last non-blank line in region. Insert
15914 ;; drawer's closing, then indent it.
15915 (goto-char rend)
15916 (skip-chars-backward " \r\t\n")
15917 (insert "\n:END:")
15918 (deactivate-mark t)
15919 (indent-for-tab-command)
15920 (unless (eolp) (insert "\n")))
15921 ;; Clear marker, whatever the outcome of insertion is.
15922 (set-marker rend nil)))))))
15924 (defvar org-property-set-functions-alist nil
15925 "Property set function alist.
15926 Each entry should have the following format:
15928 (PROPERTY . READ-FUNCTION)
15930 The read function will be called with the same argument as
15931 `org-completing-read'.")
15933 (defun org-set-property-function (property)
15934 "Get the function that should be used to set PROPERTY.
15935 This is computed according to `org-property-set-functions-alist'."
15936 (or (cdr (assoc property org-property-set-functions-alist))
15937 'org-completing-read))
15939 (defun org-read-property-value (property)
15940 "Read PROPERTY value from user."
15941 (let* ((completion-ignore-case t)
15942 (allowed (org-property-get-allowed-values nil property 'table))
15943 (cur (org-entry-get nil property))
15944 (prompt (concat property " value"
15945 (if (and cur (string-match "\\S-" cur))
15946 (concat " [" cur "]") "") ": "))
15947 (set-function (org-set-property-function property))
15948 (val (if allowed
15949 (funcall set-function prompt allowed nil
15950 (not (get-text-property 0 'org-unrestricted
15951 (caar allowed))))
15952 (let (org-completion-use-ido org-completion-use-iswitchb)
15953 (funcall set-function prompt
15954 (mapcar 'list (org-property-values property))
15955 nil nil "" nil cur)))))
15956 (if (equal val "")
15958 val)))
15960 (defvar org-last-set-property nil)
15961 (defvar org-last-set-property-value nil)
15962 (defun org-read-property-name ()
15963 "Read a property name."
15964 (let* ((completion-ignore-case t)
15965 (keys (org-buffer-property-keys nil t t))
15966 (default-prop (or (save-excursion
15967 (save-match-data
15968 (beginning-of-line)
15969 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15970 (null (string= (match-string 1) "END"))
15971 (match-string 1))))
15972 org-last-set-property))
15973 (property (org-icompleting-read
15974 (concat "Property"
15975 (if default-prop (concat " [" default-prop "]") "")
15976 ": ")
15977 (mapcar 'list keys)
15978 nil nil nil nil
15979 default-prop)))
15980 (if (member property keys)
15981 property
15982 (or (cdr (assoc (downcase property)
15983 (mapcar (lambda (x) (cons (downcase x) x))
15984 keys)))
15985 property))))
15987 (defun org-set-property-and-value (use-last)
15988 "Allow to set [PROPERTY]: [value] direction from prompt.
15989 When use-default, don't even ask, just use the last
15990 \"[PROPERTY]: [value]\" string from the history."
15991 (interactive "P")
15992 (let* ((completion-ignore-case t)
15993 (pv (or (and use-last org-last-set-property-value)
15994 (org-completing-read
15995 "Enter a \"[Property]: [value]\" pair: "
15996 nil nil nil nil nil
15997 org-last-set-property-value)))
15998 prop val)
15999 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16000 (setq prop (match-string 1 pv)
16001 val (match-string 2 pv))
16002 (org-set-property prop val))))
16004 (defun org-set-property (property value)
16005 "In the current entry, set PROPERTY to VALUE.
16006 When called interactively, this will prompt for a property name, offering
16007 completion on existing and default properties. And then it will prompt
16008 for a value, offering completion either on allowed values (via an inherited
16009 xxx_ALL property) or on existing values in other instances of this property
16010 in the current file."
16011 (interactive (list nil nil))
16012 (let* ((property (or property (org-read-property-name)))
16013 (value (or value (org-read-property-value property)))
16014 (fn (cdr (assoc property org-properties-postprocess-alist))))
16015 (setq org-last-set-property property)
16016 (setq org-last-set-property-value (concat property ": " value))
16017 ;; Possibly postprocess the inserted value:
16018 (when fn (setq value (funcall fn value)))
16019 (unless (equal (org-entry-get nil property) value)
16020 (org-entry-put nil property value))))
16022 (defun org-delete-property (property)
16023 "In the current entry, delete PROPERTY."
16024 (interactive
16025 (let* ((completion-ignore-case t)
16026 (cat (org-entry-get (point) "CATEGORY"))
16027 (props0 (org-entry-properties nil 'standard))
16028 (props (if cat props0
16029 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16030 (prop (if (< 1 (length props))
16031 (org-icompleting-read "Property: " props nil t)
16032 (caar props))))
16033 (list prop)))
16034 (if (org-entry-delete nil property)
16035 (message "Property %s deleted" property)))
16037 (defun org-delete-property-globally (property)
16038 "Remove PROPERTY globally, from all entries."
16039 (interactive
16040 (let* ((completion-ignore-case t)
16041 (prop (org-icompleting-read
16042 "Globally remove property: "
16043 (mapcar 'list (org-buffer-property-keys)))))
16044 (list prop)))
16045 (save-excursion
16046 (save-restriction
16047 (widen)
16048 (goto-char (point-min))
16049 (let ((cnt 0))
16050 (while (re-search-forward
16051 (org-re-property property)
16052 nil t)
16053 (setq cnt (1+ cnt))
16054 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16055 (message "Property \"%s\" removed from %d entries" property cnt)))))
16057 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16059 (defun org-compute-property-at-point ()
16060 "Compute the property at point.
16061 This looks for an enclosing column format, extracts the operator and
16062 then applies it to the property in the column format's scope."
16063 (interactive)
16064 (unless (org-at-property-p)
16065 (user-error "Not at a property"))
16066 (let ((prop (org-match-string-no-properties 2)))
16067 (org-columns-get-format-and-top-level)
16068 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16069 (user-error "No operator defined for property %s" prop))
16070 (org-columns-compute prop)))
16072 (defvar org-property-allowed-value-functions nil
16073 "Hook for functions supplying allowed values for a specific property.
16074 The functions must take a single argument, the name of the property, and
16075 return a flat list of allowed values. If \":ETC\" is one of
16076 the values, this means that these values are intended as defaults for
16077 completion, but that other values should be allowed too.
16078 The functions must return nil if they are not responsible for this
16079 property.")
16081 (defun org-property-get-allowed-values (pom property &optional table)
16082 "Get allowed values for the property PROPERTY.
16083 When TABLE is non-nil, return an alist that can directly be used for
16084 completion."
16085 (let (vals)
16086 (cond
16087 ((equal property "TODO")
16088 (setq vals (org-with-point-at pom
16089 (append org-todo-keywords-1 '("")))))
16090 ((equal property "PRIORITY")
16091 (let ((n org-lowest-priority))
16092 (while (>= n org-highest-priority)
16093 (push (char-to-string n) vals)
16094 (setq n (1- n)))))
16095 ((member property org-special-properties))
16096 ((setq vals (run-hook-with-args-until-success
16097 'org-property-allowed-value-functions property)))
16099 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16100 (when (and vals (string-match "\\S-" vals))
16101 (setq vals (car (read-from-string (concat "(" vals ")"))))
16102 (setq vals (mapcar (lambda (x)
16103 (cond ((stringp x) x)
16104 ((numberp x) (number-to-string x))
16105 ((symbolp x) (symbol-name x))
16106 (t "???")))
16107 vals)))))
16108 (when (member ":ETC" vals)
16109 (setq vals (remove ":ETC" vals))
16110 (org-add-props (car vals) '(org-unrestricted t)))
16111 (if table (mapcar 'list vals) vals)))
16113 (defun org-property-previous-allowed-value (&optional previous)
16114 "Switch to the next allowed value for this property."
16115 (interactive)
16116 (org-property-next-allowed-value t))
16118 (defun org-property-next-allowed-value (&optional previous)
16119 "Switch to the next allowed value for this property."
16120 (interactive)
16121 (unless (org-at-property-p)
16122 (user-error "Not at a property"))
16123 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16124 (key (match-string 2))
16125 (value (match-string 3))
16126 (allowed (or (org-property-get-allowed-values (point) key)
16127 (and (member value '("[ ]" "[-]" "[X]"))
16128 '("[ ]" "[X]"))))
16129 (heading (save-match-data (nth 4 (org-heading-components))))
16130 nval)
16131 (unless allowed
16132 (user-error "Allowed values for this property have not been defined"))
16133 (if previous (setq allowed (reverse allowed)))
16134 (if (member value allowed)
16135 (setq nval (car (cdr (member value allowed)))))
16136 (setq nval (or nval (car allowed)))
16137 (if (equal nval value)
16138 (user-error "Only one allowed value for this property"))
16139 (org-at-property-p)
16140 (replace-match (concat " :" key ": " nval) t t)
16141 (org-indent-line)
16142 (beginning-of-line 1)
16143 (skip-chars-forward " \t")
16144 (when (equal prop org-effort-property)
16145 (save-excursion
16146 (org-back-to-heading t)
16147 (put-text-property (point-at-bol) (point-at-eol) 'effort nval)
16148 (put-text-property (point-at-bol) (point-at-eol) 'effort-minutes
16149 (org-duration-string-to-minutes nval)))
16150 (when (string= org-clock-current-task heading)
16151 (setq org-clock-effort nval)
16152 (org-clock-update-mode-line)))
16153 (run-hook-with-args 'org-property-changed-functions key nval)))
16155 (defun org-find-olp (path &optional this-buffer)
16156 "Return a marker pointing to the entry at outline path OLP.
16157 If anything goes wrong, throw an error.
16158 You can wrap this call to catch the error like this:
16160 (condition-case msg
16161 (org-mobile-locate-entry (match-string 4))
16162 (error (nth 1 msg)))
16164 The return value will then be either a string with the error message,
16165 or a marker if everything is OK.
16167 If THIS-BUFFER is set, the outline path does not contain a file,
16168 only headings."
16169 (let* ((file (if this-buffer buffer-file-name (pop path)))
16170 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16171 (level 1)
16172 (lmin 1)
16173 (lmax 1)
16174 limit re end found pos heading cnt flevel)
16175 (unless buffer (error "File not found :%s" file))
16176 (with-current-buffer buffer
16177 (save-excursion
16178 (save-restriction
16179 (widen)
16180 (setq limit (point-max))
16181 (goto-char (point-min))
16182 (while (setq heading (pop path))
16183 (setq re (format org-complex-heading-regexp-format
16184 (regexp-quote heading)))
16185 (setq cnt 0 pos (point))
16186 (while (re-search-forward re end t)
16187 (setq level (- (match-end 1) (match-beginning 1)))
16188 (if (and (>= level lmin) (<= level lmax))
16189 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16190 (when (= cnt 0) (error "Heading not found on level %d: %s"
16191 lmax heading))
16192 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16193 lmax heading))
16194 (goto-char found)
16195 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16196 (setq end (save-excursion (org-end-of-subtree t t))))
16197 (when (org-at-heading-p)
16198 (point-marker)))))))
16200 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16201 "Find node HEADING in BUFFER.
16202 Return a marker to the heading if it was found, or nil if not.
16203 If POS-ONLY is set, return just the position instead of a marker.
16205 The heading text must match exact, but it may have a TODO keyword,
16206 a priority cookie and tags in the standard locations."
16207 (with-current-buffer (or buffer (current-buffer))
16208 (save-excursion
16209 (save-restriction
16210 (widen)
16211 (goto-char (point-min))
16212 (let (case-fold-search)
16213 (if (re-search-forward
16214 (format org-complex-heading-regexp-format
16215 (regexp-quote heading)) nil t)
16216 (if pos-only
16217 (match-beginning 0)
16218 (move-marker (make-marker) (match-beginning 0)))))))))
16220 (defun org-find-exact-heading-in-directory (heading &optional dir)
16221 "Find Org node headline HEADING in all .org files in directory DIR.
16222 When the target headline is found, return a marker to this location."
16223 (let ((files (directory-files (or dir default-directory)
16224 t "\\`[^.#].*\\.org\\'"))
16225 file visiting m buffer)
16226 (catch 'found
16227 (while (setq file (pop files))
16228 (message "trying %s" file)
16229 (setq visiting (org-find-base-buffer-visiting file))
16230 (setq buffer (or visiting (find-file-noselect file)))
16231 (setq m (org-find-exact-headline-in-buffer
16232 heading buffer))
16233 (when (and (not m) (not visiting)) (kill-buffer buffer))
16234 (and m (throw 'found m))))))
16236 (defun org-find-entry-with-id (ident)
16237 "Locate the entry that contains the ID property with exact value IDENT.
16238 IDENT can be a string, a symbol or a number, this function will search for
16239 the string representation of it.
16240 Return the position where this entry starts, or nil if there is no such entry."
16241 (interactive "sID: ")
16242 (let ((id (cond
16243 ((stringp ident) ident)
16244 ((symbol-name ident) (symbol-name ident))
16245 ((numberp ident) (number-to-string ident))
16246 (t (error "IDENT %s must be a string, symbol or number" ident))))
16247 (case-fold-search nil))
16248 (save-excursion
16249 (save-restriction
16250 (widen)
16251 (goto-char (point-min))
16252 (when (re-search-forward
16253 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16254 nil t)
16255 (org-back-to-heading t)
16256 (point))))))
16258 ;;;; Timestamps
16260 (defvar org-last-changed-timestamp nil)
16261 (defvar org-last-inserted-timestamp nil
16262 "The last time stamp inserted with `org-insert-time-stamp'.")
16263 (defvar org-ts-what) ; dynamically scoped parameter
16265 (defun org-time-stamp (arg &optional inactive)
16266 "Prompt for a date/time and insert a time stamp.
16267 If the user specifies a time like HH:MM or if this command is
16268 called with at least one prefix argument, the time stamp contains
16269 the date and the time. Otherwise, only the date is be included.
16271 All parts of a date not specified by the user is filled in from
16272 the current date/time. So if you just press return without
16273 typing anything, the time stamp will represent the current
16274 date/time.
16276 If there is already a timestamp at the cursor, it will be
16277 modified.
16279 With two universal prefix arguments, insert an active timestamp
16280 with the current time without prompting the user.
16282 When called from lisp, the timestamp is inactive if INACTIVE is
16283 non-nil."
16284 (interactive "P")
16285 (let* ((ts nil)
16286 (default-time
16287 ;; Default time is either today, or, when entering a range,
16288 ;; the range start.
16289 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16290 (save-excursion
16291 (re-search-backward
16292 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16293 (- (point) 20) t)))
16294 (apply 'encode-time (org-parse-time-string (match-string 1)))
16295 (current-time)))
16296 (default-input (and ts (org-get-compact-tod ts)))
16297 (repeater (save-excursion
16298 (save-match-data
16299 (beginning-of-line)
16300 (when (re-search-forward
16301 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16302 (save-excursion (progn (end-of-line) (point))) t)
16303 (match-string 0)))))
16304 org-time-was-given org-end-time-was-given time)
16305 (cond
16306 ((and (org-at-timestamp-p t)
16307 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16308 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16309 (insert "--")
16310 (setq time (let ((this-command this-command))
16311 (org-read-date arg 'totime nil nil
16312 default-time default-input inactive)))
16313 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16314 ((org-at-timestamp-p t)
16315 (setq time (let ((this-command this-command))
16316 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16317 (when (org-at-timestamp-p t) ; just to get the match data
16318 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16319 (replace-match "")
16320 (setq org-last-changed-timestamp
16321 (org-insert-time-stamp
16322 time (or org-time-was-given arg)
16323 inactive nil nil (list org-end-time-was-given)))
16324 (when repeater (goto-char (1- (point))) (insert " " repeater)
16325 (setq org-last-changed-timestamp
16326 (concat (substring org-last-inserted-timestamp 0 -1)
16327 " " repeater ">"))))
16328 (message "Timestamp updated"))
16329 ((equal arg '(16))
16330 (org-insert-time-stamp (current-time) t inactive))
16332 (setq time (let ((this-command this-command))
16333 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16334 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16335 nil nil (list org-end-time-was-given))))))
16337 ;; FIXME: can we use this for something else, like computing time differences?
16338 (defun org-get-compact-tod (s)
16339 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16340 (let* ((t1 (match-string 1 s))
16341 (h1 (string-to-number (match-string 2 s)))
16342 (m1 (string-to-number (match-string 3 s)))
16343 (t2 (and (match-end 4) (match-string 5 s)))
16344 (h2 (and t2 (string-to-number (match-string 6 s))))
16345 (m2 (and t2 (string-to-number (match-string 7 s))))
16346 dh dm)
16347 (if (not t2)
16349 (setq dh (- h2 h1) dm (- m2 m1))
16350 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16351 (concat t1 "+" (number-to-string dh)
16352 (and (/= 0 dm) (format ":%02d" dm)))))))
16354 (defun org-time-stamp-inactive (&optional arg)
16355 "Insert an inactive time stamp.
16356 An inactive time stamp is enclosed in square brackets instead of angle
16357 brackets. It is inactive in the sense that it does not trigger agenda entries,
16358 does not link to the calendar and cannot be changed with the S-cursor keys.
16359 So these are more for recording a certain time/date."
16360 (interactive "P")
16361 (org-time-stamp arg 'inactive))
16363 (defvar org-date-ovl (make-overlay 1 1))
16364 (overlay-put org-date-ovl 'face 'org-date-selected)
16365 (org-detach-overlay org-date-ovl)
16367 (defvar org-ans1) ; dynamically scoped parameter
16368 (defvar org-ans2) ; dynamically scoped parameter
16370 (defvar org-plain-time-of-day-regexp) ; defined below
16372 (defvar org-overriding-default-time nil) ; dynamically scoped
16373 (defvar org-read-date-overlay nil)
16374 (defvar org-dcst nil) ; dynamically scoped
16375 (defvar org-read-date-history nil)
16376 (defvar org-read-date-final-answer nil)
16377 (defvar org-read-date-analyze-futurep nil)
16378 (defvar org-read-date-analyze-forced-year nil)
16379 (defvar org-read-date-inactive)
16381 (defvar org-read-date-minibuffer-local-map
16382 (let* ((org-replace-disputed-keys nil)
16383 (map (make-sparse-keymap)))
16384 (set-keymap-parent map minibuffer-local-map)
16385 (org-defkey map (kbd ".")
16386 (lambda () (interactive)
16387 ;; Are we at the beginning of the prompt?
16388 (if (looking-back "^[^:]+: ")
16389 (org-eval-in-calendar '(calendar-goto-today))
16390 (insert "."))))
16391 (org-defkey map (kbd "C-.")
16392 (lambda () (interactive)
16393 (org-eval-in-calendar '(calendar-goto-today))))
16394 (org-defkey map [(meta shift left)]
16395 (lambda () (interactive)
16396 (org-eval-in-calendar '(calendar-backward-month 1))))
16397 (org-defkey map [(meta shift right)]
16398 (lambda () (interactive)
16399 (org-eval-in-calendar '(calendar-forward-month 1))))
16400 (org-defkey map [(meta shift up)]
16401 (lambda () (interactive)
16402 (org-eval-in-calendar '(calendar-backward-year 1))))
16403 (org-defkey map [(meta shift down)]
16404 (lambda () (interactive)
16405 (org-eval-in-calendar '(calendar-forward-year 1))))
16406 (org-defkey map [?\e (shift left)]
16407 (lambda () (interactive)
16408 (org-eval-in-calendar '(calendar-backward-month 1))))
16409 (org-defkey map [?\e (shift right)]
16410 (lambda () (interactive)
16411 (org-eval-in-calendar '(calendar-forward-month 1))))
16412 (org-defkey map [?\e (shift up)]
16413 (lambda () (interactive)
16414 (org-eval-in-calendar '(calendar-backward-year 1))))
16415 (org-defkey map [?\e (shift down)]
16416 (lambda () (interactive)
16417 (org-eval-in-calendar '(calendar-forward-year 1))))
16418 (org-defkey map [(shift up)]
16419 (lambda () (interactive)
16420 (org-eval-in-calendar '(calendar-backward-week 1))))
16421 (org-defkey map [(shift down)]
16422 (lambda () (interactive)
16423 (org-eval-in-calendar '(calendar-forward-week 1))))
16424 (org-defkey map [(shift left)]
16425 (lambda () (interactive)
16426 (org-eval-in-calendar '(calendar-backward-day 1))))
16427 (org-defkey map [(shift right)]
16428 (lambda () (interactive)
16429 (org-eval-in-calendar '(calendar-forward-day 1))))
16430 (org-defkey map "!"
16431 (lambda () (interactive)
16432 (org-eval-in-calendar '(diary-view-entries))
16433 (message "")))
16434 (org-defkey map ">"
16435 (lambda () (interactive)
16436 (org-eval-in-calendar '(scroll-calendar-left 1))))
16437 (org-defkey map "<"
16438 (lambda () (interactive)
16439 (org-eval-in-calendar '(scroll-calendar-right 1))))
16440 (org-defkey map "\C-v"
16441 (lambda () (interactive)
16442 (org-eval-in-calendar
16443 '(calendar-scroll-left-three-months 1))))
16444 (org-defkey map "\M-v"
16445 (lambda () (interactive)
16446 (org-eval-in-calendar
16447 '(calendar-scroll-right-three-months 1))))
16448 map)
16449 "Keymap for minibuffer commands when using `org-read-date'.")
16451 (defvar org-def)
16452 (defvar org-defdecode)
16453 (defvar org-with-time)
16455 (defun org-read-date (&optional org-with-time to-time from-string prompt
16456 default-time default-input inactive)
16457 "Read a date, possibly a time, and make things smooth for the user.
16458 The prompt will suggest to enter an ISO date, but you can also enter anything
16459 which will at least partially be understood by `parse-time-string'.
16460 Unrecognized parts of the date will default to the current day, month, year,
16461 hour and minute. If this command is called to replace a timestamp at point,
16462 or to enter the second timestamp of a range, the default time is taken
16463 from the existing stamp. Furthermore, the command prefers the future,
16464 so if you are giving a date where the year is not given, and the day-month
16465 combination is already past in the current year, it will assume you
16466 mean next year. For details, see the manual. A few examples:
16468 3-2-5 --> 2003-02-05
16469 feb 15 --> currentyear-02-15
16470 2/15 --> currentyear-02-15
16471 sep 12 9 --> 2009-09-12
16472 12:45 --> today 12:45
16473 22 sept 0:34 --> currentyear-09-22 0:34
16474 12 --> currentyear-currentmonth-12
16475 Fri --> nearest Friday after today
16476 -Tue --> last Tuesday
16477 etc.
16479 Furthermore you can specify a relative date by giving, as the *first* thing
16480 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16481 change in days weeks, months, years.
16482 With a single plus or minus, the date is relative to today. With a double
16483 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16484 +4d --> four days from today
16485 +4 --> same as above
16486 +2w --> two weeks from today
16487 ++5 --> five days from default date
16489 The function understands only English month and weekday abbreviations.
16491 While prompting, a calendar is popped up - you can also select the
16492 date with the mouse (button 1). The calendar shows a period of three
16493 months. To scroll it to other months, use the keys `>' and `<'.
16494 If you don't like the calendar, turn it off with
16495 \(setq org-read-date-popup-calendar nil)
16497 With optional argument TO-TIME, the date will immediately be converted
16498 to an internal time.
16499 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16500 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16501 still enter a time, and this function will inform the calling routine
16502 about this change. The calling routine may then choose to change the
16503 format used to insert the time stamp into the buffer to include the time.
16504 With optional argument FROM-STRING, read from this string instead from
16505 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16506 the time/date that is used for everything that is not specified by the
16507 user."
16508 (require 'parse-time)
16509 (let* ((org-time-stamp-rounding-minutes
16510 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16511 (org-dcst org-display-custom-times)
16512 (ct (org-current-time))
16513 (org-def (or org-overriding-default-time default-time ct))
16514 (org-defdecode (decode-time org-def))
16515 (dummy (progn
16516 (when (< (nth 2 org-defdecode) org-extend-today-until)
16517 (setcar (nthcdr 2 org-defdecode) -1)
16518 (setcar (nthcdr 1 org-defdecode) 59)
16519 (setq org-def (apply 'encode-time org-defdecode)
16520 org-defdecode (decode-time org-def)))))
16521 (mouse-autoselect-window nil) ; Don't let the mouse jump
16522 (calendar-frame-setup nil)
16523 (calendar-setup nil)
16524 (calendar-move-hook nil)
16525 (calendar-view-diary-initially-flag nil)
16526 (calendar-view-holidays-initially-flag nil)
16527 (timestr (format-time-string
16528 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16529 (prompt (concat (if prompt (concat prompt " ") "")
16530 (format "Date+time [%s]: " timestr)))
16531 ans (org-ans0 "") org-ans1 org-ans2 final)
16533 (cond
16534 (from-string (setq ans from-string))
16535 (org-read-date-popup-calendar
16536 (save-excursion
16537 (save-window-excursion
16538 (calendar)
16539 (org-eval-in-calendar '(setq cursor-type nil) t)
16540 (unwind-protect
16541 (progn
16542 (calendar-forward-day (- (time-to-days org-def)
16543 (calendar-absolute-from-gregorian
16544 (calendar-current-date))))
16545 (org-eval-in-calendar nil t)
16546 (let* ((old-map (current-local-map))
16547 (map (copy-keymap calendar-mode-map))
16548 (minibuffer-local-map
16549 (copy-keymap org-read-date-minibuffer-local-map)))
16550 (org-defkey map (kbd "RET") 'org-calendar-select)
16551 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16552 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16553 (unwind-protect
16554 (progn
16555 (use-local-map map)
16556 (setq org-read-date-inactive inactive)
16557 (add-hook 'post-command-hook 'org-read-date-display)
16558 (setq org-ans0 (read-string prompt default-input
16559 'org-read-date-history nil))
16560 ;; org-ans0: from prompt
16561 ;; org-ans1: from mouse click
16562 ;; org-ans2: from calendar motion
16563 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16564 (remove-hook 'post-command-hook 'org-read-date-display)
16565 (use-local-map old-map)
16566 (when org-read-date-overlay
16567 (delete-overlay org-read-date-overlay)
16568 (setq org-read-date-overlay nil)))))
16569 (bury-buffer "*Calendar*")))))
16571 (t ; Naked prompt only
16572 (unwind-protect
16573 (setq ans (read-string prompt default-input
16574 'org-read-date-history timestr))
16575 (when org-read-date-overlay
16576 (delete-overlay org-read-date-overlay)
16577 (setq org-read-date-overlay nil)))))
16579 (setq final (org-read-date-analyze ans org-def org-defdecode))
16581 (when org-read-date-analyze-forced-year
16582 (message "Year was forced into %s"
16583 (if org-read-date-force-compatible-dates
16584 "compatible range (1970-2037)"
16585 "range representable on this machine"))
16586 (ding))
16588 ;; One round trip to get rid of 34th of August and stuff like that....
16589 (setq final (decode-time (apply 'encode-time final)))
16591 (setq org-read-date-final-answer ans)
16593 (if to-time
16594 (apply 'encode-time final)
16595 (if (and (boundp 'org-time-was-given) org-time-was-given)
16596 (format "%04d-%02d-%02d %02d:%02d"
16597 (nth 5 final) (nth 4 final) (nth 3 final)
16598 (nth 2 final) (nth 1 final))
16599 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16601 (defun org-read-date-display ()
16602 "Display the current date prompt interpretation in the minibuffer."
16603 (when org-read-date-display-live
16604 (when org-read-date-overlay
16605 (delete-overlay org-read-date-overlay))
16606 (when (minibufferp (current-buffer))
16607 (save-excursion
16608 (end-of-line 1)
16609 (while (not (equal (buffer-substring
16610 (max (point-min) (- (point) 4)) (point))
16611 " "))
16612 (insert " ")))
16613 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16614 " " (or org-ans1 org-ans2)))
16615 (org-end-time-was-given nil)
16616 (f (org-read-date-analyze ans org-def org-defdecode))
16617 (fmts (if org-dcst
16618 org-time-stamp-custom-formats
16619 org-time-stamp-formats))
16620 (fmt (if (or org-with-time
16621 (and (boundp 'org-time-was-given) org-time-was-given))
16622 (cdr fmts)
16623 (car fmts)))
16624 (txt (format-time-string fmt (apply 'encode-time f)))
16625 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16626 (txt (concat "=> " txt)))
16627 (when (and org-end-time-was-given
16628 (string-match org-plain-time-of-day-regexp txt))
16629 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16630 org-end-time-was-given
16631 (substring txt (match-end 0)))))
16632 (when org-read-date-analyze-futurep
16633 (setq txt (concat txt " (=>F)")))
16634 (setq org-read-date-overlay
16635 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16636 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16638 (defun org-read-date-analyze (ans org-def org-defdecode)
16639 "Analyze the combined answer of the date prompt."
16640 ;; FIXME: cleanup and comment
16641 (let ((nowdecode (decode-time (current-time)))
16642 delta deltan deltaw deltadef year month day
16643 hour minute second wday pm h2 m2 tl wday1
16644 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16645 (setq org-read-date-analyze-futurep nil
16646 org-read-date-analyze-forced-year nil)
16647 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16648 (setq ans "+0"))
16650 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16651 (setq ans (replace-match "" t t ans)
16652 deltan (car delta)
16653 deltaw (nth 1 delta)
16654 deltadef (nth 2 delta)))
16656 ;; Check if there is an iso week date in there. If yes, store the
16657 ;; info and postpone interpreting it until the rest of the parsing
16658 ;; is done.
16659 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16660 (setq iso-year (if (match-end 1)
16661 (org-small-year-to-year
16662 (string-to-number (match-string 1 ans))))
16663 iso-weekday (if (match-end 3)
16664 (string-to-number (match-string 3 ans)))
16665 iso-week (string-to-number (match-string 2 ans)))
16666 (setq ans (replace-match "" t t ans)))
16668 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16669 (when (string-match
16670 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16671 (setq year (if (match-end 2)
16672 (string-to-number (match-string 2 ans))
16673 (progn (setq kill-year t)
16674 (string-to-number (format-time-string "%Y"))))
16675 month (string-to-number (match-string 3 ans))
16676 day (string-to-number (match-string 4 ans)))
16677 (if (< year 100) (setq year (+ 2000 year)))
16678 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16679 t nil ans)))
16681 ;; Help matching dotted european dates
16682 (when (string-match
16683 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16684 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16685 (setq kill-year t)
16686 (string-to-number (format-time-string "%Y")))
16687 day (string-to-number (match-string 1 ans))
16688 month (string-to-number (match-string 2 ans))
16689 ans (replace-match (format "%04d-%02d-%02d" year month day)
16690 t nil ans)))
16692 ;; Help matching american dates, like 5/30 or 5/30/7
16693 (when (string-match
16694 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16695 (setq year (if (match-end 4)
16696 (string-to-number (match-string 4 ans))
16697 (progn (setq kill-year t)
16698 (string-to-number (format-time-string "%Y"))))
16699 month (string-to-number (match-string 1 ans))
16700 day (string-to-number (match-string 2 ans)))
16701 (if (< year 100) (setq year (+ 2000 year)))
16702 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16703 t nil ans)))
16704 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16705 ;; If there is a time with am/pm, and *no* time without it, we convert
16706 ;; so that matching will be successful.
16707 (loop for i from 1 to 2 do ; twice, for end time as well
16708 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16709 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16710 (setq hour (string-to-number (match-string 1 ans))
16711 minute (if (match-end 3)
16712 (string-to-number (match-string 3 ans))
16714 pm (equal ?p
16715 (string-to-char (downcase (match-string 4 ans)))))
16716 (if (and (= hour 12) (not pm))
16717 (setq hour 0)
16718 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16719 (setq ans (replace-match (format "%02d:%02d" hour minute)
16720 t t ans))))
16722 ;; Check if a time range is given as a duration
16723 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16724 (setq hour (string-to-number (match-string 1 ans))
16725 h2 (+ hour (string-to-number (match-string 3 ans)))
16726 minute (string-to-number (match-string 2 ans))
16727 m2 (+ minute (if (match-end 5) (string-to-number
16728 (match-string 5 ans))0)))
16729 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16730 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16731 t t ans)))
16733 ;; Check if there is a time range
16734 (when (boundp 'org-end-time-was-given)
16735 (setq org-time-was-given nil)
16736 (when (and (string-match org-plain-time-of-day-regexp ans)
16737 (match-end 8))
16738 (setq org-end-time-was-given (match-string 8 ans))
16739 (setq ans (concat (substring ans 0 (match-beginning 7))
16740 (substring ans (match-end 7))))))
16742 (setq tl (parse-time-string ans)
16743 day (or (nth 3 tl) (nth 3 org-defdecode))
16744 month (or (nth 4 tl)
16745 (if (and org-read-date-prefer-future
16746 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16747 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16748 (nth 4 org-defdecode)))
16749 year (or (and (not kill-year) (nth 5 tl))
16750 (if (and org-read-date-prefer-future
16751 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16752 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16753 (nth 5 org-defdecode)))
16754 hour (or (nth 2 tl) (nth 2 org-defdecode))
16755 minute (or (nth 1 tl) (nth 1 org-defdecode))
16756 second (or (nth 0 tl) 0)
16757 wday (nth 6 tl))
16759 (when (and (eq org-read-date-prefer-future 'time)
16760 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16761 (equal day (nth 3 nowdecode))
16762 (equal month (nth 4 nowdecode))
16763 (equal year (nth 5 nowdecode))
16764 (nth 2 tl)
16765 (or (< (nth 2 tl) (nth 2 nowdecode))
16766 (and (= (nth 2 tl) (nth 2 nowdecode))
16767 (nth 1 tl)
16768 (< (nth 1 tl) (nth 1 nowdecode)))))
16769 (setq day (1+ day)
16770 futurep t))
16772 ;; Special date definitions below
16773 (cond
16774 (iso-week
16775 ;; There was an iso week
16776 (require 'cal-iso)
16777 (setq futurep nil)
16778 (setq year (or iso-year year)
16779 day (or iso-weekday wday 1)
16780 wday nil ; to make sure that the trigger below does not match
16781 iso-date (calendar-gregorian-from-absolute
16782 (calendar-absolute-from-iso
16783 (list iso-week day year))))
16784 ; FIXME: Should we also push ISO weeks into the future?
16785 ; (when (and org-read-date-prefer-future
16786 ; (not iso-year)
16787 ; (< (calendar-absolute-from-gregorian iso-date)
16788 ; (time-to-days (current-time))))
16789 ; (setq year (1+ year)
16790 ; iso-date (calendar-gregorian-from-absolute
16791 ; (calendar-absolute-from-iso
16792 ; (list iso-week day year)))))
16793 (setq month (car iso-date)
16794 year (nth 2 iso-date)
16795 day (nth 1 iso-date)))
16796 (deltan
16797 (setq futurep nil)
16798 (unless deltadef
16799 (let ((now (decode-time (current-time))))
16800 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16801 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16802 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16803 ((equal deltaw "m") (setq month (+ month deltan)))
16804 ((equal deltaw "y") (setq year (+ year deltan)))))
16805 ((and wday (not (nth 3 tl)))
16806 ;; Weekday was given, but no day, so pick that day in the week
16807 ;; on or after the derived date.
16808 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16809 (unless (equal wday wday1)
16810 (setq day (+ day (% (- wday wday1 -7) 7))))))
16811 (if (and (boundp 'org-time-was-given)
16812 (nth 2 tl))
16813 (setq org-time-was-given t))
16814 (if (< year 100) (setq year (+ 2000 year)))
16815 ;; Check of the date is representable
16816 (if org-read-date-force-compatible-dates
16817 (progn
16818 (if (< year 1970)
16819 (setq year 1970 org-read-date-analyze-forced-year t))
16820 (if (> year 2037)
16821 (setq year 2037 org-read-date-analyze-forced-year t)))
16822 (condition-case nil
16823 (ignore (encode-time second minute hour day month year))
16824 (error
16825 (setq year (nth 5 org-defdecode))
16826 (setq org-read-date-analyze-forced-year t))))
16827 (setq org-read-date-analyze-futurep futurep)
16828 (list second minute hour day month year)))
16830 (defvar parse-time-weekdays)
16831 (defun org-read-date-get-relative (s today default)
16832 "Check string S for special relative date string.
16833 TODAY and DEFAULT are internal times, for today and for a default.
16834 Return shift list (N what def-flag)
16835 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16836 N is the number of WHATs to shift.
16837 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16838 the DEFAULT date rather than TODAY."
16839 (require 'parse-time)
16840 (when (and
16841 (string-match
16842 (concat
16843 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16844 "\\([0-9]+\\)?"
16845 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16846 "\\([ \t]\\|$\\)") s)
16847 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16848 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16849 (string-to-char (substring (match-string 1 s) -1))
16850 ?+))
16851 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16852 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16853 (what (if (match-end 3) (match-string 3 s) "d"))
16854 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16855 (date (if rel default today))
16856 (wday (nth 6 (decode-time date)))
16857 delta)
16858 (if wday1
16859 (progn
16860 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16861 (if (= delta 0) (setq delta 7))
16862 (if (= dir ?-)
16863 (progn
16864 (setq delta (- delta 7))
16865 (if (= delta 0) (setq delta -7))))
16866 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16867 (list delta "d" rel))
16868 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16870 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16871 "Turn a user-specified date into the internal representation.
16872 The internal representation needed by the calendar is (month day year).
16873 This is a wrapper to handle the brain-dead convention in calendar that
16874 user function argument order change dependent on argument order."
16875 (if (boundp 'calendar-date-style)
16876 (cond
16877 ((eq calendar-date-style 'american)
16878 (list arg1 arg2 arg3))
16879 ((eq calendar-date-style 'european)
16880 (list arg2 arg1 arg3))
16881 ((eq calendar-date-style 'iso)
16882 (list arg2 arg3 arg1)))
16883 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16884 (if (org-bound-and-true-p european-calendar-style)
16885 (list arg2 arg1 arg3)
16886 (list arg1 arg2 arg3)))))
16888 (defun org-eval-in-calendar (form &optional keepdate)
16889 "Eval FORM in the calendar window and return to current window.
16890 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16891 otherwise stick to the current value of `org-ans2'."
16892 (let ((sf (selected-frame))
16893 (sw (selected-window)))
16894 (select-window (get-buffer-window "*Calendar*" t))
16895 (eval form)
16896 (when (and (not keepdate) (calendar-cursor-to-date))
16897 (let* ((date (calendar-cursor-to-date))
16898 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16899 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16900 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16901 (select-window sw)
16902 (org-select-frame-set-input-focus sf)))
16904 (defun org-calendar-select ()
16905 "Return to `org-read-date' with the date currently selected.
16906 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16907 (interactive)
16908 (when (calendar-cursor-to-date)
16909 (let* ((date (calendar-cursor-to-date))
16910 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16911 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16912 (if (active-minibuffer-window) (exit-minibuffer))))
16914 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16915 "Insert a date stamp for the date given by the internal TIME.
16916 WITH-HM means use the stamp format that includes the time of the day.
16917 INACTIVE means use square brackets instead of angular ones, so that the
16918 stamp will not contribute to the agenda.
16919 PRE and POST are optional strings to be inserted before and after the
16920 stamp.
16921 The command returns the inserted time stamp."
16922 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16923 stamp)
16924 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16925 (insert-before-markers (or pre ""))
16926 (when (listp extra)
16927 (setq extra (car extra))
16928 (if (and (stringp extra)
16929 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16930 (setq extra (format "-%02d:%02d"
16931 (string-to-number (match-string 1 extra))
16932 (string-to-number (match-string 2 extra))))
16933 (setq extra nil)))
16934 (when extra
16935 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16936 (insert-before-markers (setq stamp (format-time-string fmt time)))
16937 (insert-before-markers (or post ""))
16938 (setq org-last-inserted-timestamp stamp)))
16940 (defun org-toggle-time-stamp-overlays ()
16941 "Toggle the use of custom time stamp formats."
16942 (interactive)
16943 (setq org-display-custom-times (not org-display-custom-times))
16944 (unless org-display-custom-times
16945 (let ((p (point-min)) (bmp (buffer-modified-p)))
16946 (while (setq p (next-single-property-change p 'display))
16947 (if (and (get-text-property p 'display)
16948 (eq (get-text-property p 'face) 'org-date))
16949 (remove-text-properties
16950 p (setq p (next-single-property-change p 'display))
16951 '(display t))))
16952 (set-buffer-modified-p bmp)))
16953 (if (featurep 'xemacs)
16954 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16955 (org-restart-font-lock)
16956 (setq org-table-may-need-update t)
16957 (if org-display-custom-times
16958 (message "Time stamps are overlaid with custom format")
16959 (message "Time stamp overlays removed")))
16961 (defun org-display-custom-time (beg end)
16962 "Overlay modified time stamp format over timestamp between BEG and END."
16963 (let* ((ts (buffer-substring beg end))
16964 t1 w1 with-hm tf time str w2 (off 0))
16965 (save-match-data
16966 (setq t1 (org-parse-time-string ts t))
16967 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16968 (setq off (- (match-end 0) (match-beginning 0)))))
16969 (setq end (- end off))
16970 (setq w1 (- end beg)
16971 with-hm (and (nth 1 t1) (nth 2 t1))
16972 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16973 time (org-fix-decoded-time t1)
16974 str (org-add-props
16975 (format-time-string
16976 (substring tf 1 -1) (apply 'encode-time time))
16977 nil 'mouse-face 'highlight)
16978 w2 (length str))
16979 (if (not (= w2 w1))
16980 (add-text-properties (1+ beg) (+ 2 beg)
16981 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16982 (if (featurep 'xemacs)
16983 (progn
16984 (put-text-property beg end 'invisible t)
16985 (put-text-property beg end 'end-glyph (make-glyph str)))
16986 (put-text-property beg end 'display str))))
16988 (defun org-translate-time (string)
16989 "Translate all timestamps in STRING to custom format.
16990 But do this only if the variable `org-display-custom-times' is set."
16991 (when org-display-custom-times
16992 (save-match-data
16993 (let* ((start 0)
16994 (re org-ts-regexp-both)
16995 t1 with-hm inactive tf time str beg end)
16996 (while (setq start (string-match re string start))
16997 (setq beg (match-beginning 0)
16998 end (match-end 0)
16999 t1 (save-match-data
17000 (org-parse-time-string (substring string beg end) t))
17001 with-hm (and (nth 1 t1) (nth 2 t1))
17002 inactive (equal (substring string beg (1+ beg)) "[")
17003 tf (funcall (if with-hm 'cdr 'car)
17004 org-time-stamp-custom-formats)
17005 time (org-fix-decoded-time t1)
17006 str (format-time-string
17007 (concat
17008 (if inactive "[" "<") (substring tf 1 -1)
17009 (if inactive "]" ">"))
17010 (apply 'encode-time time))
17011 string (replace-match str t t string)
17012 start (+ start (length str)))))))
17013 string)
17015 (defun org-fix-decoded-time (time)
17016 "Set 0 instead of nil for the first 6 elements of time.
17017 Don't touch the rest."
17018 (let ((n 0))
17019 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17021 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17023 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17024 "Difference between TIMESTAMP-STRING and now in days.
17025 If SECONDS is non-nil, return the difference in seconds."
17026 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17027 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17028 (funcall fdiff (current-time)))))
17030 (defun org-deadline-close (timestamp-string &optional ndays)
17031 "Is the time in TIMESTAMP-STRING close to the current date?"
17032 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17033 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17034 (not (org-entry-is-done-p))))
17036 (defun org-get-wdays (ts &optional delay zero-delay)
17037 "Get the deadline lead time appropriate for timestring TS.
17038 When DELAY is non-nil, get the delay time for scheduled items
17039 instead of the deadline lead time. When ZERO-DELAY is non-nil
17040 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17041 don't try to find the delay cookie in the scheduled timestamp."
17042 (let ((tv (if delay org-scheduled-delay-days
17043 org-deadline-warning-days)))
17044 (cond
17045 ((or (and delay (< tv 0))
17046 (and delay zero-delay (<= tv 0))
17047 (and (not delay) (<= tv 0)))
17048 ;; Enforce this value no matter what
17049 (- tv))
17050 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17051 ;; lead time is specified.
17052 (floor (* (string-to-number (match-string 1 ts))
17053 (cdr (assoc (match-string 2 ts)
17054 '(("d" . 1) ("w" . 7)
17055 ("m" . 30.4) ("y" . 365.25)
17056 ("h" . 0.041667)))))))
17057 ;; go for the default.
17058 (t tv))))
17060 (defun org-calendar-select-mouse (ev)
17061 "Return to `org-read-date' with the date currently selected.
17062 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17063 (interactive "e")
17064 (mouse-set-point ev)
17065 (when (calendar-cursor-to-date)
17066 (let* ((date (calendar-cursor-to-date))
17067 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17068 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17069 (if (active-minibuffer-window) (exit-minibuffer))))
17071 (defun org-check-deadlines (ndays)
17072 "Check if there are any deadlines due or past due.
17073 A deadline is considered due if it happens within `org-deadline-warning-days'
17074 days from today's date. If the deadline appears in an entry marked DONE,
17075 it is not shown. The prefix arg NDAYS can be used to test that many
17076 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17077 (interactive "P")
17078 (let* ((org-warn-days
17079 (cond
17080 ((equal ndays '(4)) 100000)
17081 (ndays (prefix-numeric-value ndays))
17082 (t (abs org-deadline-warning-days))))
17083 (case-fold-search nil)
17084 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17085 (callback
17086 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17088 (message "%d deadlines past-due or due within %d days"
17089 (org-occur regexp nil callback)
17090 org-warn-days)))
17092 (defsubst org-re-timestamp (type)
17093 "Return a regexp for timestamp TYPE.
17094 Allowed values for TYPE are:
17096 all: all timestamps
17097 active: only active timestamps (<...>)
17098 inactive: only inactive timestamps ([...])
17099 scheduled: only scheduled timestamps
17100 deadline: only deadline timestamps
17101 closed: only closed time-stamps
17103 When TYPE is nil, fall back on returning a regexp that matches
17104 both scheduled and deadline timestamps."
17105 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17106 ((eq type 'active) org-ts-regexp)
17107 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17108 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17109 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17110 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17111 ((eq type 'scheduled-or-deadline)
17112 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17114 (defun org-check-before-date (date)
17115 "Check if there are deadlines or scheduled entries before DATE."
17116 (interactive (list (org-read-date)))
17117 (let ((case-fold-search nil)
17118 (regexp (org-re-timestamp org-ts-type))
17119 (callback
17120 (lambda () (time-less-p
17121 (org-time-string-to-time (match-string 1))
17122 (org-time-string-to-time date)))))
17123 (message "%d entries before %s"
17124 (org-occur regexp nil callback) date)))
17126 (defun org-check-after-date (date)
17127 "Check if there are deadlines or scheduled entries after DATE."
17128 (interactive (list (org-read-date)))
17129 (let ((case-fold-search nil)
17130 (regexp (org-re-timestamp org-ts-type))
17131 (callback
17132 (lambda () (not
17133 (time-less-p
17134 (org-time-string-to-time (match-string 1))
17135 (org-time-string-to-time date))))))
17136 (message "%d entries after %s"
17137 (org-occur regexp nil callback) date)))
17139 (defun org-check-dates-range (start-date end-date)
17140 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17141 (interactive (list (org-read-date nil nil nil "Range starts")
17142 (org-read-date nil nil nil "Range end")))
17143 (let ((case-fold-search nil)
17144 (regexp (org-re-timestamp org-ts-type))
17145 (callback
17146 (lambda ()
17147 (let ((match (match-string 1)))
17148 (and
17149 (not (time-less-p
17150 (org-time-string-to-time match)
17151 (org-time-string-to-time start-date)))
17152 (time-less-p
17153 (org-time-string-to-time match)
17154 (org-time-string-to-time end-date)))))))
17155 (message "%d entries between %s and %s"
17156 (org-occur regexp nil callback) start-date end-date)))
17158 (defun org-evaluate-time-range (&optional to-buffer)
17159 "Evaluate a time range by computing the difference between start and end.
17160 Normally the result is just printed in the echo area, but with prefix arg
17161 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17162 If the time range is actually in a table, the result is inserted into the
17163 next column.
17164 For time difference computation, a year is assumed to be exactly 365
17165 days in order to avoid rounding problems."
17166 (interactive "P")
17168 (org-clock-update-time-maybe)
17169 (save-excursion
17170 (unless (org-at-date-range-p t)
17171 (goto-char (point-at-bol))
17172 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17173 (if (not (org-at-date-range-p t))
17174 (user-error "Not at a time-stamp range, and none found in current line")))
17175 (let* ((ts1 (match-string 1))
17176 (ts2 (match-string 2))
17177 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17178 (match-end (match-end 0))
17179 (time1 (org-time-string-to-time ts1))
17180 (time2 (org-time-string-to-time ts2))
17181 (t1 (org-float-time time1))
17182 (t2 (org-float-time time2))
17183 (diff (abs (- t2 t1)))
17184 (negative (< (- t2 t1) 0))
17185 ;; (ys (floor (* 365 24 60 60)))
17186 (ds (* 24 60 60))
17187 (hs (* 60 60))
17188 (fy "%dy %dd %02d:%02d")
17189 (fy1 "%dy %dd")
17190 (fd "%dd %02d:%02d")
17191 (fd1 "%dd")
17192 (fh "%02d:%02d")
17193 y d h m align)
17194 (if havetime
17195 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17197 d (floor (/ diff ds)) diff (mod diff ds)
17198 h (floor (/ diff hs)) diff (mod diff hs)
17199 m (floor (/ diff 60)))
17200 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17202 d (floor (+ (/ diff ds) 0.5))
17203 h 0 m 0))
17204 (if (not to-buffer)
17205 (message "%s" (org-make-tdiff-string y d h m))
17206 (if (org-at-table-p)
17207 (progn
17208 (goto-char match-end)
17209 (setq align t)
17210 (and (looking-at " *|") (goto-char (match-end 0))))
17211 (goto-char match-end))
17212 (if (looking-at
17213 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17214 (replace-match ""))
17215 (if negative (insert " -"))
17216 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17217 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17218 (insert " " (format fh h m))))
17219 (if align (org-table-align))
17220 (message "Time difference inserted")))))
17222 (defun org-make-tdiff-string (y d h m)
17223 (let ((fmt "")
17224 (l nil))
17225 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17226 l (push y l)))
17227 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17228 l (push d l)))
17229 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17230 l (push h l)))
17231 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17232 l (push m l)))
17233 (apply 'format fmt (nreverse l))))
17235 (defun org-time-string-to-time (s &optional buffer pos)
17236 "Convert a timestamp string into internal time."
17237 (condition-case errdata
17238 (apply 'encode-time (org-parse-time-string s))
17239 (error (error "Bad timestamp `%s'%s\nError was: %s"
17240 s (if (not (and buffer pos))
17242 (format " at %d in buffer `%s'" pos buffer))
17243 (cdr errdata)))))
17245 (defun org-time-string-to-seconds (s)
17246 "Convert a timestamp string to a number of seconds."
17247 (org-float-time (org-time-string-to-time s)))
17249 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17250 "Convert a time stamp to an absolute day number.
17251 If there is a specifier for a cyclic time stamp, get the closest
17252 date to DAYNR.
17253 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17254 The variable `date' is bound by the calendar when this is called."
17255 (cond
17256 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17257 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17258 daynr
17259 (+ daynr 1000)))
17260 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17261 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17262 (time-to-days (current-time))) (match-string 0 s)
17263 prefer show-all))
17264 (t (time-to-days
17265 (condition-case errdata
17266 (apply 'encode-time (org-parse-time-string s))
17267 (error (error "Bad timestamp `%s'%s\nError was: %s"
17268 s (if (not (and buffer pos))
17270 (format " at %d in buffer `%s'" pos buffer))
17271 (cdr errdata))))))))
17273 (defun org-days-to-iso-week (days)
17274 "Return the iso week number."
17275 (require 'cal-iso)
17276 (car (calendar-iso-from-absolute days)))
17278 (defun org-small-year-to-year (year)
17279 "Convert 2-digit years into 4-digit years.
17280 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17281 The year 2000 cannot be abbreviated. Any year larger than 99
17282 is returned unchanged."
17283 (if (< year 38)
17284 (setq year (+ 2000 year))
17285 (if (< year 100)
17286 (setq year (+ 1900 year))))
17287 year)
17289 (defun org-time-from-absolute (d)
17290 "Return the time corresponding to date D.
17291 D may be an absolute day number, or a calendar-type list (month day year)."
17292 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17293 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17295 (defun org-calendar-holiday ()
17296 "List of holidays, for Diary display in Org-mode."
17297 (require 'holidays)
17298 (let ((hl (funcall
17299 (if (fboundp 'calendar-check-holidays)
17300 'calendar-check-holidays 'check-calendar-holidays) date)))
17301 (if hl (mapconcat 'identity hl "; "))))
17303 (defun org-diary-sexp-entry (sexp entry date)
17304 "Process a SEXP diary ENTRY for DATE."
17305 (require 'diary-lib)
17306 (let ((result (if calendar-debug-sexp
17307 (let ((stack-trace-on-error t))
17308 (eval (car (read-from-string sexp))))
17309 (condition-case nil
17310 (eval (car (read-from-string sexp)))
17311 (error
17312 (beep)
17313 (message "Bad sexp at line %d in %s: %s"
17314 (org-current-line)
17315 (buffer-file-name) sexp)
17316 (sleep-for 2))))))
17317 (cond ((stringp result) (split-string result "; "))
17318 ((and (consp result)
17319 (not (consp (cdr result)))
17320 (stringp (cdr result))) (cdr result))
17321 ((and (consp result)
17322 (stringp (car result))) result)
17323 (result entry))))
17325 (defun org-diary-to-ical-string (frombuf)
17326 "Get iCalendar entries from diary entries in buffer FROMBUF.
17327 This uses the icalendar.el library."
17328 (let* ((tmpdir (if (featurep 'xemacs)
17329 (temp-directory)
17330 temporary-file-directory))
17331 (tmpfile (make-temp-name
17332 (expand-file-name "orgics" tmpdir)))
17333 buf rtn b e)
17334 (with-current-buffer frombuf
17335 (icalendar-export-region (point-min) (point-max) tmpfile)
17336 (setq buf (find-buffer-visiting tmpfile))
17337 (set-buffer buf)
17338 (goto-char (point-min))
17339 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17340 (setq b (match-beginning 0)))
17341 (goto-char (point-max))
17342 (if (re-search-backward "^END:VEVENT" nil t)
17343 (setq e (match-end 0)))
17344 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17345 (kill-buffer buf)
17346 (delete-file tmpfile)
17347 rtn))
17349 (defun org-closest-date (start current change prefer show-all)
17350 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17351 When PREFER is `past', return a date that is either CURRENT or past.
17352 When PREFER is `future', return a date that is either CURRENT or future.
17353 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17354 ;; Make the proper lists from the dates
17355 (catch 'exit
17356 (let ((a1 '(("h" . hour)
17357 ("d" . day)
17358 ("w" . week)
17359 ("m" . month)
17360 ("y" . year)))
17361 (shour (nth 2 (org-parse-time-string start)))
17362 dn dw sday cday n1 n2 n0
17363 d m y y1 y2 date1 date2 nmonths nm ny m2)
17365 (setq start (org-date-to-gregorian start)
17366 current (org-date-to-gregorian
17367 (if show-all
17368 current
17369 (time-to-days (current-time))))
17370 sday (calendar-absolute-from-gregorian start)
17371 cday (calendar-absolute-from-gregorian current))
17373 (if (<= cday sday) (throw 'exit sday))
17375 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17376 (setq dn (string-to-number (match-string 1 change))
17377 dw (cdr (assoc (match-string 2 change) a1)))
17378 (user-error "Invalid change specifier: %s" change))
17379 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17380 (cond
17381 ((eq dw 'hour)
17382 (let ((missing-hours
17383 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17384 dn)))
17385 (setq n1 (if (zerop missing-hours) cday
17386 (- cday (1+ (floor (/ missing-hours 24)))))
17387 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17388 ((eq dw 'day)
17389 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17390 n2 (+ n1 dn)))
17391 ((eq dw 'year)
17392 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17393 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17394 (setq date1 (list m d y1)
17395 n1 (calendar-absolute-from-gregorian date1)
17396 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17397 n2 (calendar-absolute-from-gregorian date2)))
17398 ((eq dw 'month)
17399 ;; approx number of month between the two dates
17400 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17401 ;; How often does dn fit in there?
17402 (setq d (nth 1 start) m (car start) y (nth 2 start)
17403 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17404 m (+ m nm)
17405 ny (floor (/ m 12))
17406 y (+ y ny)
17407 m (- m (* ny 12)))
17408 (while (> m 12) (setq m (- m 12) y (1+ y)))
17409 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17410 (setq m2 (+ m dn) y2 y)
17411 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17412 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17413 (while (<= n2 cday)
17414 (setq n1 n2 m m2 y y2)
17415 (setq m2 (+ m dn) y2 y)
17416 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17417 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17418 ;; Make sure n1 is the earlier date
17419 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17420 (if show-all
17421 (cond
17422 ((eq prefer 'past) (if (= cday n2) n2 n1))
17423 ((eq prefer 'future) (if (= cday n1) n1 n2))
17424 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17425 (cond
17426 ((eq prefer 'past) (if (= cday n2) n2 n1))
17427 ((eq prefer 'future) (if (= cday n1) n1 n2))
17428 (t (if (= cday n1) n1 n2)))))))
17430 (defun org-date-to-gregorian (date)
17431 "Turn any specification of DATE into a Gregorian date for the calendar."
17432 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17433 ((and (listp date) (= (length date) 3)) date)
17434 ((stringp date)
17435 (setq date (org-parse-time-string date))
17436 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17437 ((listp date)
17438 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17440 (defun org-parse-time-string (s &optional nodefault)
17441 "Parse the standard Org-mode time string.
17442 This should be a lot faster than the normal `parse-time-string'.
17443 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17444 hour and minute fields will be nil if not given."
17445 (cond ((string-match org-ts-regexp0 s)
17446 (list 0
17447 (if (or (match-beginning 8) (not nodefault))
17448 (string-to-number (or (match-string 8 s) "0")))
17449 (if (or (match-beginning 7) (not nodefault))
17450 (string-to-number (or (match-string 7 s) "0")))
17451 (string-to-number (match-string 4 s))
17452 (string-to-number (match-string 3 s))
17453 (string-to-number (match-string 2 s))
17454 nil nil nil))
17455 ((string-match "^<[^>]+>$" s)
17456 (decode-time (seconds-to-time (org-matcher-time s))))
17457 (t (error "Not a standard Org-mode time string: %s" s))))
17459 (defun org-timestamp-up (&optional arg)
17460 "Increase the date item at the cursor by one.
17461 If the cursor is on the year, change the year. If it is on the month,
17462 the day or the time, change that.
17463 With prefix ARG, change by that many units."
17464 (interactive "p")
17465 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17467 (defun org-timestamp-down (&optional arg)
17468 "Decrease the date item at the cursor by one.
17469 If the cursor is on the year, change the year. If it is on the month,
17470 the day or the time, change that.
17471 With prefix ARG, change by that many units."
17472 (interactive "p")
17473 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17475 (defun org-timestamp-up-day (&optional arg)
17476 "Increase the date in the time stamp by one day.
17477 With prefix ARG, change that many days."
17478 (interactive "p")
17479 (if (and (not (org-at-timestamp-p t))
17480 (org-at-heading-p))
17481 (org-todo 'up)
17482 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17484 (defun org-timestamp-down-day (&optional arg)
17485 "Decrease the date in the time stamp by one day.
17486 With prefix ARG, change that many days."
17487 (interactive "p")
17488 (if (and (not (org-at-timestamp-p t))
17489 (org-at-heading-p))
17490 (org-todo 'down)
17491 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17493 (defun org-at-timestamp-p (&optional inactive-ok)
17494 "Determine if the cursor is in or at a timestamp."
17495 (interactive)
17496 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17497 (pos (point))
17498 (ans (or (looking-at tsr)
17499 (save-excursion
17500 (skip-chars-backward "^[<\n\r\t")
17501 (if (> (point) (point-min)) (backward-char 1))
17502 (and (looking-at tsr)
17503 (> (- (match-end 0) pos) -1))))))
17504 (and ans
17505 (boundp 'org-ts-what)
17506 (setq org-ts-what
17507 (cond
17508 ((= pos (match-beginning 0)) 'bracket)
17509 ;; Point is considered to be "on the bracket" whether
17510 ;; it's really on it or right after it.
17511 ((= pos (1- (match-end 0))) 'bracket)
17512 ((= pos (match-end 0)) 'after)
17513 ((org-pos-in-match-range pos 2) 'year)
17514 ((org-pos-in-match-range pos 3) 'month)
17515 ((org-pos-in-match-range pos 7) 'hour)
17516 ((org-pos-in-match-range pos 8) 'minute)
17517 ((or (org-pos-in-match-range pos 4)
17518 (org-pos-in-match-range pos 5)) 'day)
17519 ((and (> pos (or (match-end 8) (match-end 5)))
17520 (< pos (match-end 0)))
17521 (- pos (or (match-end 8) (match-end 5))))
17522 (t 'day))))
17523 ans))
17525 (defun org-toggle-timestamp-type ()
17526 "Toggle the type (<active> or [inactive]) of a time stamp."
17527 (interactive)
17528 (when (org-at-timestamp-p t)
17529 (let ((beg (match-beginning 0)) (end (match-end 0))
17530 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17531 (save-excursion
17532 (goto-char beg)
17533 (while (re-search-forward "[][<>]" end t)
17534 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17535 t t)))
17536 (message "Timestamp is now %sactive"
17537 (if (equal (char-after beg) ?<) "" "in")))))
17539 (defun org-at-clock-log-p nil
17540 "Is the cursor on the clock log line?"
17541 (save-excursion
17542 (move-beginning-of-line 1)
17543 (looking-at "^[ \t]*CLOCK:")))
17545 (defvar org-clock-history) ; defined in org-clock.el
17546 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17547 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17548 "Change the date in the time stamp at point.
17549 The date will be changed by N times WHAT. WHAT can be `day', `month',
17550 `year', `minute', `second'. If WHAT is not given, the cursor position
17551 in the timestamp determines what will be changed.
17552 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17553 (let ((origin (point)) origin-cat
17554 with-hm inactive
17555 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17556 org-ts-what
17557 extra rem
17558 ts time time0 fixnext clrgx)
17559 (if (not (org-at-timestamp-p t))
17560 (user-error "Not at a timestamp"))
17561 (if (and (not what) (eq org-ts-what 'bracket))
17562 (org-toggle-timestamp-type)
17563 ;; Point isn't on brackets. Remember the part of the time-stamp
17564 ;; the point was in. Indeed, size of time-stamps may change,
17565 ;; but point must be kept in the same category nonetheless.
17566 (setq origin-cat org-ts-what)
17567 (if (and (not what) (not (eq org-ts-what 'day))
17568 org-display-custom-times
17569 (get-text-property (point) 'display)
17570 (not (get-text-property (1- (point)) 'display)))
17571 (setq org-ts-what 'day))
17572 (setq org-ts-what (or what org-ts-what)
17573 inactive (= (char-after (match-beginning 0)) ?\[)
17574 ts (match-string 0))
17575 (replace-match "")
17576 (when (string-match
17577 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17579 (setq extra (match-string 1 ts))
17580 (if suppress-tmp-delay
17581 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17582 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17583 (setq with-hm t))
17584 (setq time0 (org-parse-time-string ts))
17585 (when (and updown
17586 (eq org-ts-what 'minute)
17587 (not current-prefix-arg))
17588 ;; This looks like s-up and s-down. Change by one rounding step.
17589 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17590 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17591 (setcar (cdr time0) (+ (nth 1 time0)
17592 (if (> n 0) (- rem) (- dm rem))))))
17593 (setq time
17594 (encode-time (or (car time0) 0)
17595 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17596 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17597 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17598 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17599 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17600 (nthcdr 6 time0)))
17601 (when (and (member org-ts-what '(hour minute))
17602 extra
17603 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17604 (setq extra (org-modify-ts-extra
17605 extra
17606 (if (eq org-ts-what 'hour) 2 5)
17607 n dm)))
17608 (when (integerp org-ts-what)
17609 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17610 (if (eq what 'calendar)
17611 (let ((cal-date (org-get-date-from-calendar)))
17612 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17613 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17614 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17615 (setcar time0 (or (car time0) 0))
17616 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17617 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17618 (setq time (apply 'encode-time time0))))
17619 ;; Insert the new time-stamp, and ensure point stays in the same
17620 ;; category as before (i.e. not after the last position in that
17621 ;; category).
17622 (let ((pos (point)))
17623 ;; Stay before inserted string. `save-excursion' is of no use.
17624 (setq org-last-changed-timestamp
17625 (org-insert-time-stamp time with-hm inactive nil nil extra))
17626 (goto-char pos))
17627 (save-match-data
17628 (looking-at org-ts-regexp3)
17629 (goto-char (cond
17630 ;; `day' category ends before `hour' if any, or at
17631 ;; the end of the day name.
17632 ((eq origin-cat 'day)
17633 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17634 ((eq origin-cat 'hour) (min (match-end 7) origin))
17635 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17636 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17637 ;; `year' and `month' have both fixed size: point
17638 ;; couldn't have moved into another part.
17639 (t origin))))
17640 ;; Update clock if on a CLOCK line.
17641 (org-clock-update-time-maybe)
17642 ;; Maybe adjust the closest clock in `org-clock-history'
17643 (when org-clock-adjust-closest
17644 (if (not (and (org-at-clock-log-p)
17645 (< 1 (length (delq nil (mapcar 'marker-position
17646 org-clock-history))))))
17647 (message "No clock to adjust")
17648 (cond ((save-excursion ; fix previous clock?
17649 (re-search-backward org-ts-regexp0 nil t)
17650 (org-looking-back (concat org-clock-string " \\[")))
17651 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17652 ((save-excursion ; fix next clock?
17653 (re-search-backward org-ts-regexp0 nil t)
17654 (looking-at (concat org-ts-regexp0 "\\] =>")))
17655 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17656 (save-window-excursion
17657 ;; Find closest clock to point, adjust the previous/next one in history
17658 (let* ((p (save-excursion (org-back-to-heading t)))
17659 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17660 (clfixnth
17661 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17662 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17663 (if (not clfixpos)
17664 (message "No clock to adjust")
17665 (save-excursion
17666 (org-goto-marker-or-bmk clfixpos)
17667 (org-show-subtree)
17668 (when (re-search-forward clrgx nil t)
17669 (goto-char (match-beginning 1))
17670 (let (org-clock-adjust-closest)
17671 (org-timestamp-change n org-ts-what updown))
17672 (message "Clock adjusted in %s for heading: %s"
17673 (file-name-nondirectory (buffer-file-name))
17674 (org-get-heading t t)))))))))
17675 ;; Try to recenter the calendar window, if any.
17676 (if (and org-calendar-follow-timestamp-change
17677 (get-buffer-window "*Calendar*" t)
17678 (memq org-ts-what '(day month year)))
17679 (org-recenter-calendar (time-to-days time))))))
17681 (defun org-modify-ts-extra (s pos n dm)
17682 "Change the different parts of the lead-time and repeat fields in timestamp."
17683 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17684 ng h m new rem)
17685 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17686 (cond
17687 ((or (org-pos-in-match-range pos 2)
17688 (org-pos-in-match-range pos 3))
17689 (setq m (string-to-number (match-string 3 s))
17690 h (string-to-number (match-string 2 s)))
17691 (if (org-pos-in-match-range pos 2)
17692 (setq h (+ h n))
17693 (setq n (* dm (org-no-warnings (signum n))))
17694 (when (not (= 0 (setq rem (% m dm))))
17695 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17696 (setq m (+ m n)))
17697 (if (< m 0) (setq m (+ m 60) h (1- h)))
17698 (if (> m 59) (setq m (- m 60) h (1+ h)))
17699 (setq h (min 24 (max 0 h)))
17700 (setq ng 1 new (format "-%02d:%02d" h m)))
17701 ((org-pos-in-match-range pos 6)
17702 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17703 ((org-pos-in-match-range pos 5)
17704 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17706 ((org-pos-in-match-range pos 9)
17707 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17708 ((org-pos-in-match-range pos 8)
17709 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17711 (when ng
17712 (setq s (concat
17713 (substring s 0 (match-beginning ng))
17715 (substring s (match-end ng))))))
17718 (defun org-recenter-calendar (date)
17719 "If the calendar is visible, recenter it to DATE."
17720 (let ((cwin (get-buffer-window "*Calendar*" t)))
17721 (when cwin
17722 (let ((calendar-move-hook nil))
17723 (with-selected-window cwin
17724 (calendar-goto-date (if (listp date) date
17725 (calendar-gregorian-from-absolute date))))))))
17727 (defun org-goto-calendar (&optional arg)
17728 "Go to the Emacs calendar at the current date.
17729 If there is a time stamp in the current line, go to that date.
17730 A prefix ARG can be used to force the current date."
17731 (interactive "P")
17732 (let ((tsr org-ts-regexp) diff
17733 (calendar-move-hook nil)
17734 (calendar-view-holidays-initially-flag nil)
17735 (calendar-view-diary-initially-flag nil))
17736 (if (or (org-at-timestamp-p)
17737 (save-excursion
17738 (beginning-of-line 1)
17739 (looking-at (concat ".*" tsr))))
17740 (let ((d1 (time-to-days (current-time)))
17741 (d2 (time-to-days
17742 (org-time-string-to-time (match-string 1)))))
17743 (setq diff (- d2 d1))))
17744 (calendar)
17745 (calendar-goto-today)
17746 (if (and diff (not arg)) (calendar-forward-day diff))))
17748 (defun org-get-date-from-calendar ()
17749 "Return a list (month day year) of date at point in calendar."
17750 (with-current-buffer "*Calendar*"
17751 (save-match-data
17752 (calendar-cursor-to-date))))
17754 (defun org-date-from-calendar ()
17755 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17756 If there is already a time stamp at the cursor position, update it."
17757 (interactive)
17758 (if (org-at-timestamp-p t)
17759 (org-timestamp-change 0 'calendar)
17760 (let ((cal-date (org-get-date-from-calendar)))
17761 (org-insert-time-stamp
17762 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17764 (defcustom org-effort-durations
17765 `(("h" . 60)
17766 ("d" . ,(* 60 8))
17767 ("w" . ,(* 60 8 5))
17768 ("m" . ,(* 60 8 5 4))
17769 ("y" . ,(* 60 8 5 40)))
17770 "Conversion factor to minutes for an effort modifier.
17772 Each entry has the form (MODIFIER . MINUTES).
17774 In an effort string, a number followed by MODIFIER is multiplied
17775 by the specified number of MINUTES to obtain an effort in
17776 minutes.
17778 For example, if the value of this variable is ((\"hours\" . 60)), then an
17779 effort string \"2hours\" is equivalent to 120 minutes."
17780 :group 'org-agenda
17781 :version "24.1"
17782 :type '(alist :key-type (string :tag "Modifier")
17783 :value-type (number :tag "Minutes")))
17785 (defun org-minutes-to-clocksum-string (m)
17786 "Format number of minutes as a clocksum string.
17787 The format is determined by `org-time-clocksum-format',
17788 `org-time-clocksum-use-fractional' and
17789 `org-time-clocksum-fractional-format' and
17790 `org-time-clocksum-use-effort-durations'."
17791 (let ((clocksum "")
17792 (m (round m)) ; Don't allow fractions of minutes
17793 h d w mo y fmt n)
17794 (setq h (if org-time-clocksum-use-effort-durations
17795 (cdr (assoc "h" org-effort-durations)) 60)
17796 d (if org-time-clocksum-use-effort-durations
17797 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17798 w (if org-time-clocksum-use-effort-durations
17799 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17800 mo (if org-time-clocksum-use-effort-durations
17801 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17802 y (if org-time-clocksum-use-effort-durations
17803 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17804 ;; fractional format
17805 (if org-time-clocksum-use-fractional
17806 (cond
17807 ;; single format string
17808 ((stringp org-time-clocksum-fractional-format)
17809 (format org-time-clocksum-fractional-format (/ m (float h))))
17810 ;; choice of fractional formats for different time units
17811 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17812 (> (/ (truncate m) (* y d h)) 0))
17813 (format fmt (/ m (* y d (float h)))))
17814 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17815 (> (/ (truncate m) (* mo d h)) 0))
17816 (format fmt (/ m (* mo d (float h)))))
17817 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17818 (> (/ (truncate m) (* w d h)) 0))
17819 (format fmt (/ m (* w d (float h)))))
17820 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17821 (> (/ (truncate m) (* d h)) 0))
17822 (format fmt (/ m (* d (float h)))))
17823 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17824 (> (/ (truncate m) h) 0))
17825 (format fmt (/ m (float h))))
17826 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17827 (format fmt m))
17828 ;; fall back to smallest time unit with a format
17829 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17830 (format fmt (/ m (float h))))
17831 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17832 (format fmt (/ m (* d (float h)))))
17833 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17834 (format fmt (/ m (* w d (float h)))))
17835 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17836 (format fmt (/ m (* mo d (float h)))))
17837 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17838 (format fmt (/ m (* y d (float h))))))
17839 ;; standard (non-fractional) format, with single format string
17840 (if (stringp org-time-clocksum-format)
17841 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17842 ;; separate formats components
17843 (and (setq fmt (plist-get org-time-clocksum-format :years))
17844 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17845 (plist-get org-time-clocksum-format :require-years))
17846 (setq clocksum (concat clocksum (format fmt n))
17847 m (- m (* n y d h))))
17848 (and (setq fmt (plist-get org-time-clocksum-format :months))
17849 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17850 (plist-get org-time-clocksum-format :require-months))
17851 (setq clocksum (concat clocksum (format fmt n))
17852 m (- m (* n mo d h))))
17853 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17854 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17855 (plist-get org-time-clocksum-format :require-weeks))
17856 (setq clocksum (concat clocksum (format fmt n))
17857 m (- m (* n w d h))))
17858 (and (setq fmt (plist-get org-time-clocksum-format :days))
17859 (or (> (setq n (/ (truncate m) (* d h))) 0)
17860 (plist-get org-time-clocksum-format :require-days))
17861 (setq clocksum (concat clocksum (format fmt n))
17862 m (- m (* n d h))))
17863 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17864 (or (> (setq n (/ (truncate m) h)) 0)
17865 (plist-get org-time-clocksum-format :require-hours))
17866 (setq clocksum (concat clocksum (format fmt n))
17867 m (- m (* n h))))
17868 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17869 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17870 (setq clocksum (concat clocksum (format fmt m))))
17871 ;; return formatted time duration
17872 clocksum))))
17874 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17875 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17876 "Org mode version 8.0")
17878 (defun org-hours-to-clocksum-string (n)
17879 (org-minutes-to-clocksum-string (* n 60)))
17881 (defun org-hh:mm-string-to-minutes (s)
17882 "Convert a string H:MM to a number of minutes.
17883 If the string is just a number, interpret it as minutes.
17884 In fact, the first hh:mm or number in the string will be taken,
17885 there can be extra stuff in the string.
17886 If no number is found, the return value is 0."
17887 (cond
17888 ((integerp s) s)
17889 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17890 (+ (* (string-to-number (match-string 1 s)) 60)
17891 (string-to-number (match-string 2 s))))
17892 ((string-match "\\([0-9]+\\)" s)
17893 (string-to-number (match-string 1 s)))
17894 (t 0)))
17896 (defcustom org-image-actual-width t
17897 "Should we use the actual width of images when inlining them?
17899 When set to `t', always use the image width.
17901 When set to a number, use imagemagick (when available) to set
17902 the image's width to this value.
17904 When set to a number in a list, try to get the width from any
17905 #+ATTR.* keyword if it matches a width specification like
17907 #+ATTR_HTML: :width 300px
17909 and fall back on that number if none is found.
17911 When set to nil, try to get the width from an #+ATTR.* keyword
17912 and fall back on the original width if none is found.
17914 This requires Emacs >= 24.1, build with imagemagick support."
17915 :group 'org-appearance
17916 :version "24.4"
17917 :package-version '(Org . "8.0")
17918 :type '(choice
17919 (const :tag "Use the image width" t)
17920 (integer :tag "Use a number of pixels")
17921 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17922 (const :tag "Use #+ATTR* or don't resize" nil)))
17924 (defcustom org-agenda-inhibit-startup nil
17925 "Inhibit startup when preparing agenda buffers.
17926 When this variable is `t' (the default), the initialization of
17927 the Org agenda buffers is inhibited: e.g. the visibility state
17928 is not set, the tables are not re-aligned, etc."
17929 :type 'boolean
17930 :version "24.3"
17931 :group 'org-agenda)
17933 (define-obsolete-variable-alias
17934 'org-agenda-ignore-drawer-properties
17935 'org-agenda-ignore-properties "24.5")
17937 (defcustom org-agenda-ignore-properties nil
17938 "Avoid updating text properties when building the agenda.
17939 Properties are used to prepare buffers for effort estimates,
17940 appointments, statistics and subtree-local categories.
17941 If you don't use these in the agenda, you can add them to this
17942 list and agenda building will be a bit faster.
17943 The value is a list, with zero or more of the symbols `effort', `appt',
17944 `stats' or `category'."
17945 :type '(set :greedy t
17946 (const effort)
17947 (const appt)
17948 (const stats)
17949 (const category))
17950 :version "24.5"
17951 :package-version '(Org . "8.3")
17952 :group 'org-agenda)
17954 (defun org-duration-string-to-minutes (s &optional output-to-string)
17955 "Convert a duration string S to minutes.
17957 A bare number is interpreted as minutes, modifiers can be set by
17958 customizing `org-effort-durations' (which see).
17960 Entries containing a colon are interpreted as H:MM by
17961 `org-hh:mm-string-to-minutes'."
17962 (let ((result 0)
17963 (re (concat "\\([0-9.]+\\) *\\("
17964 (regexp-opt (mapcar 'car org-effort-durations))
17965 "\\)")))
17966 (while (string-match re s)
17967 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17968 (string-to-number (match-string 1 s))))
17969 (setq s (replace-match "" nil t s)))
17970 (setq result (floor result))
17971 (incf result (org-hh:mm-string-to-minutes s))
17972 (if output-to-string (number-to-string result) result)))
17974 ;;;; Files
17976 (defun org-save-all-org-buffers ()
17977 "Save all Org-mode buffers without user confirmation."
17978 (interactive)
17979 (message "Saving all Org-mode buffers...")
17980 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17981 (when (featurep 'org-id) (org-id-locations-save))
17982 (message "Saving all Org-mode buffers... done"))
17984 (defun org-revert-all-org-buffers ()
17985 "Revert all Org-mode buffers.
17986 Prompt for confirmation when there are unsaved changes.
17987 Be sure you know what you are doing before letting this function
17988 overwrite your changes.
17990 This function is useful in a setup where one tracks org files
17991 with a version control system, to revert on one machine after pulling
17992 changes from another. I believe the procedure must be like this:
17994 1. M-x org-save-all-org-buffers
17995 2. Pull changes from the other machine, resolve conflicts
17996 3. M-x org-revert-all-org-buffers"
17997 (interactive)
17998 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17999 (user-error "Abort"))
18000 (save-excursion
18001 (save-window-excursion
18002 (mapc
18003 (lambda (b)
18004 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18005 (with-current-buffer b buffer-file-name))
18006 (org-pop-to-buffer-same-window b)
18007 (revert-buffer t 'no-confirm)))
18008 (buffer-list))
18009 (when (and (featurep 'org-id) org-id-track-globally)
18010 (org-id-locations-load)))))
18012 ;;;; Agenda files
18014 ;;;###autoload
18015 (defun org-switchb (&optional arg)
18016 "Switch between Org buffers.
18017 With one prefix argument, restrict available buffers to files.
18018 With two prefix arguments, restrict available buffers to agenda files.
18020 Defaults to `iswitchb' for buffer name completion.
18021 Set `org-completion-use-ido' to make it use ido instead."
18022 (interactive "P")
18023 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18024 ((equal arg '(16)) (org-buffer-list 'agenda))
18025 (t (org-buffer-list))))
18026 (org-completion-use-iswitchb org-completion-use-iswitchb)
18027 (org-completion-use-ido org-completion-use-ido))
18028 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18029 (setq org-completion-use-iswitchb t))
18030 (org-pop-to-buffer-same-window
18031 (org-icompleting-read "Org buffer: "
18032 (mapcar 'list (mapcar 'buffer-name blist))
18033 nil t))))
18035 ;;; Define some older names previously used for this functionality
18036 ;;;###autoload
18037 (defalias 'org-ido-switchb 'org-switchb)
18038 ;;;###autoload
18039 (defalias 'org-iswitchb 'org-switchb)
18041 (defun org-buffer-list (&optional predicate exclude-tmp)
18042 "Return a list of Org buffers.
18043 PREDICATE can be `export', `files' or `agenda'.
18045 export restrict the list to Export buffers.
18046 files restrict the list to buffers visiting Org files.
18047 agenda restrict the list to buffers visiting agenda files.
18049 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18050 (let* ((bfn nil)
18051 (agenda-files (and (eq predicate 'agenda)
18052 (mapcar 'file-truename (org-agenda-files t))))
18053 (filter
18054 (cond
18055 ((eq predicate 'files)
18056 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18057 ((eq predicate 'export)
18058 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18059 ((eq predicate 'agenda)
18060 (lambda (b)
18061 (with-current-buffer b
18062 (and (derived-mode-p 'org-mode)
18063 (setq bfn (buffer-file-name b))
18064 (member (file-truename bfn) agenda-files)))))
18065 (t (lambda (b) (with-current-buffer b
18066 (or (derived-mode-p 'org-mode)
18067 (string-match "\*Org .*Export"
18068 (buffer-name b)))))))))
18069 (delq nil
18070 (mapcar
18071 (lambda(b)
18072 (if (and (funcall filter b)
18073 (or (not exclude-tmp)
18074 (not (string-match "tmp" (buffer-name b)))))
18076 nil))
18077 (buffer-list)))))
18079 (defun org-agenda-files (&optional unrestricted archives)
18080 "Get the list of agenda files.
18081 Optional UNRESTRICTED means return the full list even if a restriction
18082 is currently in place.
18083 When ARCHIVES is t, include all archive files that are really being
18084 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18085 `org-agenda-archives-mode' is t."
18086 (let ((files
18087 (cond
18088 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18089 ((stringp org-agenda-files) (org-read-agenda-file-list))
18090 ((listp org-agenda-files) org-agenda-files)
18091 (t (error "Invalid value of `org-agenda-files'")))))
18092 (setq files (apply 'append
18093 (mapcar (lambda (f)
18094 (if (file-directory-p f)
18095 (directory-files
18096 f t org-agenda-file-regexp)
18097 (list f)))
18098 files)))
18099 (when org-agenda-skip-unavailable-files
18100 (setq files (delq nil
18101 (mapcar (function
18102 (lambda (file)
18103 (and (file-readable-p file) file)))
18104 files))))
18105 (when (or (eq archives t)
18106 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18107 (setq files (org-add-archive-files files)))
18108 files))
18110 (defun org-agenda-file-p (&optional file)
18111 "Return non-nil, if FILE is an agenda file.
18112 If FILE is omitted, use the file associated with the current
18113 buffer."
18114 (member (or file (buffer-file-name))
18115 (org-agenda-files t)))
18117 (defun org-edit-agenda-file-list ()
18118 "Edit the list of agenda files.
18119 Depending on setup, this either uses customize to edit the variable
18120 `org-agenda-files', or it visits the file that is holding the list. In the
18121 latter case, the buffer is set up in a way that saving it automatically kills
18122 the buffer and restores the previous window configuration."
18123 (interactive)
18124 (if (stringp org-agenda-files)
18125 (let ((cw (current-window-configuration)))
18126 (find-file org-agenda-files)
18127 (org-set-local 'org-window-configuration cw)
18128 (org-add-hook 'after-save-hook
18129 (lambda ()
18130 (set-window-configuration
18131 (prog1 org-window-configuration
18132 (kill-buffer (current-buffer))))
18133 (org-install-agenda-files-menu)
18134 (message "New agenda file list installed"))
18135 nil 'local)
18136 (message "%s" (substitute-command-keys
18137 "Edit list and finish with \\[save-buffer]")))
18138 (customize-variable 'org-agenda-files)))
18140 (defun org-store-new-agenda-file-list (list)
18141 "Set new value for the agenda file list and save it correctly."
18142 (if (stringp org-agenda-files)
18143 (let ((fe (org-read-agenda-file-list t)) b u)
18144 (while (setq b (find-buffer-visiting org-agenda-files))
18145 (kill-buffer b))
18146 (with-temp-file org-agenda-files
18147 (insert
18148 (mapconcat
18149 (lambda (f) ;; Keep un-expanded entries.
18150 (if (setq u (assoc f fe))
18151 (cdr u)
18153 list "\n")
18154 "\n")))
18155 (let ((org-mode-hook nil) (org-inhibit-startup t)
18156 (org-insert-mode-line-in-empty-file nil))
18157 (setq org-agenda-files list)
18158 (customize-save-variable 'org-agenda-files org-agenda-files))))
18160 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18161 "Read the list of agenda files from a file.
18162 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18163 filenames, used by `org-store-new-agenda-file-list' to write back
18164 un-expanded file names."
18165 (when (file-directory-p org-agenda-files)
18166 (error "`org-agenda-files' cannot be a single directory"))
18167 (when (stringp org-agenda-files)
18168 (with-temp-buffer
18169 (insert-file-contents org-agenda-files)
18170 (mapcar
18171 (lambda (f)
18172 (let ((e (expand-file-name (substitute-in-file-name f)
18173 org-directory)))
18174 (if pair-with-expansion
18175 (cons e f)
18176 e)))
18177 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18179 ;;;###autoload
18180 (defun org-cycle-agenda-files ()
18181 "Cycle through the files in `org-agenda-files'.
18182 If the current buffer visits an agenda file, find the next one in the list.
18183 If the current buffer does not, find the first agenda file."
18184 (interactive)
18185 (let* ((fs (org-agenda-files t))
18186 (files (append fs (list (car fs))))
18187 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18188 file)
18189 (unless files (user-error "No agenda files"))
18190 (catch 'exit
18191 (while (setq file (pop files))
18192 (if (equal (file-truename file) tcf)
18193 (when (car files)
18194 (find-file (car files))
18195 (throw 'exit t))))
18196 (find-file (car fs)))
18197 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18199 (defun org-agenda-file-to-front (&optional to-end)
18200 "Move/add the current file to the top of the agenda file list.
18201 If the file is not present in the list, it is added to the front. If it is
18202 present, it is moved there. With optional argument TO-END, add/move to the
18203 end of the list."
18204 (interactive "P")
18205 (let ((org-agenda-skip-unavailable-files nil)
18206 (file-alist (mapcar (lambda (x)
18207 (cons (file-truename x) x))
18208 (org-agenda-files t)))
18209 (ctf (file-truename
18210 (or buffer-file-name
18211 (user-error "Please save the current buffer to a file"))))
18212 x had)
18213 (setq x (assoc ctf file-alist) had x)
18215 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18216 (if to-end
18217 (setq file-alist (append (delq x file-alist) (list x)))
18218 (setq file-alist (cons x (delq x file-alist))))
18219 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18220 (org-install-agenda-files-menu)
18221 (message "File %s to %s of agenda file list"
18222 (if had "moved" "added") (if to-end "end" "front"))))
18224 (defun org-remove-file (&optional file)
18225 "Remove current file from the list of files in variable `org-agenda-files'.
18226 These are the files which are being checked for agenda entries.
18227 Optional argument FILE means use this file instead of the current."
18228 (interactive)
18229 (let* ((org-agenda-skip-unavailable-files nil)
18230 (file (or file buffer-file-name
18231 (user-error "Current buffer does not visit a file")))
18232 (true-file (file-truename file))
18233 (afile (abbreviate-file-name file))
18234 (files (delq nil (mapcar
18235 (lambda (x)
18236 (if (equal true-file
18237 (file-truename x))
18238 nil x))
18239 (org-agenda-files t)))))
18240 (if (not (= (length files) (length (org-agenda-files t))))
18241 (progn
18242 (org-store-new-agenda-file-list files)
18243 (org-install-agenda-files-menu)
18244 (message "Removed file: %s" afile))
18245 (message "File was not in list: %s (not removed)" afile))))
18247 (defun org-file-menu-entry (file)
18248 (vector file (list 'find-file file) t))
18250 (defun org-check-agenda-file (file)
18251 "Make sure FILE exists. If not, ask user what to do."
18252 (when (not (file-exists-p file))
18253 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18254 (abbreviate-file-name file))
18255 (let ((r (downcase (read-char-exclusive))))
18256 (cond
18257 ((equal r ?r)
18258 (org-remove-file file)
18259 (throw 'nextfile t))
18260 (t (user-error "Abort"))))))
18262 (defun org-get-agenda-file-buffer (file)
18263 "Get an agenda buffer visiting FILE.
18264 If the buffer needs to be created, add it to the list of buffers
18265 which might be released later."
18266 (let ((buf (org-find-base-buffer-visiting file)))
18267 (if buf
18268 buf ; just return it
18269 ;; Make a new buffer and remember it
18270 (setq buf (find-file-noselect file))
18271 (if buf (push buf org-agenda-new-buffers))
18272 buf)))
18274 (defun org-release-buffers (blist)
18275 "Release all buffers in list, asking the user for confirmation when needed.
18276 When a buffer is unmodified, it is just killed. When modified, it is saved
18277 \(if the user agrees) and then killed."
18278 (let (buf file)
18279 (while (setq buf (pop blist))
18280 (setq file (buffer-file-name buf))
18281 (when (and (buffer-modified-p buf)
18282 file
18283 (y-or-n-p (format "Save file %s? " file)))
18284 (with-current-buffer buf (save-buffer)))
18285 (kill-buffer buf))))
18287 (defun org-agenda-prepare-buffers (files)
18288 "Create buffers for all agenda files, protect archived trees and comments."
18289 (interactive)
18290 (let ((pa '(:org-archived t))
18291 (pc '(:org-comment t))
18292 (pall '(:org-archived t :org-comment t))
18293 (inhibit-read-only t)
18294 (org-inhibit-startup org-agenda-inhibit-startup)
18295 (rea (concat ":" org-archive-tag ":"))
18296 file re pos)
18297 (setq org-tag-alist-for-agenda nil
18298 org-tag-groups-alist-for-agenda nil)
18299 (save-excursion
18300 (save-restriction
18301 (while (setq file (pop files))
18302 (catch 'nextfile
18303 (if (bufferp file)
18304 (set-buffer file)
18305 (org-check-agenda-file file)
18306 (set-buffer (org-get-agenda-file-buffer file)))
18307 (widen)
18308 (org-set-regexps-and-options-for-tags)
18309 (setq pos (point))
18310 (goto-char (point-min))
18311 (let ((case-fold-search t))
18312 (when (search-forward "#+setupfile" nil t)
18313 ;; Don't set all regexps and options systematically as
18314 ;; this is only run for setting agenda tags from setup
18315 ;; file
18316 (org-set-regexps-and-options)))
18317 (or (memq 'category org-agenda-ignore-properties)
18318 (org-refresh-category-properties))
18319 (or (memq 'stats org-agenda-ignore-properties)
18320 (org-refresh-stats-properties))
18321 (or (memq 'effort org-agenda-ignore-properties)
18322 (org-refresh-properties
18323 org-effort-property
18324 '((effort . identity)
18325 (effort-minutes . org-duration-string-to-minutes))))
18326 (or (memq 'appt org-agenda-ignore-properties)
18327 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18328 (setq org-todo-keywords-for-agenda
18329 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18330 (setq org-done-keywords-for-agenda
18331 (append org-done-keywords-for-agenda org-done-keywords))
18332 (setq org-todo-keyword-alist-for-agenda
18333 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18334 (setq org-tag-alist-for-agenda
18335 (org-uniquify
18336 (append org-tag-alist-for-agenda
18337 org-tag-alist
18338 org-tag-persistent-alist)))
18339 (if org-group-tags
18340 (setq org-tag-groups-alist-for-agenda
18341 (org-uniquify-alist
18342 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18343 (org-with-silent-modifications
18344 (save-excursion
18345 (remove-text-properties (point-min) (point-max) pall)
18346 (when org-agenda-skip-archived-trees
18347 (goto-char (point-min))
18348 (while (re-search-forward rea nil t)
18349 (if (org-at-heading-p t)
18350 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18351 (goto-char (point-min))
18352 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18353 (while (re-search-forward re nil t)
18354 (when (save-match-data (org-in-commented-heading-p t))
18355 (add-text-properties
18356 (match-beginning 0) (org-end-of-subtree t) pc)))))
18357 (goto-char pos)))))
18358 (setq org-todo-keywords-for-agenda
18359 (org-uniquify org-todo-keywords-for-agenda))
18360 (setq org-todo-keyword-alist-for-agenda
18361 (org-uniquify org-todo-keyword-alist-for-agenda))))
18364 ;;;; CDLaTeX minor mode
18366 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18367 "Keymap for the minor `org-cdlatex-mode'.")
18369 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18370 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18371 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18372 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18373 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18375 (defvar org-cdlatex-texmathp-advice-is-done nil
18376 "Flag remembering if we have applied the advice to texmathp already.")
18378 (define-minor-mode org-cdlatex-mode
18379 "Toggle the minor `org-cdlatex-mode'.
18380 This mode supports entering LaTeX environment and math in LaTeX fragments
18381 in Org-mode.
18382 \\{org-cdlatex-mode-map}"
18383 nil " OCDL" nil
18384 (when org-cdlatex-mode
18385 (require 'cdlatex)
18386 (run-hooks 'cdlatex-mode-hook)
18387 (cdlatex-compute-tables))
18388 (unless org-cdlatex-texmathp-advice-is-done
18389 (setq org-cdlatex-texmathp-advice-is-done t)
18390 (defadvice texmathp (around org-math-always-on activate)
18391 "Always return t in org-mode buffers.
18392 This is because we want to insert math symbols without dollars even outside
18393 the LaTeX math segments. If Orgmode thinks that point is actually inside
18394 an embedded LaTeX fragment, let texmathp do its job.
18395 \\[org-cdlatex-mode-map]"
18396 (interactive)
18397 (let (p)
18398 (cond
18399 ((not (derived-mode-p 'org-mode)) ad-do-it)
18400 ((eq this-command 'cdlatex-math-symbol)
18401 (setq ad-return-value t
18402 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18404 (let ((p (org-inside-LaTeX-fragment-p)))
18405 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18406 (setq ad-return-value t
18407 texmathp-why '("Org-mode embedded math" . 0))
18408 (if p ad-do-it)))))))))
18410 (defun turn-on-org-cdlatex ()
18411 "Unconditionally turn on `org-cdlatex-mode'."
18412 (org-cdlatex-mode 1))
18414 (defun org-try-cdlatex-tab ()
18415 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18416 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18417 - inside a LaTeX fragment, or
18418 - after the first word in a line, where an abbreviation expansion could
18419 insert a LaTeX environment."
18420 (when org-cdlatex-mode
18421 (cond
18422 ;; Before any word on the line: No expansion possible.
18423 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18424 ;; Just after first word on the line: Expand it. Make sure it
18425 ;; cannot happen on headlines, though.
18426 ((save-excursion
18427 (skip-chars-backward "a-zA-Z0-9*")
18428 (skip-chars-backward " \t")
18429 (and (bolp) (not (org-at-heading-p))))
18430 (cdlatex-tab) t)
18431 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18433 (defun org-cdlatex-underscore-caret (&optional arg)
18434 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18435 Revert to the normal definition outside of these fragments."
18436 (interactive "P")
18437 (if (org-inside-LaTeX-fragment-p)
18438 (call-interactively 'cdlatex-sub-superscript)
18439 (let (org-cdlatex-mode)
18440 (call-interactively (key-binding (vector last-input-event))))))
18442 (defun org-cdlatex-math-modify (&optional arg)
18443 "Execute `cdlatex-math-modify' in LaTeX fragments.
18444 Revert to the normal definition outside of these fragments."
18445 (interactive "P")
18446 (if (org-inside-LaTeX-fragment-p)
18447 (call-interactively 'cdlatex-math-modify)
18448 (let (org-cdlatex-mode)
18449 (call-interactively (key-binding (vector last-input-event))))))
18453 ;;;; LaTeX fragments
18455 (defun org-inside-LaTeX-fragment-p ()
18456 "Test if point is inside a LaTeX fragment.
18457 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18458 sequence appearing also before point.
18459 Even though the matchers for math are configurable, this function assumes
18460 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18461 delimiters are skipped when they have been removed by customization.
18462 The return value is nil, or a cons cell with the delimiter and the
18463 position of this delimiter.
18465 This function does a reasonably good job, but can locally be fooled by
18466 for example currency specifications. For example it will assume being in
18467 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18468 fragments that are properly closed, but during editing, we have to live
18469 with the uncertainty caused by missing closing delimiters. This function
18470 looks only before point, not after."
18471 (catch 'exit
18472 (let ((pos (point))
18473 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18474 (lim (progn
18475 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18476 (point)))
18477 dd-on str (start 0) m re)
18478 (goto-char pos)
18479 (when dodollar
18480 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18481 re (nth 1 (assoc "$" org-latex-regexps)))
18482 (while (string-match re str start)
18483 (cond
18484 ((= (match-end 0) (length str))
18485 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18486 ((= (match-end 0) (- (length str) 5))
18487 (throw 'exit nil))
18488 (t (setq start (match-end 0))))))
18489 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18490 (goto-char pos)
18491 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18492 (and (match-beginning 2) (throw 'exit nil))
18493 ;; count $$
18494 (while (re-search-backward "\\$\\$" lim t)
18495 (setq dd-on (not dd-on)))
18496 (goto-char pos)
18497 (if dd-on (cons "$$" m))))))
18499 (defun org-inside-latex-macro-p ()
18500 "Is point inside a LaTeX macro or its arguments?"
18501 (save-match-data
18502 (org-in-regexp
18503 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18505 (defvar org-latex-fragment-image-overlays nil
18506 "List of overlays carrying the images of latex fragments.")
18507 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18509 (defun org-remove-latex-fragment-image-overlays ()
18510 "Remove all overlays with LaTeX fragment images in current buffer."
18511 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18512 (setq org-latex-fragment-image-overlays nil))
18514 (defun org-preview-latex-fragment (&optional subtree)
18515 "Preview the LaTeX fragment at point, or all locally or globally.
18516 If the cursor is in a LaTeX fragment, create the image and overlay
18517 it over the source code. If there is no fragment at point, display
18518 all fragments in the current text, from one headline to the next. With
18519 prefix SUBTREE, display all fragments in the current subtree. With a
18520 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18521 the cursor is before the first headline,
18522 display all fragments in the buffer.
18523 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18524 (interactive "P")
18525 (unless buffer-file-name
18526 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18527 (when (display-graphic-p)
18528 (org-remove-latex-fragment-image-overlays)
18529 (save-excursion
18530 (save-restriction
18531 (let (beg end at msg)
18532 (cond
18533 ((or (equal subtree '(16))
18534 (not (save-excursion
18535 (re-search-backward org-outline-regexp-bol nil t))))
18536 (setq beg (point-min) end (point-max)
18537 msg "Creating images for buffer...%s"))
18538 ((equal subtree '(4))
18539 (org-back-to-heading)
18540 (setq beg (point) end (org-end-of-subtree t)
18541 msg "Creating images for subtree...%s"))
18543 (if (setq at (org-inside-LaTeX-fragment-p))
18544 (goto-char (max (point-min) (- (cdr at) 2)))
18545 (org-back-to-heading))
18546 (setq beg (point) end (progn (outline-next-heading) (point))
18547 msg (if at "Creating image...%s"
18548 "Creating images for entry...%s"))))
18549 (message msg "")
18550 (narrow-to-region beg end)
18551 (goto-char beg)
18552 (org-format-latex
18553 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18554 (file-name-nondirectory
18555 buffer-file-name)))
18556 default-directory 'overlays msg at 'forbuffer
18557 org-latex-create-formula-image-program)
18558 (message msg "done. Use `C-c C-c' to remove images."))))))
18560 (defun org-format-latex (prefix &optional dir overlays msg at
18561 forbuffer processing-type)
18562 "Replace LaTeX fragments with links to an image, and produce images.
18563 Some of the options can be changed using the variable
18564 `org-format-latex-options'."
18565 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18566 (let* ((prefixnodir (file-name-nondirectory prefix))
18567 (absprefix (expand-file-name prefix dir))
18568 (todir (file-name-directory absprefix))
18569 (opt org-format-latex-options)
18570 (optnew org-format-latex-options)
18571 (matchers (plist-get opt :matchers))
18572 (re-list org-latex-regexps)
18573 (cnt 0) txt hash link beg end re e checkdir
18574 string
18575 m n block-type block linkfile movefile ov)
18576 ;; Check the different regular expressions
18577 (while (setq e (pop re-list))
18578 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18579 block (if block-type "\n\n" ""))
18580 (when (member m matchers)
18581 (goto-char (point-min))
18582 (while (re-search-forward re nil t)
18583 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18584 (or (not overlays)
18585 (not (eq (get-char-property (match-beginning n)
18586 'org-overlay-type)
18587 'org-latex-overlay))))
18588 (cond
18589 ((eq processing-type 'verbatim))
18590 ((eq processing-type 'mathjax)
18591 ;; Prepare for MathJax processing.
18592 (setq string (match-string n))
18593 (when (member m '("$" "$1"))
18594 (save-excursion
18595 (delete-region (match-beginning n) (match-end n))
18596 (goto-char (match-beginning n))
18597 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18598 ((or (eq processing-type 'dvipng)
18599 (eq processing-type 'imagemagick))
18600 ;; Process to an image.
18601 (setq txt (match-string n)
18602 beg (match-beginning n) end (match-end n)
18603 cnt (1+ cnt))
18604 (let ((face (face-at-point))
18605 (fg (plist-get opt :foreground))
18606 (bg (plist-get opt :background))
18607 ;; Ensure full list is printed.
18608 print-length print-level)
18609 (when forbuffer
18610 ;; Get the colors from the face at point.
18611 (goto-char beg)
18612 (when (eq fg 'auto)
18613 (setq fg (face-attribute face :foreground nil 'default)))
18614 (when (eq bg 'auto)
18615 (setq bg (face-attribute face :background nil 'default)))
18616 (setq optnew (copy-sequence opt))
18617 (plist-put optnew :foreground fg)
18618 (plist-put optnew :background bg))
18619 (setq hash (sha1 (prin1-to-string
18620 (list org-format-latex-header
18621 org-latex-default-packages-alist
18622 org-latex-packages-alist
18623 org-format-latex-options
18624 forbuffer txt fg bg)))
18625 linkfile (format "%s_%s.png" prefix hash)
18626 movefile (format "%s_%s.png" absprefix hash)))
18627 (setq link (concat block "[[file:" linkfile "]]" block))
18628 (if msg (message msg cnt))
18629 (goto-char beg)
18630 (unless checkdir ; Ensure the directory exists.
18631 (setq checkdir t)
18632 (or (file-directory-p todir) (make-directory todir t)))
18633 (unless (file-exists-p movefile)
18634 (org-create-formula-image
18635 txt movefile optnew forbuffer processing-type))
18636 (if overlays
18637 (progn
18638 (mapc (lambda (o)
18639 (if (eq (overlay-get o 'org-overlay-type)
18640 'org-latex-overlay)
18641 (delete-overlay o)))
18642 (overlays-in beg end))
18643 (setq ov (make-overlay beg end))
18644 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18645 (if (featurep 'xemacs)
18646 (progn
18647 (overlay-put ov 'invisible t)
18648 (overlay-put
18649 ov 'end-glyph
18650 (make-glyph (vector 'png :file movefile))))
18651 (overlay-put
18652 ov 'display
18653 (list 'image :type 'png :file movefile :ascent 'center)))
18654 (push ov org-latex-fragment-image-overlays)
18655 (goto-char end))
18656 (delete-region beg end)
18657 (insert (org-add-props link
18658 (list 'org-latex-src
18659 (replace-regexp-in-string
18660 "\"" "" txt)
18661 'org-latex-src-embed-type
18662 (if block-type 'paragraph 'character))))))
18663 ((eq processing-type 'mathml)
18664 ;; Process to MathML
18665 (unless (save-match-data (org-format-latex-mathml-available-p))
18666 (user-error "LaTeX to MathML converter not configured"))
18667 (setq txt (match-string n)
18668 beg (match-beginning n) end (match-end n)
18669 cnt (1+ cnt))
18670 (if msg (message msg cnt))
18671 (goto-char beg)
18672 (delete-region beg end)
18673 (insert (org-format-latex-as-mathml
18674 txt block-type prefix dir)))
18676 (error "Unknown conversion type %s for LaTeX fragments"
18677 processing-type)))))))))
18679 (defun org-create-math-formula (latex-frag &optional mathml-file)
18680 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18681 Use `org-latex-to-mathml-convert-command'. If the conversion is
18682 sucessful, return the portion between \"<math...> </math>\"
18683 elements otherwise return nil. When MATHML-FILE is specified,
18684 write the results in to that file. When invoked as an
18685 interactive command, prompt for LATEX-FRAG, with initial value
18686 set to the current active region and echo the results for user
18687 inspection."
18688 (interactive (list (let ((frag (when (org-region-active-p)
18689 (buffer-substring-no-properties
18690 (region-beginning) (region-end)))))
18691 (read-string "LaTeX Fragment: " frag nil frag))))
18692 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18693 (let* ((tmp-in-file (file-relative-name
18694 (make-temp-name (expand-file-name "ltxmathml-in"))))
18695 (ignore (write-region latex-frag nil tmp-in-file))
18696 (tmp-out-file (file-relative-name
18697 (make-temp-name (expand-file-name "ltxmathml-out"))))
18698 (cmd (format-spec
18699 org-latex-to-mathml-convert-command
18700 `((?j . ,(shell-quote-argument
18701 (expand-file-name org-latex-to-mathml-jar-file)))
18702 (?I . ,(shell-quote-argument tmp-in-file))
18703 (?o . ,(shell-quote-argument tmp-out-file)))))
18704 mathml shell-command-output)
18705 (when (org-called-interactively-p 'any)
18706 (unless (org-format-latex-mathml-available-p)
18707 (user-error "LaTeX to MathML converter not configured")))
18708 (message "Running %s" cmd)
18709 (setq shell-command-output (shell-command-to-string cmd))
18710 (setq mathml
18711 (when (file-readable-p tmp-out-file)
18712 (with-current-buffer (find-file-noselect tmp-out-file t)
18713 (goto-char (point-min))
18714 (when (re-search-forward
18715 (concat
18716 (regexp-quote
18717 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18718 "\\(.\\|\n\\)*"
18719 (regexp-quote "</math>")) nil t)
18720 (prog1 (match-string 0) (kill-buffer))))))
18721 (cond
18722 (mathml
18723 (setq mathml
18724 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18725 (when mathml-file
18726 (write-region mathml nil mathml-file))
18727 (when (org-called-interactively-p 'any)
18728 (message mathml)))
18729 ((message "LaTeX to MathML conversion failed")
18730 (message shell-command-output)))
18731 (delete-file tmp-in-file)
18732 (when (file-exists-p tmp-out-file)
18733 (delete-file tmp-out-file))
18734 mathml))
18736 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18737 prefix &optional dir)
18738 "Use `org-create-math-formula' but check local cache first."
18739 (let* ((absprefix (expand-file-name prefix dir))
18740 (print-length nil) (print-level nil)
18741 (formula-id (concat
18742 "formula-"
18743 (sha1
18744 (prin1-to-string
18745 (list latex-frag
18746 org-latex-to-mathml-convert-command)))))
18747 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18748 (formula-cache-dir (file-name-directory formula-cache)))
18750 (unless (file-directory-p formula-cache-dir)
18751 (make-directory formula-cache-dir t))
18753 (unless (file-exists-p formula-cache)
18754 (org-create-math-formula latex-frag formula-cache))
18756 (if (file-exists-p formula-cache)
18757 ;; Successful conversion. Return the link to MathML file.
18758 (org-add-props
18759 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18760 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18761 'org-latex-src-embed-type (if latex-frag-type
18762 'paragraph 'character)))
18763 ;; Failed conversion. Return the LaTeX fragment verbatim
18764 latex-frag)))
18766 (defun org-create-formula-image (string tofile options buffer &optional type)
18767 "Create an image from LaTeX source using dvipng or convert.
18768 This function calls either `org-create-formula-image-with-dvipng'
18769 or `org-create-formula-image-with-imagemagick' depending on the
18770 value of `org-latex-create-formula-image-program' or on the value
18771 of the optional TYPE variable.
18773 Note: ultimately these two function should be combined as they
18774 share a good deal of logic."
18775 (org-check-external-command
18776 "latex" "needed to convert LaTeX fragments to images")
18777 (funcall
18778 (case (or type org-latex-create-formula-image-program)
18779 ('dvipng
18780 (org-check-external-command
18781 "dvipng" "needed to convert LaTeX fragments to images")
18782 #'org-create-formula-image-with-dvipng)
18783 ('imagemagick
18784 (org-check-external-command
18785 "convert" "you need to install imagemagick")
18786 #'org-create-formula-image-with-imagemagick)
18787 (t (error
18788 "Invalid value of `org-latex-create-formula-image-program'")))
18789 string tofile options buffer))
18791 (declare-function org-export-get-backend "ox" (name))
18792 (declare-function org-export--get-global-options "ox" (&optional backend))
18793 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18794 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18795 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18796 (defun org-create-formula--latex-header ()
18797 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18798 (let ((info (org-combine-plists (org-export--get-global-options
18799 (org-export-get-backend 'latex))
18800 (org-export--get-inbuffer-options
18801 (org-export-get-backend 'latex)))))
18802 (org-latex-guess-babel-language
18803 (org-latex-guess-inputenc
18804 (org-splice-latex-header
18805 org-format-latex-header
18806 org-latex-default-packages-alist
18807 org-latex-packages-alist t
18808 (plist-get info :latex-header)))
18809 info)))
18811 ;; This function borrows from Ganesh Swami's latex2png.el
18812 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18813 "This calls dvipng."
18814 (require 'ox-latex)
18815 (let* ((tmpdir (if (featurep 'xemacs)
18816 (temp-directory)
18817 temporary-file-directory))
18818 (texfilebase (make-temp-name
18819 (expand-file-name "orgtex" tmpdir)))
18820 (texfile (concat texfilebase ".tex"))
18821 (dvifile (concat texfilebase ".dvi"))
18822 (pngfile (concat texfilebase ".png"))
18823 (fnh (if (featurep 'xemacs)
18824 (font-height (face-font 'default))
18825 (face-attribute 'default :height nil)))
18826 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18827 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18828 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18829 "Black"))
18830 (bg (or (plist-get options (if buffer :background :html-background))
18831 "Transparent")))
18832 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18833 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18834 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18835 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18836 (let ((latex-header (org-create-formula--latex-header)))
18837 (with-temp-file texfile
18838 (insert latex-header)
18839 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18840 (let ((dir default-directory))
18841 (condition-case nil
18842 (progn
18843 (cd tmpdir)
18844 (call-process "latex" nil nil nil texfile))
18845 (error nil))
18846 (cd dir))
18847 (if (not (file-exists-p dvifile))
18848 (progn (message "Failed to create dvi file from %s" texfile) nil)
18849 (condition-case nil
18850 (if (featurep 'xemacs)
18851 (call-process "dvipng" nil nil nil
18852 "-fg" fg "-bg" bg
18853 "-T" "tight"
18854 "-o" pngfile
18855 dvifile)
18856 (call-process "dvipng" nil nil nil
18857 "-fg" fg "-bg" bg
18858 "-D" dpi
18859 ;;"-x" scale "-y" scale
18860 "-T" "tight"
18861 "-o" pngfile
18862 dvifile))
18863 (error nil))
18864 (if (not (file-exists-p pngfile))
18865 (if org-format-latex-signal-error
18866 (error "Failed to create png file from %s" texfile)
18867 (message "Failed to create png file from %s" texfile)
18868 nil)
18869 ;; Use the requested file name and clean up
18870 (copy-file pngfile tofile 'replace)
18871 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18872 (if (file-exists-p (concat texfilebase e))
18873 (delete-file (concat texfilebase e))))
18874 pngfile))))
18876 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18877 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18878 "This calls convert, which is included into imagemagick."
18879 (require 'ox-latex)
18880 (let* ((tmpdir (if (featurep 'xemacs)
18881 (temp-directory)
18882 temporary-file-directory))
18883 (texfilebase (make-temp-name
18884 (expand-file-name "orgtex" tmpdir)))
18885 (texfile (concat texfilebase ".tex"))
18886 (pdffile (concat texfilebase ".pdf"))
18887 (pngfile (concat texfilebase ".png"))
18888 (fnh (if (featurep 'xemacs)
18889 (font-height (face-font 'default))
18890 (face-attribute 'default :height nil)))
18891 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18892 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18893 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18894 "black"))
18895 (bg (or (plist-get options (if buffer :background :html-background))
18896 "white")))
18897 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18898 (setq fg (org-latex-color-format fg)))
18899 (if (eq bg 'default) (setq bg (org-latex-color :background))
18900 (setq bg (org-latex-color-format
18901 (if (string= bg "Transparent") "white" bg))))
18902 (let ((latex-header (org-create-formula--latex-header)))
18903 (with-temp-file texfile
18904 (insert latex-header)
18905 (insert "\n\\begin{document}\n"
18906 "\\definecolor{fg}{rgb}{" fg "}\n"
18907 "\\definecolor{bg}{rgb}{" bg "}\n"
18908 "\n\\pagecolor{bg}\n"
18909 "\n{\\color{fg}\n"
18910 string
18911 "\n}\n"
18912 "\n\\end{document}\n")))
18913 (org-latex-compile texfile t)
18914 (if (not (file-exists-p pdffile))
18915 (progn (message "Failed to create pdf file from %s" texfile) nil)
18916 (condition-case nil
18917 (if (featurep 'xemacs)
18918 (call-process "convert" nil nil nil
18919 "-density" "96"
18920 "-trim"
18921 "-antialias"
18922 pdffile
18923 "-quality" "100"
18924 ;; "-sharpen" "0x1.0"
18925 pngfile)
18926 (call-process "convert" nil nil nil
18927 "-density" dpi
18928 "-trim"
18929 "-antialias"
18930 pdffile
18931 "-quality" "100"
18932 ;; "-sharpen" "0x1.0"
18933 pngfile))
18934 (error nil))
18935 (if (not (file-exists-p pngfile))
18936 (if org-format-latex-signal-error
18937 (error "Failed to create png file from %s" texfile)
18938 (message "Failed to create png file from %s" texfile)
18939 nil)
18940 ;; Use the requested file name and clean up
18941 (copy-file pngfile tofile 'replace)
18942 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18943 (if (file-exists-p (concat texfilebase e))
18944 (delete-file (concat texfilebase e))))
18945 pngfile))))
18947 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18948 "Fill a LaTeX header template TPL.
18949 In the template, the following place holders will be recognized:
18951 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18952 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18953 [PACKAGES] \\usepackage statements for PKG
18954 [NO-PACKAGES] do not include PKG
18955 [EXTRA] the string EXTRA
18956 [NO-EXTRA] do not include EXTRA
18958 For backward compatibility, if both the positive and the negative place
18959 holder is missing, the positive one (without the \"NO-\") will be
18960 assumed to be present at the end of the template.
18961 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18962 EXTRA is a string.
18963 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18964 (let (rpl (end ""))
18965 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18966 (setq rpl (if (or (match-end 1) (not def-pkg))
18967 "" (org-latex-packages-to-string def-pkg snippets-p t))
18968 tpl (replace-match rpl t t tpl))
18969 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18971 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18972 (setq rpl (if (or (match-end 1) (not pkg))
18973 "" (org-latex-packages-to-string pkg snippets-p t))
18974 tpl (replace-match rpl t t tpl))
18975 (if pkg (setq end
18976 (concat end "\n"
18977 (org-latex-packages-to-string pkg snippets-p)))))
18979 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18980 (setq rpl (if (or (match-end 1) (not extra))
18981 "" (concat extra "\n"))
18982 tpl (replace-match rpl t t tpl))
18983 (if (and extra (string-match "\\S-" extra))
18984 (setq end (concat end "\n" extra))))
18986 (if (string-match "\\S-" end)
18987 (concat tpl "\n" end)
18988 tpl)))
18990 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18991 "Turn an alist of packages into a string with the \\usepackage macros."
18992 (setq pkg (mapconcat (lambda(p)
18993 (cond
18994 ((stringp p) p)
18995 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18996 (format "%% Package %s omitted" (cadr p)))
18997 ((equal "" (car p))
18998 (format "\\usepackage{%s}" (cadr p)))
19000 (format "\\usepackage[%s]{%s}"
19001 (car p) (cadr p)))))
19003 "\n"))
19004 (if newline (concat pkg "\n") pkg))
19006 (defun org-dvipng-color (attr)
19007 "Return a RGB color specification for dvipng."
19008 (apply 'format "rgb %s %s %s"
19009 (mapcar 'org-normalize-color
19010 (if (featurep 'xemacs)
19011 (color-rgb-components
19012 (face-property 'default
19013 (cond ((eq attr :foreground) 'foreground)
19014 ((eq attr :background) 'background))))
19015 (color-values (face-attribute 'default attr nil))))))
19017 (defun org-dvipng-color-format (color-name)
19018 "Convert COLOR-NAME to a RGB color value for dvipng."
19019 (apply 'format "rgb %s %s %s"
19020 (mapcar 'org-normalize-color
19021 (color-values color-name))))
19023 (defun org-latex-color (attr)
19024 "Return a RGB color for the LaTeX color package."
19025 (apply 'format "%s,%s,%s"
19026 (mapcar 'org-normalize-color
19027 (if (featurep 'xemacs)
19028 (color-rgb-components
19029 (face-property 'default
19030 (cond ((eq attr :foreground) 'foreground)
19031 ((eq attr :background) 'background))))
19032 (color-values (face-attribute 'default attr nil))))))
19034 (defun org-latex-color-format (color-name)
19035 "Convert COLOR-NAME to a RGB color value."
19036 (apply 'format "%s,%s,%s"
19037 (mapcar 'org-normalize-color
19038 (color-values color-name))))
19040 (defun org-normalize-color (value)
19041 "Return string to be used as color value for an RGB component."
19042 (format "%g" (/ value 65535.0)))
19046 ;; Image display
19048 (defvar org-inline-image-overlays nil)
19049 (make-variable-buffer-local 'org-inline-image-overlays)
19051 (defun org-toggle-inline-images (&optional include-linked)
19052 "Toggle the display of inline images.
19053 INCLUDE-LINKED is passed to `org-display-inline-images'."
19054 (interactive "P")
19055 (if org-inline-image-overlays
19056 (progn
19057 (org-remove-inline-images)
19058 (message "Inline image display turned off"))
19059 (org-display-inline-images include-linked)
19060 (if (and (org-called-interactively-p)
19061 org-inline-image-overlays)
19062 (message "%d images displayed inline"
19063 (length org-inline-image-overlays))
19064 (message "No images to display inline"))))
19066 (defun org-redisplay-inline-images ()
19067 "Refresh the display of inline images."
19068 (interactive)
19069 (if (not org-inline-image-overlays)
19070 (org-toggle-inline-images)
19071 (org-toggle-inline-images)
19072 (org-toggle-inline-images)))
19074 (defun org-display-inline-images (&optional include-linked refresh beg end)
19075 "Display inline images.
19077 An inline image is a link which follows either of these
19078 conventions:
19080 1. Its path is a file with an extension matching return value
19081 from `image-file-name-regexp' and it has no contents.
19083 2. Its description consists in a single link of the previous
19084 type.
19086 When optional argument INCLUDE-LINKED is non-nil, also links with
19087 a text description part will be inlined. This can be nice for
19088 a quick look at those images, but it does not reflect what
19089 exported files will look like.
19091 When optional argument REFRESH is non-nil, refresh existing
19092 images between BEG and END. This will create new image displays
19093 only if necessary. BEG and END default to the buffer
19094 boundaries."
19095 (interactive "P")
19096 (when (display-graphic-p)
19097 (unless refresh
19098 (org-remove-inline-images)
19099 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19100 (org-with-wide-buffer
19101 (goto-char (or beg (point-min)))
19102 (let ((case-fold-search t)
19103 (file-extension-re (org-image-file-name-regexp)))
19104 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19105 (let ((link (save-match-data (org-element-context))))
19106 ;; Check if we're at an inline image.
19107 (when (and (equal (org-element-property :type link) "file")
19108 (or include-linked
19109 (not (org-element-property :contents-begin link)))
19110 (let ((parent (org-element-property :parent link)))
19111 (or (not (eq (org-element-type parent) 'link))
19112 (not (cdr (org-element-contents parent)))))
19113 (org-string-match-p file-extension-re
19114 (org-element-property :path link)))
19115 (let ((file (expand-file-name (org-element-property :path link))))
19116 (when (file-exists-p file)
19117 (let ((width
19118 ;; Apply `org-image-actual-width' specifications.
19119 (cond
19120 ((not (image-type-available-p 'imagemagick)) nil)
19121 ((eq org-image-actual-width t) nil)
19122 ((listp org-image-actual-width)
19124 ;; First try to find a width among
19125 ;; attributes associated to the paragraph
19126 ;; containing link.
19127 (let ((paragraph
19128 (let ((e link))
19129 (while (and (setq e (org-element-property
19130 :parent e))
19131 (not (eq (org-element-type e)
19132 'paragraph))))
19133 e)))
19134 (when paragraph
19135 (save-excursion
19136 (goto-char (org-element-property :begin paragraph))
19137 (when (save-match-data
19138 (re-search-forward
19139 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19140 (org-element-property
19141 :post-affiliated paragraph)
19143 (string-to-number (match-string 1))))))
19144 ;; Otherwise, fall-back to provided number.
19145 (car org-image-actual-width)))
19146 ((numberp org-image-actual-width)
19147 org-image-actual-width)))
19148 (old (get-char-property-and-overlay
19149 (org-element-property :begin link)
19150 'org-image-overlay)))
19151 (if (and (car-safe old) refresh)
19152 (image-refresh (overlay-get (cdr old) 'display))
19153 (let ((image (save-match-data
19154 (create-image file
19155 (and width 'imagemagick)
19157 :width width))))
19158 (when image
19159 (let* ((link
19160 ;; If inline image is the description
19161 ;; of another link, be sure to
19162 ;; consider the latter as the one to
19163 ;; apply the overlay on.
19164 (let ((parent
19165 (org-element-property :parent link)))
19166 (if (eq (org-element-type parent) 'link)
19167 parent
19168 link)))
19169 (ov (make-overlay
19170 (org-element-property :begin link)
19171 (progn
19172 (goto-char
19173 (org-element-property :end link))
19174 (skip-chars-backward " \t")
19175 (point)))))
19176 (overlay-put ov 'display image)
19177 (overlay-put ov 'face 'default)
19178 (overlay-put ov 'org-image-overlay t)
19179 (overlay-put
19180 ov 'modification-hooks
19181 (list 'org-display-inline-remove-overlay))
19182 (push ov org-inline-image-overlays)))))))))))))))
19184 (define-obsolete-function-alias
19185 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19187 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19188 "Remove inline-display overlay if a corresponding region is modified."
19189 (let ((inhibit-modification-hooks t))
19190 (when (and ov after)
19191 (delete ov org-inline-image-overlays)
19192 (delete-overlay ov))))
19194 (defun org-remove-inline-images ()
19195 "Remove inline display of images."
19196 (interactive)
19197 (mapc 'delete-overlay org-inline-image-overlays)
19198 (setq org-inline-image-overlays nil))
19200 ;;;; Key bindings
19202 ;; Outline functions from `outline-mode-prefix-map'
19203 ;; that can be remapped in Org:
19204 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19205 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19206 (define-key org-mode-map [remap outline-forward-same-level]
19207 'org-forward-heading-same-level)
19208 (define-key org-mode-map [remap outline-backward-same-level]
19209 'org-backward-heading-same-level)
19210 (define-key org-mode-map [remap show-branches]
19211 'org-kill-note-or-show-branches)
19212 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19213 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19214 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19216 ;; Outline functions from `outline-mode-prefix-map' that can not
19217 ;; be remapped in Org:
19219 ;; - the column "key binding" shows whether the Outline function is still
19220 ;; available in Org mode on the same key that it has been bound to in
19221 ;; Outline mode:
19222 ;; - "overridden": key used for a different functionality in Org mode
19223 ;; - else: key still bound to the same Outline function in Org mode
19225 ;; | Outline function | key binding | Org replacement |
19226 ;; |------------------------------------+-------------+-----------------------|
19227 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19228 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19229 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19230 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19231 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19232 ;; | `show-entry' | overridden | no replacement |
19233 ;; | `show-children' | `C-c C-i' | visibility cycling |
19234 ;; | `show-branches' | `C-c C-k' | still same function |
19235 ;; | `show-subtree' | overridden | visibility cycling |
19236 ;; | `show-all' | overridden | no replacement |
19237 ;; | `hide-subtree' | overridden | visibility cycling |
19238 ;; | `hide-body' | overridden | no replacement |
19239 ;; | `hide-entry' | overridden | visibility cycling |
19240 ;; | `hide-leaves' | overridden | no replacement |
19241 ;; | `hide-sublevels' | overridden | no replacement |
19242 ;; | `hide-other' | overridden | no replacement |
19244 ;; Make `C-c C-x' a prefix key
19245 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19247 ;; TAB key with modifiers
19248 (org-defkey org-mode-map "\C-i" 'org-cycle)
19249 (org-defkey org-mode-map [(tab)] 'org-cycle)
19250 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19251 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19252 ;; The following line is necessary under Suse GNU/Linux
19253 (unless (featurep 'xemacs)
19254 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19255 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19256 (define-key org-mode-map [backtab] 'org-shifttab)
19258 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19259 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19260 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19262 ;; Cursor keys with modifiers
19263 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19264 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19265 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19266 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19268 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19269 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19270 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19271 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19272 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19273 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19275 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19276 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19277 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19278 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19280 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19281 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19282 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19283 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19285 ;; Babel keys
19286 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19287 (mapc (lambda (pair)
19288 (define-key org-babel-map (car pair) (cdr pair)))
19289 org-babel-key-bindings)
19291 ;;; Extra keys for tty access.
19292 ;; We only set them when really needed because otherwise the
19293 ;; menus don't show the simple keys
19295 (when (or org-use-extra-keys
19296 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19297 (not window-system))
19298 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19299 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19300 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19301 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19302 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19303 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19304 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19305 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19306 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19307 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19308 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19309 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19310 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19311 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19312 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19313 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19314 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19315 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19316 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19317 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19318 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19319 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19320 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19321 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19322 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19323 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19324 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19325 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19327 ;; All the other keys
19329 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19330 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19331 (if (boundp 'narrow-map)
19332 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19333 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19334 (if (boundp 'narrow-map)
19335 (org-defkey narrow-map "b" 'org-narrow-to-block)
19336 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19337 (if (boundp 'narrow-map)
19338 (org-defkey narrow-map "e" 'org-narrow-to-element)
19339 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19340 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19341 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19342 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19343 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19344 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19345 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19346 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19347 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19348 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19349 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19350 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19351 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19352 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19353 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19354 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19355 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19356 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19357 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19358 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19359 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19360 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19361 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19362 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19363 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19364 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19365 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19366 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19367 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19368 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19369 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19370 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19371 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19372 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19373 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19374 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19375 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19376 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19377 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19378 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19379 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19380 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19381 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19382 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19383 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19384 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19385 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19386 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19387 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19388 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19389 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19390 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19391 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19392 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19393 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19394 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19395 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19396 (org-defkey org-mode-map "\C-c^" 'org-sort)
19397 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19398 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19399 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19400 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19401 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19402 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19403 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19404 (org-defkey org-mode-map "\C-m" 'org-return)
19405 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19406 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19407 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19408 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19409 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19410 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19411 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19412 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19413 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19414 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19415 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19416 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19417 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19418 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19419 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19420 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19421 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19422 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19423 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19424 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19425 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19426 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19427 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19429 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19430 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19431 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19433 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19434 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19435 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19436 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19437 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19438 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19439 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19440 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19441 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19442 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19443 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19444 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19445 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19446 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19447 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19448 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19449 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19450 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19451 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19452 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19453 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19454 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19455 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19457 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19458 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19459 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19460 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19461 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19463 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19465 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19467 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19468 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19470 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19473 (when (featurep 'xemacs)
19474 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19477 (defconst org-speed-commands-default
19479 ("Outline Navigation")
19480 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19481 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19482 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19483 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19484 ("F" . org-next-block)
19485 ("B" . org-previous-block)
19486 ("u" . (org-speed-move-safe 'outline-up-heading))
19487 ("j" . org-goto)
19488 ("g" . (org-refile t))
19489 ("Outline Visibility")
19490 ("c" . org-cycle)
19491 ("C" . org-shifttab)
19492 (" " . org-display-outline-path)
19493 ("s" . org-narrow-to-subtree)
19494 ("=" . org-columns)
19495 ("Outline Structure Editing")
19496 ("U" . org-shiftmetaup)
19497 ("D" . org-shiftmetadown)
19498 ("r" . org-metaright)
19499 ("l" . org-metaleft)
19500 ("R" . org-shiftmetaright)
19501 ("L" . org-shiftmetaleft)
19502 ("i" . (progn (forward-char 1) (call-interactively
19503 'org-insert-heading-respect-content)))
19504 ("^" . org-sort)
19505 ("w" . org-refile)
19506 ("a" . org-archive-subtree-default-with-confirmation)
19507 ("@" . org-mark-subtree)
19508 ("#" . org-toggle-comment)
19509 ("Clock Commands")
19510 ("I" . org-clock-in)
19511 ("O" . org-clock-out)
19512 ("Meta Data Editing")
19513 ("t" . org-todo)
19514 ("," . (org-priority))
19515 ("0" . (org-priority ?\ ))
19516 ("1" . (org-priority ?A))
19517 ("2" . (org-priority ?B))
19518 ("3" . (org-priority ?C))
19519 (":" . org-set-tags-command)
19520 ("e" . org-set-effort)
19521 ("E" . org-inc-effort)
19522 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19523 (org-entry-put (point) "APPT_WARNTIME" m)))
19524 ("Agenda Views etc")
19525 ("v" . org-agenda)
19526 ("/" . org-sparse-tree)
19527 ("Misc")
19528 ("o" . org-open-at-point)
19529 ("?" . org-speed-command-help)
19530 ("<" . (org-agenda-set-restriction-lock 'subtree))
19531 (">" . (org-agenda-remove-restriction-lock))
19533 "The default speed commands.")
19535 (defun org-print-speed-command (e)
19536 (if (> (length (car e)) 1)
19537 (progn
19538 (princ "\n")
19539 (princ (car e))
19540 (princ "\n")
19541 (princ (make-string (length (car e)) ?-))
19542 (princ "\n"))
19543 (princ (car e))
19544 (princ " ")
19545 (if (symbolp (cdr e))
19546 (princ (symbol-name (cdr e)))
19547 (prin1 (cdr e)))
19548 (princ "\n")))
19550 (defun org-speed-command-help ()
19551 "Show the available speed commands."
19552 (interactive)
19553 (if (not org-use-speed-commands)
19554 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19555 (with-output-to-temp-buffer "*Help*"
19556 (princ "User-defined Speed commands\n===========================\n")
19557 (mapc 'org-print-speed-command org-speed-commands-user)
19558 (princ "\n")
19559 (princ "Built-in Speed commands\n=======================\n")
19560 (mapc 'org-print-speed-command org-speed-commands-default))
19561 (with-current-buffer "*Help*"
19562 (setq truncate-lines t))))
19564 (defun org-speed-move-safe (cmd)
19565 "Execute CMD, but make sure that the cursor always ends up in a headline.
19566 If not, return to the original position and throw an error."
19567 (interactive)
19568 (let ((pos (point)))
19569 (call-interactively cmd)
19570 (unless (and (bolp) (org-at-heading-p))
19571 (goto-char pos)
19572 (error "Boundary reached while executing %s" cmd))))
19574 (defvar org-self-insert-command-undo-counter 0)
19576 (defvar org-table-auto-blank-field) ; defined in org-table.el
19577 (defvar org-speed-command nil)
19579 (define-obsolete-function-alias
19580 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19582 (defun org-speed-command-activate (keys)
19583 "Hook for activating single-letter speed commands.
19584 `org-speed-commands-default' specifies a minimal command set.
19585 Use `org-speed-commands-user' for further customization."
19586 (when (or (and (bolp) (looking-at org-outline-regexp))
19587 (and (functionp org-use-speed-commands)
19588 (funcall org-use-speed-commands)))
19589 (cdr (assoc keys (append org-speed-commands-user
19590 org-speed-commands-default)))))
19592 (define-obsolete-function-alias
19593 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19595 (defun org-babel-speed-command-activate (keys)
19596 "Hook for activating single-letter code block commands."
19597 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19598 (cdr (assoc keys org-babel-key-bindings))))
19600 (defcustom org-speed-command-hook
19601 '(org-speed-command-default-hook org-babel-speed-command-hook)
19602 "Hook for activating speed commands at strategic locations.
19603 Hook functions are called in sequence until a valid handler is
19604 found.
19606 Each hook takes a single argument, a user-pressed command key
19607 which is also a `self-insert-command' from the global map.
19609 Within the hook, examine the cursor position and the command key
19610 and return nil or a valid handler as appropriate. Handler could
19611 be one of an interactive command, a function, or a form.
19613 Set `org-use-speed-commands' to non-nil value to enable this
19614 hook. The default setting is `org-speed-command-activate'."
19615 :group 'org-structure
19616 :version "24.1"
19617 :type 'hook)
19619 (defun org-self-insert-command (N)
19620 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19621 If the cursor is in a table looking at whitespace, the whitespace is
19622 overwritten, and the table is not marked as requiring realignment."
19623 (interactive "p")
19624 (org-check-before-invisible-edit 'insert)
19625 (cond
19626 ((and org-use-speed-commands
19627 (setq org-speed-command
19628 (run-hook-with-args-until-success
19629 'org-speed-command-hook (this-command-keys))))
19630 (cond
19631 ((commandp org-speed-command)
19632 (setq this-command org-speed-command)
19633 (call-interactively org-speed-command))
19634 ((functionp org-speed-command)
19635 (funcall org-speed-command))
19636 ((and org-speed-command (listp org-speed-command))
19637 (eval org-speed-command))
19638 (t (let (org-use-speed-commands)
19639 (call-interactively 'org-self-insert-command)))))
19640 ((and
19641 (org-table-p)
19642 (progn
19643 ;; check if we blank the field, and if that triggers align
19644 (and (featurep 'org-table) org-table-auto-blank-field
19645 (member last-command
19646 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19647 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19648 ;; got extra space, this field does not determine column width
19649 (let (org-table-may-need-update) (org-table-blank-field))
19650 ;; no extra space, this field may determine column width
19651 (org-table-blank-field)))
19653 (eq N 1)
19654 (looking-at "[^|\n]* |"))
19655 (let (org-table-may-need-update)
19656 (goto-char (1- (match-end 0)))
19657 (backward-delete-char 1)
19658 (goto-char (match-beginning 0))
19659 (self-insert-command N)))
19661 (setq org-table-may-need-update t)
19662 (self-insert-command N)
19663 (org-fix-tags-on-the-fly)
19664 (if org-self-insert-cluster-for-undo
19665 (if (not (eq last-command 'org-self-insert-command))
19666 (setq org-self-insert-command-undo-counter 1)
19667 (if (>= org-self-insert-command-undo-counter 20)
19668 (setq org-self-insert-command-undo-counter 1)
19669 (and (> org-self-insert-command-undo-counter 0)
19670 buffer-undo-list (listp buffer-undo-list)
19671 (not (cadr buffer-undo-list)) ; remove nil entry
19672 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19673 (setq org-self-insert-command-undo-counter
19674 (1+ org-self-insert-command-undo-counter))))))))
19676 (defun org-check-before-invisible-edit (kind)
19677 "Check is editing if kind KIND would be dangerous with invisible text around.
19678 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19679 ;; First, try to get out of here as quickly as possible, to reduce overhead
19680 (if (and org-catch-invisible-edits
19681 (or (not (boundp 'visible-mode)) (not visible-mode))
19682 (or (get-char-property (point) 'invisible)
19683 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19684 ;; OK, we need to take a closer look
19685 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19686 (invisible-before-point (if (bobp) nil (get-char-property
19687 (1- (point)) 'invisible)))
19688 (border-and-ok-direction
19690 ;; Check if we are acting predictably before invisible text
19691 (and invisible-at-point (not invisible-before-point)
19692 (memq kind '(insert delete-backward)))
19693 ;; Check if we are acting predictably after invisible text
19694 ;; This works not well, and I have turned it off. It seems
19695 ;; better to always show and stop after invisible text.
19696 ;; (and (not invisible-at-point) invisible-before-point
19697 ;; (memq kind '(insert delete)))
19699 (when (or (memq invisible-at-point '(outline org-hide-block t))
19700 (memq invisible-before-point '(outline org-hide-block t)))
19701 (if (eq org-catch-invisible-edits 'error)
19702 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19703 (if (and org-custom-properties-overlays
19704 (y-or-n-p "Display invisible properties in this buffer? "))
19705 (org-toggle-custom-properties-visibility)
19706 ;; Make the area visible
19707 (save-excursion
19708 (if invisible-before-point
19709 (goto-char (previous-single-char-property-change
19710 (point) 'invisible)))
19711 (show-subtree))
19712 (cond
19713 ((eq org-catch-invisible-edits 'show)
19714 ;; That's it, we do the edit after showing
19715 (message
19716 "Unfolding invisible region around point before editing")
19717 (sit-for 1))
19718 ((and (eq org-catch-invisible-edits 'smart)
19719 border-and-ok-direction)
19720 (message "Unfolding invisible region around point before editing"))
19722 ;; Don't do the edit, make the user repeat it in full visibility
19723 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19725 (defun org-fix-tags-on-the-fly ()
19726 (when (and (equal (char-after (point-at-bol)) ?*)
19727 (org-at-heading-p))
19728 (org-align-tags-here org-tags-column)))
19730 (defun org-delete-backward-char (N)
19731 "Like `delete-backward-char', insert whitespace at field end in tables.
19732 When deleting backwards, in tables this function will insert whitespace in
19733 front of the next \"|\" separator, to keep the table aligned. The table will
19734 still be marked for re-alignment if the field did fill the entire column,
19735 because, in this case the deletion might narrow the column."
19736 (interactive "p")
19737 (save-match-data
19738 (org-check-before-invisible-edit 'delete-backward)
19739 (if (and (org-table-p)
19740 (eq N 1)
19741 (string-match "|" (buffer-substring (point-at-bol) (point)))
19742 (looking-at ".*?|"))
19743 (let ((pos (point))
19744 (noalign (looking-at "[^|\n\r]* |"))
19745 (c org-table-may-need-update))
19746 (backward-delete-char N)
19747 (if (not overwrite-mode)
19748 (progn
19749 (skip-chars-forward "^|")
19750 (insert " ")
19751 (goto-char (1- pos))))
19752 ;; noalign: if there were two spaces at the end, this field
19753 ;; does not determine the width of the column.
19754 (if noalign (setq org-table-may-need-update c)))
19755 (backward-delete-char N)
19756 (org-fix-tags-on-the-fly))))
19758 (defun org-delete-char (N)
19759 "Like `delete-char', but insert whitespace at field end in tables.
19760 When deleting characters, in tables this function will insert whitespace in
19761 front of the next \"|\" separator, to keep the table aligned. The table will
19762 still be marked for re-alignment if the field did fill the entire column,
19763 because, in this case the deletion might narrow the column."
19764 (interactive "p")
19765 (save-match-data
19766 (org-check-before-invisible-edit 'delete)
19767 (if (and (org-table-p)
19768 (not (bolp))
19769 (not (= (char-after) ?|))
19770 (eq N 1))
19771 (if (looking-at ".*?|")
19772 (let ((pos (point))
19773 (noalign (looking-at "[^|\n\r]* |"))
19774 (c org-table-may-need-update))
19775 (replace-match
19776 (concat (substring (match-string 0) 1 -1) " |") nil t)
19777 (goto-char pos)
19778 ;; noalign: if there were two spaces at the end, this field
19779 ;; does not determine the width of the column.
19780 (if noalign (setq org-table-may-need-update c)))
19781 (delete-char N))
19782 (delete-char N)
19783 (org-fix-tags-on-the-fly))))
19785 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19786 (put 'org-self-insert-command 'delete-selection
19787 (lambda ()
19788 (not (run-hook-with-args-until-success
19789 'self-insert-uses-region-functions))))
19790 (put 'orgtbl-self-insert-command 'delete-selection
19791 (lambda ()
19792 (not (run-hook-with-args-until-success
19793 'self-insert-uses-region-functions))))
19794 (put 'org-delete-char 'delete-selection 'supersede)
19795 (put 'org-delete-backward-char 'delete-selection 'supersede)
19796 (put 'org-yank 'delete-selection 'yank)
19798 ;; Make `flyspell-mode' delay after some commands
19799 (put 'org-self-insert-command 'flyspell-delayed t)
19800 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19801 (put 'org-delete-char 'flyspell-delayed t)
19802 (put 'org-delete-backward-char 'flyspell-delayed t)
19804 ;; Make pabbrev-mode expand after org-mode commands
19805 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19806 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19808 (defun org-remap (map &rest commands)
19809 "In MAP, remap the functions given in COMMANDS.
19810 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19811 (let (new old)
19812 (while commands
19813 (setq old (pop commands) new (pop commands))
19814 (if (fboundp 'command-remapping)
19815 (org-defkey map (vector 'remap old) new)
19816 (substitute-key-definition old new map global-map)))))
19818 (defun org-transpose-words ()
19819 "Transpose words for Org.
19820 This uses the `org-mode-transpose-word-syntax-table' syntax
19821 table, which interprets characters in `org-emphasis-alist' as
19822 word constituents."
19823 (interactive)
19824 (with-syntax-table org-mode-transpose-word-syntax-table
19825 (call-interactively 'transpose-words)))
19826 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19828 (when (eq org-enable-table-editor 'optimized)
19829 ;; If the user wants maximum table support, we need to hijack
19830 ;; some standard editing functions
19831 (org-remap org-mode-map
19832 'self-insert-command 'org-self-insert-command
19833 'delete-char 'org-delete-char
19834 'delete-backward-char 'org-delete-backward-char)
19835 (org-defkey org-mode-map "|" 'org-force-self-insert))
19837 (defvar org-ctrl-c-ctrl-c-hook nil
19838 "Hook for functions attaching themselves to `C-c C-c'.
19840 This can be used to add additional functionality to the C-c C-c
19841 key which executes context-dependent commands. This hook is run
19842 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19843 run after the last test.
19845 Each function will be called with no arguments. The function
19846 must check if the context is appropriate for it to act. If yes,
19847 it should do its thing and then return a non-nil value. If the
19848 context is wrong, just do nothing and return nil.")
19850 (defvar org-ctrl-c-ctrl-c-final-hook nil
19851 "Hook for functions attaching themselves to `C-c C-c'.
19853 This can be used to add additional functionality to the C-c C-c
19854 key which executes context-dependent commands. This hook is run
19855 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19856 before the first test.
19858 Each function will be called with no arguments. The function
19859 must check if the context is appropriate for it to act. If yes,
19860 it should do its thing and then return a non-nil value. If the
19861 context is wrong, just do nothing and return nil.")
19863 (defvar org-tab-first-hook nil
19864 "Hook for functions to attach themselves to TAB.
19865 See `org-ctrl-c-ctrl-c-hook' for more information.
19866 This hook runs as the first action when TAB is pressed, even before
19867 `org-cycle' messes around with the `outline-regexp' to cater for
19868 inline tasks and plain list item folding.
19869 If any function in this hook returns t, any other actions that
19870 would have been caused by TAB (such as table field motion or visibility
19871 cycling) will not occur.")
19873 (defvar org-tab-after-check-for-table-hook nil
19874 "Hook for functions to attach themselves to TAB.
19875 See `org-ctrl-c-ctrl-c-hook' for more information.
19876 This hook runs after it has been established that the cursor is not in a
19877 table, but before checking if the cursor is in a headline or if global cycling
19878 should be done.
19879 If any function in this hook returns t, not other actions like visibility
19880 cycling will be done.")
19882 (defvar org-tab-after-check-for-cycling-hook nil
19883 "Hook for functions to attach themselves to TAB.
19884 See `org-ctrl-c-ctrl-c-hook' for more information.
19885 This hook runs after it has been established that not table field motion and
19886 not visibility should be done because of current context. This is probably
19887 the place where a package like yasnippets can hook in.")
19889 (defvar org-tab-before-tab-emulation-hook nil
19890 "Hook for functions to attach themselves to TAB.
19891 See `org-ctrl-c-ctrl-c-hook' for more information.
19892 This hook runs after every other options for TAB have been exhausted, but
19893 before indentation and \t insertion takes place.")
19895 (defvar org-metaleft-hook nil
19896 "Hook for functions attaching themselves to `M-left'.
19897 See `org-ctrl-c-ctrl-c-hook' for more information.")
19898 (defvar org-metaright-hook nil
19899 "Hook for functions attaching themselves to `M-right'.
19900 See `org-ctrl-c-ctrl-c-hook' for more information.")
19901 (defvar org-metaup-hook nil
19902 "Hook for functions attaching themselves to `M-up'.
19903 See `org-ctrl-c-ctrl-c-hook' for more information.")
19904 (defvar org-metadown-hook nil
19905 "Hook for functions attaching themselves to `M-down'.
19906 See `org-ctrl-c-ctrl-c-hook' for more information.")
19907 (defvar org-shiftmetaleft-hook nil
19908 "Hook for functions attaching themselves to `M-S-left'.
19909 See `org-ctrl-c-ctrl-c-hook' for more information.")
19910 (defvar org-shiftmetaright-hook nil
19911 "Hook for functions attaching themselves to `M-S-right'.
19912 See `org-ctrl-c-ctrl-c-hook' for more information.")
19913 (defvar org-shiftmetaup-hook nil
19914 "Hook for functions attaching themselves to `M-S-up'.
19915 See `org-ctrl-c-ctrl-c-hook' for more information.")
19916 (defvar org-shiftmetadown-hook nil
19917 "Hook for functions attaching themselves to `M-S-down'.
19918 See `org-ctrl-c-ctrl-c-hook' for more information.")
19919 (defvar org-metareturn-hook nil
19920 "Hook for functions attaching themselves to `M-RET'.
19921 See `org-ctrl-c-ctrl-c-hook' for more information.")
19922 (defvar org-shiftup-hook nil
19923 "Hook for functions attaching themselves to `S-up'.
19924 See `org-ctrl-c-ctrl-c-hook' for more information.")
19925 (defvar org-shiftup-final-hook nil
19926 "Hook for functions attaching themselves to `S-up'.
19927 This one runs after all other options except shift-select have been excluded.
19928 See `org-ctrl-c-ctrl-c-hook' for more information.")
19929 (defvar org-shiftdown-hook nil
19930 "Hook for functions attaching themselves to `S-down'.
19931 See `org-ctrl-c-ctrl-c-hook' for more information.")
19932 (defvar org-shiftdown-final-hook nil
19933 "Hook for functions attaching themselves to `S-down'.
19934 This one runs after all other options except shift-select have been excluded.
19935 See `org-ctrl-c-ctrl-c-hook' for more information.")
19936 (defvar org-shiftleft-hook nil
19937 "Hook for functions attaching themselves to `S-left'.
19938 See `org-ctrl-c-ctrl-c-hook' for more information.")
19939 (defvar org-shiftleft-final-hook nil
19940 "Hook for functions attaching themselves to `S-left'.
19941 This one runs after all other options except shift-select have been excluded.
19942 See `org-ctrl-c-ctrl-c-hook' for more information.")
19943 (defvar org-shiftright-hook nil
19944 "Hook for functions attaching themselves to `S-right'.
19945 See `org-ctrl-c-ctrl-c-hook' for more information.")
19946 (defvar org-shiftright-final-hook nil
19947 "Hook for functions attaching themselves to `S-right'.
19948 This one runs after all other options except shift-select have been excluded.
19949 See `org-ctrl-c-ctrl-c-hook' for more information.")
19951 (defun org-modifier-cursor-error ()
19952 "Throw an error, a modified cursor command was applied in wrong context."
19953 (user-error "This command is active in special context like tables, headlines or items"))
19955 (defun org-shiftselect-error ()
19956 "Throw an error because Shift-Cursor command was applied in wrong context."
19957 (if (and (boundp 'shift-select-mode) shift-select-mode)
19958 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19959 (user-error "This command works only in special context like headlines or timestamps")))
19961 (defun org-call-for-shift-select (cmd)
19962 (let ((this-command-keys-shift-translated t))
19963 (call-interactively cmd)))
19965 (defun org-shifttab (&optional arg)
19966 "Global visibility cycling or move to previous table field.
19967 Call `org-table-previous-field' within a table.
19968 When ARG is nil, cycle globally through visibility states.
19969 When ARG is a numeric prefix, show contents of this level."
19970 (interactive "P")
19971 (cond
19972 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19973 ((integerp arg)
19974 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19975 (message "Content view to level: %d" arg)
19976 (org-content (prefix-numeric-value arg2))
19977 (org-cycle-show-empty-lines t)
19978 (setq org-cycle-global-status 'overview)))
19979 (t (call-interactively 'org-global-cycle))))
19981 (defun org-shiftmetaleft ()
19982 "Promote subtree or delete table column.
19983 Calls `org-promote-subtree', `org-outdent-item-tree', or
19984 `org-table-delete-column', depending on context. See the
19985 individual commands for more information."
19986 (interactive)
19987 (cond
19988 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19989 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19990 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19991 ((if (not (org-region-active-p)) (org-at-item-p)
19992 (save-excursion (goto-char (region-beginning))
19993 (org-at-item-p)))
19994 (call-interactively 'org-outdent-item-tree))
19995 (t (org-modifier-cursor-error))))
19997 (defun org-shiftmetaright ()
19998 "Demote subtree or insert table column.
19999 Calls `org-demote-subtree', `org-indent-item-tree', or
20000 `org-table-insert-column', depending on context. See the
20001 individual commands for more information."
20002 (interactive)
20003 (cond
20004 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20005 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20006 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20007 ((if (not (org-region-active-p)) (org-at-item-p)
20008 (save-excursion (goto-char (region-beginning))
20009 (org-at-item-p)))
20010 (call-interactively 'org-indent-item-tree))
20011 (t (org-modifier-cursor-error))))
20013 (defun org-shiftmetaup (&optional arg)
20014 "Move subtree up or kill table row.
20015 Calls `org-move-subtree-up' or `org-table-kill-row' or
20016 `org-move-item-up' or `org-timestamp-up', depending on context.
20017 See the individual commands for more information."
20018 (interactive "P")
20019 (cond
20020 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20021 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20022 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20023 ((org-at-item-p) (call-interactively 'org-move-item-up))
20024 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20025 (call-interactively 'org-timestamp-up)))
20026 (t (call-interactively 'org-drag-line-backward))))
20028 (defun org-shiftmetadown (&optional arg)
20029 "Move subtree down or insert table row.
20030 Calls `org-move-subtree-down' or `org-table-insert-row' or
20031 `org-move-item-down' or `org-timestamp-up', depending on context.
20032 See the individual commands for more information."
20033 (interactive "P")
20034 (cond
20035 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20036 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20037 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20038 ((org-at-item-p) (call-interactively 'org-move-item-down))
20039 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20040 (call-interactively 'org-timestamp-down)))
20041 (t (call-interactively 'org-drag-line-forward))))
20043 (defsubst org-hidden-tree-error ()
20044 (user-error
20045 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20047 (defun org-metaleft (&optional arg)
20048 "Promote heading or move table column to left.
20049 Calls `org-do-promote' or `org-table-move-column', depending on context.
20050 With no specific context, calls the Emacs default `backward-word'.
20051 See the individual commands for more information."
20052 (interactive "P")
20053 (cond
20054 ((run-hook-with-args-until-success 'org-metaleft-hook))
20055 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20056 ((org-with-limited-levels
20057 (or (org-at-heading-p)
20058 (and (org-region-active-p)
20059 (save-excursion
20060 (goto-char (region-beginning))
20061 (org-at-heading-p)))))
20062 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20063 (call-interactively 'org-do-promote))
20064 ;; At an inline task.
20065 ((org-at-heading-p)
20066 (call-interactively 'org-inlinetask-promote))
20067 ((or (org-at-item-p)
20068 (and (org-region-active-p)
20069 (save-excursion
20070 (goto-char (region-beginning))
20071 (org-at-item-p))))
20072 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20073 (call-interactively 'org-outdent-item))
20074 (t (call-interactively 'backward-word))))
20076 (defun org-metaright (&optional arg)
20077 "Demote a subtree, a list item or move table column to right.
20078 In front of a drawer or a block keyword, indent it correctly.
20079 With no specific context, calls the Emacs default `forward-word'.
20080 See the individual commands for more information."
20081 (interactive "P")
20082 (cond
20083 ((run-hook-with-args-until-success 'org-metaright-hook))
20084 ((org-at-table-p) (call-interactively 'org-table-move-column))
20085 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20086 ((org-at-block-p) (call-interactively 'org-indent-block))
20087 ((org-with-limited-levels
20088 (or (org-at-heading-p)
20089 (and (org-region-active-p)
20090 (save-excursion
20091 (goto-char (region-beginning))
20092 (org-at-heading-p)))))
20093 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20094 (call-interactively 'org-do-demote))
20095 ;; At an inline task.
20096 ((org-at-heading-p)
20097 (call-interactively 'org-inlinetask-demote))
20098 ((or (org-at-item-p)
20099 (and (org-region-active-p)
20100 (save-excursion
20101 (goto-char (region-beginning))
20102 (org-at-item-p))))
20103 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20104 (call-interactively 'org-indent-item))
20105 (t (call-interactively 'forward-word))))
20107 (defun org-check-for-hidden (what)
20108 "Check if there are hidden headlines/items in the current visual line.
20109 WHAT can be either `headlines' or `items'. If the current line is
20110 an outline or item heading and it has a folded subtree below it,
20111 this function returns t, nil otherwise."
20112 (let ((re (cond
20113 ((eq what 'headlines) org-outline-regexp-bol)
20114 ((eq what 'items) (org-item-beginning-re))
20115 (t (error "This should not happen"))))
20116 beg end)
20117 (save-excursion
20118 (catch 'exit
20119 (unless (org-region-active-p)
20120 (setq beg (point-at-bol))
20121 (beginning-of-line 2)
20122 (while (and (not (eobp)) ;; this is like `next-line'
20123 (get-char-property (1- (point)) 'invisible))
20124 (beginning-of-line 2))
20125 (setq end (point))
20126 (goto-char beg)
20127 (goto-char (point-at-eol))
20128 (setq end (max end (point)))
20129 (while (re-search-forward re end t)
20130 (if (get-char-property (match-beginning 0) 'invisible)
20131 (throw 'exit t))))
20132 nil))))
20134 (defun org-metaup (&optional arg)
20135 "Move subtree up or move table row up.
20136 Calls `org-move-subtree-up' or `org-table-move-row' or
20137 `org-move-item-up', depending on context. See the individual commands
20138 for more information."
20139 (interactive "P")
20140 (cond
20141 ((run-hook-with-args-until-success 'org-metaup-hook))
20142 ((org-region-active-p)
20143 (let* ((a (min (region-beginning) (region-end)))
20144 (b (1- (max (region-beginning) (region-end))))
20145 (c (save-excursion (goto-char a)
20146 (move-beginning-of-line 0)))
20147 (d (save-excursion (goto-char a)
20148 (move-end-of-line 0) (point))))
20149 (transpose-regions a b c d)
20150 (goto-char c)))
20151 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20152 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20153 ((org-at-item-p) (call-interactively 'org-move-item-up))
20154 (t (org-drag-element-backward))))
20156 (defun org-metadown (&optional arg)
20157 "Move subtree down or move table row down.
20158 Calls `org-move-subtree-down' or `org-table-move-row' or
20159 `org-move-item-down', depending on context. See the individual
20160 commands for more information."
20161 (interactive "P")
20162 (cond
20163 ((run-hook-with-args-until-success 'org-metadown-hook))
20164 ((org-region-active-p)
20165 (let* ((a (min (region-beginning) (region-end)))
20166 (b (max (region-beginning) (region-end)))
20167 (c (save-excursion (goto-char b)
20168 (move-beginning-of-line 1)))
20169 (d (save-excursion (goto-char b)
20170 (move-end-of-line 1) (1+ (point)))))
20171 (transpose-regions a b c d)
20172 (goto-char d)))
20173 ((org-at-table-p) (call-interactively 'org-table-move-row))
20174 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20175 ((org-at-item-p) (call-interactively 'org-move-item-down))
20176 (t (org-drag-element-forward))))
20178 (defun org-shiftup (&optional arg)
20179 "Increase item in timestamp or increase priority of current headline.
20180 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20181 depending on context. See the individual commands for more information."
20182 (interactive "P")
20183 (cond
20184 ((run-hook-with-args-until-success 'org-shiftup-hook))
20185 ((and org-support-shift-select (org-region-active-p))
20186 (org-call-for-shift-select 'previous-line))
20187 ((org-at-timestamp-p t)
20188 (call-interactively (if org-edit-timestamp-down-means-later
20189 'org-timestamp-down 'org-timestamp-up)))
20190 ((and (not (eq org-support-shift-select 'always))
20191 org-enable-priority-commands
20192 (org-at-heading-p))
20193 (call-interactively 'org-priority-up))
20194 ((and (not org-support-shift-select) (org-at-item-p))
20195 (call-interactively 'org-previous-item))
20196 ((org-clocktable-try-shift 'up arg))
20197 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20198 (org-support-shift-select
20199 (org-call-for-shift-select 'previous-line))
20200 (t (org-shiftselect-error))))
20202 (defun org-shiftdown (&optional arg)
20203 "Decrease item in timestamp or decrease priority of current headline.
20204 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20205 depending on context. See the individual commands for more information."
20206 (interactive "P")
20207 (cond
20208 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20209 ((and org-support-shift-select (org-region-active-p))
20210 (org-call-for-shift-select 'next-line))
20211 ((org-at-timestamp-p t)
20212 (call-interactively (if org-edit-timestamp-down-means-later
20213 'org-timestamp-up 'org-timestamp-down)))
20214 ((and (not (eq org-support-shift-select 'always))
20215 org-enable-priority-commands
20216 (org-at-heading-p))
20217 (call-interactively 'org-priority-down))
20218 ((and (not org-support-shift-select) (org-at-item-p))
20219 (call-interactively 'org-next-item))
20220 ((org-clocktable-try-shift 'down arg))
20221 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20222 (org-support-shift-select
20223 (org-call-for-shift-select 'next-line))
20224 (t (org-shiftselect-error))))
20226 (defun org-shiftright (&optional arg)
20227 "Cycle the thing at point or in the current line, depending on context.
20228 Depending on context, this does one of the following:
20230 - switch a timestamp at point one day into the future
20231 - on a headline, switch to the next TODO keyword.
20232 - on an item, switch entire list to the next bullet type
20233 - on a property line, switch to the next allowed value
20234 - on a clocktable definition line, move time block into the future"
20235 (interactive "P")
20236 (cond
20237 ((run-hook-with-args-until-success 'org-shiftright-hook))
20238 ((and org-support-shift-select (org-region-active-p))
20239 (org-call-for-shift-select 'forward-char))
20240 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20241 ((and (not (eq org-support-shift-select 'always))
20242 (org-at-heading-p))
20243 (let ((org-inhibit-logging
20244 (not org-treat-S-cursor-todo-selection-as-state-change))
20245 (org-inhibit-blocking
20246 (not org-treat-S-cursor-todo-selection-as-state-change)))
20247 (org-call-with-arg 'org-todo 'right)))
20248 ((or (and org-support-shift-select
20249 (not (eq org-support-shift-select 'always))
20250 (org-at-item-bullet-p))
20251 (and (not org-support-shift-select) (org-at-item-p)))
20252 (org-call-with-arg 'org-cycle-list-bullet nil))
20253 ((and (not (eq org-support-shift-select 'always))
20254 (org-at-property-p))
20255 (call-interactively 'org-property-next-allowed-value))
20256 ((org-clocktable-try-shift 'right arg))
20257 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20258 (org-support-shift-select
20259 (org-call-for-shift-select 'forward-char))
20260 (t (org-shiftselect-error))))
20262 (defun org-shiftleft (&optional arg)
20263 "Cycle the thing at point or in the current line, depending on context.
20264 Depending on context, this does one of the following:
20266 - switch a timestamp at point one day into the past
20267 - on a headline, switch to the previous TODO keyword.
20268 - on an item, switch entire list to the previous bullet type
20269 - on a property line, switch to the previous allowed value
20270 - on a clocktable definition line, move time block into the past"
20271 (interactive "P")
20272 (cond
20273 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20274 ((and org-support-shift-select (org-region-active-p))
20275 (org-call-for-shift-select 'backward-char))
20276 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20277 ((and (not (eq org-support-shift-select 'always))
20278 (org-at-heading-p))
20279 (let ((org-inhibit-logging
20280 (not org-treat-S-cursor-todo-selection-as-state-change))
20281 (org-inhibit-blocking
20282 (not org-treat-S-cursor-todo-selection-as-state-change)))
20283 (org-call-with-arg 'org-todo 'left)))
20284 ((or (and org-support-shift-select
20285 (not (eq org-support-shift-select 'always))
20286 (org-at-item-bullet-p))
20287 (and (not org-support-shift-select) (org-at-item-p)))
20288 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20289 ((and (not (eq org-support-shift-select 'always))
20290 (org-at-property-p))
20291 (call-interactively 'org-property-previous-allowed-value))
20292 ((org-clocktable-try-shift 'left arg))
20293 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20294 (org-support-shift-select
20295 (org-call-for-shift-select 'backward-char))
20296 (t (org-shiftselect-error))))
20298 (defun org-shiftcontrolright ()
20299 "Switch to next TODO set."
20300 (interactive)
20301 (cond
20302 ((and org-support-shift-select (org-region-active-p))
20303 (org-call-for-shift-select 'forward-word))
20304 ((and (not (eq org-support-shift-select 'always))
20305 (org-at-heading-p))
20306 (org-call-with-arg 'org-todo 'nextset))
20307 (org-support-shift-select
20308 (org-call-for-shift-select 'forward-word))
20309 (t (org-shiftselect-error))))
20311 (defun org-shiftcontrolleft ()
20312 "Switch to previous TODO set."
20313 (interactive)
20314 (cond
20315 ((and org-support-shift-select (org-region-active-p))
20316 (org-call-for-shift-select 'backward-word))
20317 ((and (not (eq org-support-shift-select 'always))
20318 (org-at-heading-p))
20319 (org-call-with-arg 'org-todo 'previousset))
20320 (org-support-shift-select
20321 (org-call-for-shift-select 'backward-word))
20322 (t (org-shiftselect-error))))
20324 (defun org-shiftcontrolup (&optional n)
20325 "Change timestamps synchronously up in CLOCK log lines.
20326 Optional argument N tells to change by that many units."
20327 (interactive "P")
20328 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20329 (let (org-support-shift-select)
20330 (org-clock-timestamps-up n))
20331 (user-error "Not at a clock log")))
20333 (defun org-shiftcontroldown (&optional n)
20334 "Change timestamps synchronously down in CLOCK log lines.
20335 Optional argument N tells to change by that many units."
20336 (interactive "P")
20337 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20338 (let (org-support-shift-select)
20339 (org-clock-timestamps-down n))
20340 (user-error "Not at a clock log")))
20342 (defun org-increase-number-at-point (&optional inc)
20343 "Increment the number at point.
20344 With an optional prefix numeric argument INC, increment using
20345 this numeric value."
20346 (interactive "p")
20347 (if (not (number-at-point))
20348 (user-error "Not on a number")
20349 (unless inc (setq inc 1))
20350 (let ((pos (point))
20351 (beg (skip-chars-backward "-+^/*0-9eE."))
20352 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20353 (setq nap (buffer-substring-no-properties
20354 (+ pos beg) (+ pos beg end)))
20355 (delete-region (+ pos beg) (+ pos beg end))
20356 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20357 (when (org-at-table-p)
20358 (org-table-align)
20359 (org-table-end-of-field 1))))
20361 (defun org-decrease-number-at-point (&optional inc)
20362 "Decrement the number at point.
20363 With an optional prefix numeric argument INC, decrement using
20364 this numeric value."
20365 (interactive "p")
20366 (org-increase-number-at-point (- inc)))
20368 (defun org-ctrl-c-ret ()
20369 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20370 (interactive)
20371 (cond
20372 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20373 (t (call-interactively 'org-insert-heading))))
20375 (defun org-find-visible ()
20376 (let ((s (point)))
20377 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20378 (get-char-property s 'invisible)))
20380 (defun org-find-invisible ()
20381 (let ((s (point)))
20382 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20383 (not (get-char-property s 'invisible))))
20386 (defun org-copy-visible (beg end)
20387 "Copy the visible parts of the region."
20388 (interactive "r")
20389 (let (snippets s)
20390 (save-excursion
20391 (save-restriction
20392 (narrow-to-region beg end)
20393 (setq s (goto-char (point-min)))
20394 (while (not (= (point) (point-max)))
20395 (goto-char (org-find-invisible))
20396 (push (buffer-substring s (point)) snippets)
20397 (setq s (goto-char (org-find-visible))))))
20398 (kill-new (apply 'concat (nreverse snippets)))))
20400 (defun org-copy-special ()
20401 "Copy region in table or copy current subtree.
20402 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20403 See the individual commands for more information."
20404 (interactive)
20405 (call-interactively
20406 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20408 (defun org-cut-special ()
20409 "Cut region in table or cut current subtree.
20410 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20411 See the individual commands for more information."
20412 (interactive)
20413 (call-interactively
20414 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20416 (defun org-paste-special (arg)
20417 "Paste rectangular region into table, or past subtree relative to level.
20418 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20419 See the individual commands for more information."
20420 (interactive "P")
20421 (if (org-at-table-p)
20422 (org-table-paste-rectangle)
20423 (org-paste-subtree arg)))
20425 (defsubst org-in-fixed-width-region-p ()
20426 "Is point in a fixed-width region?"
20427 (save-match-data
20428 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20430 (defun org-edit-special (&optional arg)
20431 "Call a special editor for the element at point.
20432 When at a table, call the formula editor with `org-table-edit-formulas'.
20433 When in a source code block, call `org-edit-src-code'.
20434 When in a fixed-width region, call `org-edit-fixed-width-region'.
20435 When at an #+INCLUDE keyword, visit the included file.
20436 On a link, call `ffap' to visit the link at point.
20437 Otherwise, return a user error."
20438 (interactive "P")
20439 (let ((element (org-element-at-point)))
20440 (assert (not buffer-read-only) nil
20441 "Buffer is read-only: %s" (buffer-name))
20442 (case (org-element-type element)
20443 (src-block
20444 (if (not arg) (org-edit-src-code)
20445 (let* ((info (org-babel-get-src-block-info))
20446 (lang (nth 0 info))
20447 (params (nth 2 info))
20448 (session (cdr (assq :session params))))
20449 (if (not session) (org-edit-src-code)
20450 ;; At a src-block with a session and function called with
20451 ;; an ARG: switch to the buffer related to the inferior
20452 ;; process.
20453 (switch-to-buffer
20454 (funcall (intern (concat "org-babel-prep-session:" lang))
20455 session params))))))
20456 (keyword
20457 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20458 (find-file-other-window
20459 (org-remove-double-quotes
20460 (car (org-split-string (org-element-property :value element)))))
20461 (user-error "No special environment to edit here")))
20462 (table
20463 (if (eq (org-element-property :type element) 'table.el)
20464 (org-edit-src-code)
20465 (call-interactively 'org-table-edit-formulas)))
20466 ;; Only Org tables contain `table-row' type elements.
20467 (table-row (call-interactively 'org-table-edit-formulas))
20468 ((example-block export-block) (org-edit-src-code))
20469 (fixed-width (org-edit-fixed-width-region))
20470 (otherwise
20471 ;; No notable element at point. Though, we may be at a link,
20472 ;; which is an object. Thus, scan deeper.
20473 (if (eq (org-element-type (org-element-context element)) 'link)
20474 (call-interactively 'ffap)
20475 (user-error "No special environment to edit here"))))))
20477 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20478 (defun org-ctrl-c-ctrl-c (&optional arg)
20479 "Set tags in headline, or update according to changed information at point.
20481 This command does many different things, depending on context:
20483 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20484 this is what we do.
20486 - If the cursor is on a statistics cookie, update it.
20488 - If the cursor is in a headline, prompt for tags and insert them
20489 into the current line, aligned to `org-tags-column'. When called
20490 with prefix arg, realign all tags in the current buffer.
20492 - If the cursor is in one of the special #+KEYWORD lines, this
20493 triggers scanning the buffer for these lines and updating the
20494 information.
20496 - If the cursor is inside a table, realign the table. This command
20497 works even if the automatic table editor has been turned off.
20499 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20500 the entire table.
20502 - If the cursor is at a footnote reference or definition, jump to
20503 the corresponding definition or references, respectively.
20505 - If the cursor is a the beginning of a dynamic block, update it.
20507 - If the current buffer is a capture buffer, close note and file it.
20509 - If the cursor is on a <<<target>>>, update radio targets and
20510 corresponding links in this buffer.
20512 - If the cursor is on a numbered item in a plain list, renumber the
20513 ordered list.
20515 - If the cursor is on a checkbox, toggle it.
20517 - If the cursor is on a code block, evaluate it. The variable
20518 `org-confirm-babel-evaluate' can be used to control prompting
20519 before code block evaluation, by default every code block
20520 evaluation requires confirmation. Code block evaluation can be
20521 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20522 (interactive "P")
20523 (cond
20524 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20525 org-occur-highlights
20526 org-latex-fragment-image-overlays)
20527 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20528 (org-remove-occur-highlights)
20529 (org-remove-latex-fragment-image-overlays)
20530 (message "Temporary highlights/overlays removed from current buffer"))
20531 ((and (local-variable-p 'org-finish-function (current-buffer))
20532 (fboundp org-finish-function))
20533 (funcall org-finish-function))
20534 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20536 (let* ((context (org-element-context)) (type (org-element-type context)))
20537 ;; Test if point is within a blank line.
20538 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20539 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20540 (user-error "C-c C-c can do nothing useful at this location"))
20541 (case type
20542 ;; When at a link, act according to the parent instead.
20543 (link (setq context (org-element-property :parent context))
20544 (setq type (org-element-type context)))
20545 ;; Unsupported object types: refer to the first supported
20546 ;; element or object containing it.
20547 ((bold code entity export-snippet inline-babel-call inline-src-block
20548 italic latex-fragment line-break macro strike-through subscript
20549 superscript underline verbatim)
20550 (while (and (setq context (org-element-property :parent context))
20551 (not (memq (setq type (org-element-type context))
20552 '(radio-target paragraph verse-block
20553 table-cell)))))))
20554 ;; For convenience: at the first line of a paragraph on the
20555 ;; same line as an item, apply function on that item instead.
20556 (when (eq type 'paragraph)
20557 (let ((parent (org-element-property :parent context)))
20558 (when (and (eq (org-element-type parent) 'item)
20559 (= (point-at-bol) (org-element-property :begin parent)))
20560 (setq context parent type 'item))))
20561 ;; Act according to type of element or object at point.
20562 (case type
20563 (clock (org-clock-update-time-maybe))
20564 (dynamic-block
20565 (save-excursion
20566 (goto-char (org-element-property :post-affiliated context))
20567 (org-update-dblock)))
20568 (footnote-definition
20569 (goto-char (org-element-property :post-affiliated context))
20570 (call-interactively 'org-footnote-action))
20571 (footnote-reference (call-interactively 'org-footnote-action))
20572 ((headline inlinetask)
20573 (save-excursion (goto-char (org-element-property :begin context))
20574 (call-interactively 'org-set-tags)))
20575 (item
20576 ;; At an item: a double C-u set checkbox to "[-]"
20577 ;; unconditionally, whereas a single one will toggle its
20578 ;; presence. Without an universal argument, if the item
20579 ;; has a checkbox, toggle it. Otherwise repair the list.
20580 (let* ((box (org-element-property :checkbox context))
20581 (struct (org-element-property :structure context))
20582 (old-struct (copy-tree struct))
20583 (parents (org-list-parents-alist struct))
20584 (prevs (org-list-prevs-alist struct))
20585 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20586 (org-list-set-checkbox
20587 (org-element-property :begin context) struct
20588 (cond ((equal arg '(16)) "[-]")
20589 ((and (not box) (equal arg '(4))) "[ ]")
20590 ((or (not box) (equal arg '(4))) nil)
20591 ((eq box 'on) "[ ]")
20592 (t "[X]")))
20593 ;; Mimic `org-list-write-struct' but with grabbing
20594 ;; a return value from `org-list-struct-fix-box'.
20595 (org-list-struct-fix-ind struct parents 2)
20596 (org-list-struct-fix-item-end struct)
20597 (org-list-struct-fix-bul struct prevs)
20598 (org-list-struct-fix-ind struct parents)
20599 (let ((block-item
20600 (org-list-struct-fix-box struct parents prevs orderedp)))
20601 (if (and box (equal struct old-struct))
20602 (if (equal arg '(16))
20603 (message "Checkboxes already reset")
20604 (user-error "Cannot toggle this checkbox: %s"
20605 (if (eq box 'on)
20606 "all subitems checked"
20607 "unchecked subitems")))
20608 (org-list-struct-apply-struct struct old-struct)
20609 (org-update-checkbox-count-maybe))
20610 (when block-item
20611 (message "Checkboxes were removed due to empty box at line %d"
20612 (org-current-line block-item))))))
20613 (keyword
20614 (let ((org-inhibit-startup-visibility-stuff t)
20615 (org-startup-align-all-tables nil))
20616 (when (boundp 'org-table-coordinate-overlays)
20617 (mapc 'delete-overlay org-table-coordinate-overlays)
20618 (setq org-table-coordinate-overlays nil))
20619 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20620 (message "Local setup has been refreshed"))
20621 (plain-list
20622 ;; At a plain list, with a double C-u argument, set
20623 ;; checkboxes of each item to "[-]", whereas a single one
20624 ;; will toggle their presence according to the state of the
20625 ;; first item in the list. Without an argument, repair the
20626 ;; list.
20627 (let* ((begin (org-element-property :contents-begin context))
20628 (beginm (move-marker (make-marker) begin))
20629 (struct (org-element-property :structure context))
20630 (old-struct (copy-tree struct))
20631 (first-box (save-excursion
20632 (goto-char begin)
20633 (looking-at org-list-full-item-re)
20634 (match-string-no-properties 3)))
20635 (new-box (cond ((equal arg '(16)) "[-]")
20636 ((equal arg '(4)) (unless first-box "[ ]"))
20637 ((equal first-box "[X]") "[ ]")
20638 (t "[X]"))))
20639 (cond
20640 (arg
20641 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20642 (org-list-get-all-items
20643 begin struct (org-list-prevs-alist struct))))
20644 ((and first-box (eq (point) begin))
20645 ;; For convenience, when point is at bol on the first
20646 ;; item of the list and no argument is provided, simply
20647 ;; toggle checkbox of that item, if any.
20648 (org-list-set-checkbox begin struct new-box)))
20649 (org-list-write-struct
20650 struct (org-list-parents-alist struct) old-struct)
20651 (org-update-checkbox-count-maybe)
20652 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20653 ((property-drawer node-property)
20654 (call-interactively 'org-property-action))
20655 ((radio-target target)
20656 (call-interactively 'org-update-radio-target-regexp))
20657 (statistics-cookie
20658 (call-interactively 'org-update-statistics-cookies))
20659 ((table table-cell table-row)
20660 ;; At a table, recalculate every field and align it. Also
20661 ;; send the table if necessary. If the table has
20662 ;; a `table.el' type, just give up. At a table row or
20663 ;; cell, maybe recalculate line but always align table.
20664 (if (eq (org-element-property :type context) 'table.el)
20665 (message "Use C-c ' to edit table.el tables")
20666 (let ((org-enable-table-editor t))
20667 (if (or (eq type 'table)
20668 ;; Check if point is at a TBLFM line.
20669 (and (eq type 'table-row)
20670 (= (point) (org-element-property :end context))))
20671 (save-excursion
20672 (if (org-at-TBLFM-p)
20673 (progn (require 'org-table)
20674 (org-table-calc-current-TBLFM))
20675 (goto-char (org-element-property :contents-begin context))
20676 (org-call-with-arg 'org-table-recalculate (or arg t))
20677 (orgtbl-send-table 'maybe)))
20678 (org-table-maybe-eval-formula)
20679 (cond (arg (call-interactively 'org-table-recalculate))
20680 ((org-table-maybe-recalculate-line))
20681 (t (org-table-align)))))))
20682 (timestamp (org-timestamp-change 0 'day))
20683 (otherwise
20684 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20685 (user-error
20686 "C-c C-c can do nothing useful at this location")))))))))
20688 (defun org-mode-restart ()
20689 (interactive)
20690 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20691 (funcall major-mode)
20692 (hack-local-variables)
20693 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20694 (org-indent-mode -1)))
20695 (message "%s restarted" major-mode))
20697 (defun org-kill-note-or-show-branches ()
20698 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20699 (interactive)
20700 (if (not org-finish-function)
20701 (progn
20702 (hide-subtree)
20703 (call-interactively 'show-branches))
20704 (let ((org-note-abort t))
20705 (funcall org-finish-function))))
20707 (defun org-open-line (n)
20708 "Insert a new row in tables, call `open-line' elsewhere.
20709 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20710 (interactive "*p")
20711 (cond
20712 ((not org-special-ctrl-o)
20713 (open-line n))
20714 ((org-at-table-p)
20715 (org-table-insert-row))
20717 (open-line n))))
20719 (defun org-return (&optional indent)
20720 "Goto next table row or insert a newline.
20721 Calls `org-table-next-row' or `newline', depending on context.
20722 See the individual commands for more information."
20723 (interactive)
20724 (let (org-ts-what)
20725 (cond
20726 ((or (bobp) (org-in-src-block-p))
20727 (if indent (newline-and-indent) (newline)))
20728 ((org-at-table-p)
20729 (org-table-justify-field-maybe)
20730 (call-interactively 'org-table-next-row))
20731 ;; when `newline-and-indent' is called within a list, make sure
20732 ;; text moved stays inside the item.
20733 ((and (org-in-item-p) indent)
20734 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20735 (progn
20736 (save-match-data (newline))
20737 (org-indent-line-to (length (match-string 0))))
20738 (let ((ind (org-get-indentation)))
20739 (newline)
20740 (if (org-looking-back org-list-end-re)
20741 (org-indent-line)
20742 (org-indent-line-to ind)))))
20743 ((and org-return-follows-link
20744 (org-at-timestamp-p t)
20745 (not (eq org-ts-what 'after)))
20746 (org-follow-timestamp-link))
20747 ((and org-return-follows-link
20748 (let ((tprop (get-text-property (point) 'face)))
20749 (or (eq tprop 'org-link)
20750 (and (listp tprop) (memq 'org-link tprop)))))
20751 (call-interactively 'org-open-at-point))
20752 ((and (org-at-heading-p)
20753 (looking-at
20754 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20755 (org-show-entry)
20756 (end-of-line 1)
20757 (newline))
20758 (t (if indent (newline-and-indent) (newline))))))
20760 (defun org-return-indent ()
20761 "Goto next table row or insert a newline and indent.
20762 Calls `org-table-next-row' or `newline-and-indent', depending on
20763 context. See the individual commands for more information."
20764 (interactive)
20765 (org-return t))
20767 (defun org-ctrl-c-star ()
20768 "Compute table, or change heading status of lines.
20769 Calls `org-table-recalculate' or `org-toggle-heading',
20770 depending on context."
20771 (interactive)
20772 (cond
20773 ((org-at-table-p)
20774 (call-interactively 'org-table-recalculate))
20776 ;; Convert all lines in region to list items
20777 (call-interactively 'org-toggle-heading))))
20779 (defun org-ctrl-c-minus ()
20780 "Insert separator line in table or modify bullet status of line.
20781 Also turns a plain line or a region of lines into list items.
20782 Calls `org-table-insert-hline', `org-toggle-item', or
20783 `org-cycle-list-bullet', depending on context."
20784 (interactive)
20785 (cond
20786 ((org-at-table-p)
20787 (call-interactively 'org-table-insert-hline))
20788 ((org-region-active-p)
20789 (call-interactively 'org-toggle-item))
20790 ((org-in-item-p)
20791 (call-interactively 'org-cycle-list-bullet))
20793 (call-interactively 'org-toggle-item))))
20795 (defun org-toggle-item (arg)
20796 "Convert headings or normal lines to items, items to normal lines.
20797 If there is no active region, only the current line is considered.
20799 If the first non blank line in the region is a headline, convert
20800 all headlines to items, shifting text accordingly.
20802 If it is an item, convert all items to normal lines.
20804 If it is normal text, change region into a list of items.
20805 With a prefix argument ARG, change the region in a single item."
20806 (interactive "P")
20807 (let ((shift-text
20808 (function
20809 ;; Shift text in current section to IND, from point to END.
20810 ;; The function leaves point to END line.
20811 (lambda (ind end)
20812 (let ((min-i 1000) (end (copy-marker end)))
20813 ;; First determine the minimum indentation (MIN-I) of
20814 ;; the text.
20815 (save-excursion
20816 (catch 'exit
20817 (while (< (point) end)
20818 (let ((i (org-get-indentation)))
20819 (cond
20820 ;; Skip blank lines and inline tasks.
20821 ((looking-at "^[ \t]*$"))
20822 ((looking-at org-outline-regexp-bol))
20823 ;; We can't find less than 0 indentation.
20824 ((zerop i) (throw 'exit (setq min-i 0)))
20825 ((< i min-i) (setq min-i i))))
20826 (forward-line))))
20827 ;; Then indent each line so that a line indented to
20828 ;; MIN-I becomes indented to IND. Ignore blank lines
20829 ;; and inline tasks in the process.
20830 (let ((delta (- ind min-i)))
20831 (while (< (point) end)
20832 (unless (or (looking-at "^[ \t]*$")
20833 (looking-at org-outline-regexp-bol))
20834 (org-indent-line-to (+ (org-get-indentation) delta)))
20835 (forward-line)))))))
20836 (skip-blanks
20837 (function
20838 ;; Return beginning of first non-blank line, starting from
20839 ;; line at POS.
20840 (lambda (pos)
20841 (save-excursion
20842 (goto-char pos)
20843 (skip-chars-forward " \r\t\n")
20844 (point-at-bol)))))
20845 beg end)
20846 ;; Determine boundaries of changes.
20847 (if (org-region-active-p)
20848 (setq beg (funcall skip-blanks (region-beginning))
20849 end (copy-marker (region-end)))
20850 (setq beg (funcall skip-blanks (point-at-bol))
20851 end (copy-marker (point-at-eol))))
20852 ;; Depending on the starting line, choose an action on the text
20853 ;; between BEG and END.
20854 (org-with-limited-levels
20855 (save-excursion
20856 (goto-char beg)
20857 (cond
20858 ;; Case 1. Start at an item: de-itemize. Note that it only
20859 ;; happens when a region is active: `org-ctrl-c-minus'
20860 ;; would call `org-cycle-list-bullet' otherwise.
20861 ((org-at-item-p)
20862 (while (< (point) end)
20863 (when (org-at-item-p)
20864 (skip-chars-forward " \t")
20865 (delete-region (point) (match-end 0)))
20866 (forward-line)))
20867 ;; Case 2. Start at an heading: convert to items.
20868 ((org-at-heading-p)
20869 (let* ((bul (org-list-bullet-string "-"))
20870 (bul-len (length bul))
20871 (done (org-entry-is-done-p))
20872 (todo (org-entry-is-todo-p))
20873 ;; Indentation of the first heading. It should be
20874 ;; relative to the indentation of its parent, if any.
20875 (start-ind (save-excursion
20876 (cond
20877 ((not org-adapt-indentation) 0)
20878 ((not (outline-previous-heading)) 0)
20879 (t (length (match-string 0))))))
20880 ;; Level of first heading. Further headings will be
20881 ;; compared to it to determine hierarchy in the list.
20882 (ref-level (org-reduced-level (org-outline-level))))
20883 (when (or done todo) (org-todo ""))
20884 (while (< (point) end)
20885 (let* ((level (org-reduced-level (org-outline-level)))
20886 (delta (max 0 (- level ref-level))))
20887 ;; If current headline is less indented than the first
20888 ;; one, set it as reference, in order to preserve
20889 ;; subtrees.
20890 (when (< level ref-level) (setq ref-level level))
20891 (replace-match bul t t)
20892 (org-indent-line-to (+ start-ind (* delta bul-len)))
20893 (when (or done todo)
20894 (let* ((struct (org-list-struct))
20895 (old (copy-tree struct)))
20896 (org-list-set-checkbox (line-beginning-position)
20897 struct
20898 (if done "[X]" "[ ]"))
20899 (org-list-write-struct struct
20900 (org-list-parents-alist struct)
20901 old)))
20902 ;; Ensure all text down to END (or SECTION-END) belongs
20903 ;; to the newly created item.
20904 (let ((section-end (save-excursion
20905 (or (outline-next-heading) (point)))))
20906 (forward-line)
20907 (funcall shift-text
20908 (+ start-ind (* (1+ delta) bul-len))
20909 (min end section-end)))))))
20910 ;; Case 3. Normal line with ARG: make the first line of region
20911 ;; an item, and shift indentation of others lines to
20912 ;; set them as item's body.
20913 (arg (let* ((bul (org-list-bullet-string "-"))
20914 (bul-len (length bul))
20915 (ref-ind (org-get-indentation)))
20916 (skip-chars-forward " \t")
20917 (insert bul)
20918 (forward-line)
20919 (while (< (point) end)
20920 ;; Ensure that lines less indented than first one
20921 ;; still get included in item body.
20922 (funcall shift-text
20923 (+ ref-ind bul-len)
20924 (min end (save-excursion (or (outline-next-heading)
20925 (point)))))
20926 (forward-line))))
20927 ;; Case 4. Normal line without ARG: turn each non-item line
20928 ;; into an item.
20930 (while (< (point) end)
20931 (unless (or (org-at-heading-p) (org-at-item-p))
20932 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20933 (replace-match
20934 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20935 (forward-line))))))))
20937 (defun org-toggle-heading (&optional nstars)
20938 "Convert headings to normal text, or items or text to headings.
20939 If there is no active region, only convert the current line.
20941 With a \\[universal-argument] prefix, convert the whole list at
20942 point into heading.
20944 In a region:
20946 - If the first non blank line is a headline, remove the stars
20947 from all headlines in the region.
20949 - If it is a normal line, turn each and every normal line (i.e.,
20950 not an heading or an item) in the region into headings. If you
20951 want to convert only the first line of this region, use one
20952 universal prefix argument.
20954 - If it is a plain list item, turn all plain list items into headings.
20956 When converting a line into a heading, the number of stars is chosen
20957 such that the lines become children of the current entry. However,
20958 when a numeric prefix argument is given, its value determines the
20959 number of stars to add."
20960 (interactive "P")
20961 (let ((skip-blanks
20962 (function
20963 ;; Return beginning of first non-blank line, starting from
20964 ;; line at POS.
20965 (lambda (pos)
20966 (save-excursion
20967 (goto-char pos)
20968 (while (org-at-comment-p) (forward-line))
20969 (skip-chars-forward " \r\t\n")
20970 (point-at-bol)))))
20971 beg end toggled)
20972 ;; Determine boundaries of changes. If a universal prefix has
20973 ;; been given, put the list in a region. If region ends at a bol,
20974 ;; do not consider the last line to be in the region.
20976 (when (and current-prefix-arg (org-at-item-p))
20977 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20978 (org-mark-element))
20980 (if (org-region-active-p)
20981 (setq beg (funcall skip-blanks (region-beginning))
20982 end (copy-marker (save-excursion
20983 (goto-char (region-end))
20984 (if (bolp) (point) (point-at-eol)))))
20985 (setq beg (funcall skip-blanks (point-at-bol))
20986 end (copy-marker (point-at-eol))))
20987 ;; Ensure inline tasks don't count as headings.
20988 (org-with-limited-levels
20989 (save-excursion
20990 (goto-char beg)
20991 (cond
20992 ;; Case 1. Started at an heading: de-star headings.
20993 ((org-at-heading-p)
20994 (while (< (point) end)
20995 (when (org-at-heading-p t)
20996 (looking-at org-outline-regexp) (replace-match "")
20997 (setq toggled t))
20998 (forward-line)))
20999 ;; Case 2. Started at an item: change items into headlines.
21000 ;; One star will be added by `org-list-to-subtree'.
21001 ((org-at-item-p)
21002 (let* ((stars (make-string
21003 ;; subtract the star that will be added again by
21004 ;; `org-list-to-subtree'
21005 (if (numberp nstars) (1- nstars)
21006 (or (org-current-level) 0))
21007 ?*))
21008 (add-stars
21009 (cond (nstars "") ; stars from prefix only
21010 ((equal stars "") "") ; before first heading
21011 (org-odd-levels-only "*") ; inside heading, odd
21012 (t "")))) ; inside heading, oddeven
21013 (while (< (point) end)
21014 (when (org-at-item-p)
21015 ;; Pay attention to cases when region ends before list.
21016 (let* ((struct (org-list-struct))
21017 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21018 (save-restriction
21019 (narrow-to-region (point) list-end)
21020 (insert
21021 (org-list-to-subtree
21022 (org-list-parse-list t)
21023 '(:istart (concat stars add-stars (funcall get-stars depth))
21024 :icount (concat stars add-stars (funcall get-stars depth)))))))
21025 (setq toggled t))
21026 (forward-line))))
21027 ;; Case 3. Started at normal text: make every line an heading,
21028 ;; skipping headlines and items.
21029 (t (let* ((stars
21030 (make-string
21031 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21032 (add-stars
21033 (cond (nstars "") ; stars from prefix only
21034 ((equal stars "") "*") ; before first heading
21035 (org-odd-levels-only "**") ; inside heading, odd
21036 (t "*"))) ; inside heading, oddeven
21037 (rpl (concat stars add-stars " "))
21038 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21039 (while (< (point) (if (equal nstars '(4)) lend end))
21040 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21041 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21042 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21043 (forward-line)))))))
21044 (unless toggled (message "Cannot toggle heading from here"))))
21046 (defun org-meta-return (&optional arg)
21047 "Insert a new heading or wrap a region in a table.
21048 Calls `org-insert-heading' or `org-table-wrap-region', depending
21049 on context. See the individual commands for more information."
21050 (interactive "P")
21051 (org-check-before-invisible-edit 'insert)
21052 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21053 (let* ((element (org-element-at-point))
21054 (type (org-element-type element)))
21055 (when (eq type 'table-row)
21056 (setq element (org-element-property :parent element))
21057 (setq type 'table))
21058 (if (and (eq type 'table)
21059 (eq (org-element-property :type element) 'org)
21060 (>= (point) (org-element-property :contents-begin element))
21061 (< (point) (org-element-property :contents-end element)))
21062 (call-interactively 'org-table-wrap-region)
21063 (call-interactively 'org-insert-heading)))))
21065 ;;; Menu entries
21067 (defsubst org-in-subtree-not-table-p ()
21068 "Are we in a subtree and not in a table?"
21069 (and (not (org-before-first-heading-p))
21070 (not (org-at-table-p))))
21072 ;; Define the Org-mode menus
21073 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21074 '("Tbl"
21075 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21076 ["Next Field" org-cycle (org-at-table-p)]
21077 ["Previous Field" org-shifttab (org-at-table-p)]
21078 ["Next Row" org-return (org-at-table-p)]
21079 "--"
21080 ["Blank Field" org-table-blank-field (org-at-table-p)]
21081 ["Edit Field" org-table-edit-field (org-at-table-p)]
21082 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21083 "--"
21084 ("Column"
21085 ["Move Column Left" org-metaleft (org-at-table-p)]
21086 ["Move Column Right" org-metaright (org-at-table-p)]
21087 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21088 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21089 ("Row"
21090 ["Move Row Up" org-metaup (org-at-table-p)]
21091 ["Move Row Down" org-metadown (org-at-table-p)]
21092 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21093 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21094 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21095 "--"
21096 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21097 ("Rectangle"
21098 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21099 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21100 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21101 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21102 "--"
21103 ("Calculate"
21104 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21105 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21106 ["Edit Formulas" org-edit-special (org-at-table-p)]
21107 "--"
21108 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21109 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21110 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21111 "--"
21112 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21113 "--"
21114 ["Sum Column/Rectangle" org-table-sum
21115 (or (org-at-table-p) (org-region-active-p))]
21116 ["Which Column?" org-table-current-column (org-at-table-p)])
21117 ["Debug Formulas"
21118 org-table-toggle-formula-debugger
21119 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21120 ["Show Col/Row Numbers"
21121 org-table-toggle-coordinate-overlays
21122 :style toggle
21123 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21124 "--"
21125 ["Create" org-table-create (and (not (org-at-table-p))
21126 org-enable-table-editor)]
21127 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21128 ["Import from File" org-table-import (not (org-at-table-p))]
21129 ["Export to File" org-table-export (org-at-table-p)]
21130 "--"
21131 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
21133 (easy-menu-define org-org-menu org-mode-map "Org menu"
21134 '("Org"
21135 ("Show/Hide"
21136 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21137 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21138 ["Sparse Tree..." org-sparse-tree t]
21139 ["Reveal Context" org-reveal t]
21140 ["Show All" show-all t]
21141 "--"
21142 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21143 "--"
21144 ["New Heading" org-insert-heading t]
21145 ("Navigate Headings"
21146 ["Up" outline-up-heading t]
21147 ["Next" outline-next-visible-heading t]
21148 ["Previous" outline-previous-visible-heading t]
21149 ["Next Same Level" outline-forward-same-level t]
21150 ["Previous Same Level" outline-backward-same-level t]
21151 "--"
21152 ["Jump" org-goto t])
21153 ("Edit Structure"
21154 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21155 "--"
21156 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21157 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21158 "--"
21159 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21160 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21161 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21162 "--"
21163 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21164 "--"
21165 ["Copy visible text" org-copy-visible t]
21166 "--"
21167 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21168 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21169 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21170 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21171 "--"
21172 ["Sort Region/Children" org-sort t]
21173 "--"
21174 ["Convert to odd levels" org-convert-to-odd-levels t]
21175 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21176 ("Editing"
21177 ["Emphasis..." org-emphasize t]
21178 ["Edit Source Example" org-edit-special t]
21179 "--"
21180 ["Footnote new/jump" org-footnote-action t]
21181 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21182 ("Archive"
21183 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21184 "--"
21185 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21186 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21187 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21189 "--"
21190 ("Hyperlinks"
21191 ["Store Link (Global)" org-store-link t]
21192 ["Find existing link to here" org-occur-link-in-agenda-files t]
21193 ["Insert Link" org-insert-link t]
21194 ["Follow Link" org-open-at-point t]
21195 "--"
21196 ["Next link" org-next-link t]
21197 ["Previous link" org-previous-link t]
21198 "--"
21199 ["Descriptive Links"
21200 org-toggle-link-display
21201 :style radio
21202 :selected org-descriptive-links
21204 ["Literal Links"
21205 org-toggle-link-display
21206 :style radio
21207 :selected (not org-descriptive-links)])
21208 "--"
21209 ("TODO Lists"
21210 ["TODO/DONE/-" org-todo t]
21211 ("Select keyword"
21212 ["Next keyword" org-shiftright (org-at-heading-p)]
21213 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21214 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21215 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21216 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21217 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21218 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21219 "--"
21220 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21221 :selected org-enforce-todo-dependencies :style toggle :active t]
21222 "Settings for tree at point"
21223 ["Do Children sequentially" org-toggle-ordered-property :style radio
21224 :selected (org-entry-get nil "ORDERED")
21225 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21226 ["Do Children parallel" org-toggle-ordered-property :style radio
21227 :selected (not (org-entry-get nil "ORDERED"))
21228 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21229 "--"
21230 ["Set Priority" org-priority t]
21231 ["Priority Up" org-shiftup t]
21232 ["Priority Down" org-shiftdown t]
21233 "--"
21234 ["Get news from all feeds" org-feed-update-all t]
21235 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21236 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21237 ("TAGS and Properties"
21238 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21239 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21240 "--"
21241 ["Set property" org-set-property (not (org-before-first-heading-p))]
21242 ["Column view of properties" org-columns t]
21243 ["Insert Column View DBlock" org-insert-columns-dblock t])
21244 ("Dates and Scheduling"
21245 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21246 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21247 ("Change Date"
21248 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21249 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21250 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21251 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21252 ["Compute Time Range" org-evaluate-time-range t]
21253 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21254 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21255 "--"
21256 ["Custom time format" org-toggle-time-stamp-overlays
21257 :style radio :selected org-display-custom-times]
21258 "--"
21259 ["Goto Calendar" org-goto-calendar t]
21260 ["Date from Calendar" org-date-from-calendar t]
21261 "--"
21262 ["Start/Restart Timer" org-timer-start t]
21263 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21264 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21265 ["Insert Timer String" org-timer t]
21266 ["Insert Timer Item" org-timer-item t])
21267 ("Logging work"
21268 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21269 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21270 ["Clock out" org-clock-out t]
21271 ["Clock cancel" org-clock-cancel t]
21272 "--"
21273 ["Mark as default task" org-clock-mark-default-task t]
21274 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21275 ["Goto running clock" org-clock-goto t]
21276 "--"
21277 ["Display times" org-clock-display t]
21278 ["Create clock table" org-clock-report t]
21279 "--"
21280 ["Record DONE time"
21281 (progn (setq org-log-done (not org-log-done))
21282 (message "Switching to %s will %s record a timestamp"
21283 (car org-done-keywords)
21284 (if org-log-done "automatically" "not")))
21285 :style toggle :selected org-log-done])
21286 "--"
21287 ["Agenda Command..." org-agenda t]
21288 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21289 ("File List for Agenda")
21290 ("Special views current file"
21291 ["TODO Tree" org-show-todo-tree t]
21292 ["Check Deadlines" org-check-deadlines t]
21293 ["Timeline" org-timeline t]
21294 ["Tags/Property tree" org-match-sparse-tree t])
21295 "--"
21296 ["Export/Publish..." org-export-dispatch t]
21297 ("LaTeX"
21298 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21299 :selected org-cdlatex-mode]
21300 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21301 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21302 ["Modify math symbol" org-cdlatex-math-modify
21303 (org-inside-LaTeX-fragment-p)]
21304 ["Insert citation" org-reftex-citation t]
21305 "--"
21306 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21307 "--"
21308 ("MobileOrg"
21309 ["Push Files and Views" org-mobile-push t]
21310 ["Get Captured and Flagged" org-mobile-pull t]
21311 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21312 "--"
21313 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21314 "--"
21315 ("Documentation"
21316 ["Show Version" org-version t]
21317 ["Info Documentation" org-info t])
21318 ("Customize"
21319 ["Browse Org Group" org-customize t]
21320 "--"
21321 ["Expand This Menu" org-create-customize-menu
21322 (fboundp 'customize-menu-create)])
21323 ["Send bug report" org-submit-bug-report t]
21324 "--"
21325 ("Refresh/Reload"
21326 ["Refresh setup current buffer" org-mode-restart t]
21327 ["Reload Org (after update)" org-reload t]
21328 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21331 (defun org-info (&optional node)
21332 "Read documentation for Org-mode in the info system.
21333 With optional NODE, go directly to that node."
21334 (interactive)
21335 (info (format "(org)%s" (or node ""))))
21337 ;;;###autoload
21338 (defun org-submit-bug-report ()
21339 "Submit a bug report on Org-mode via mail.
21341 Don't hesitate to report any problems or inaccurate documentation.
21343 If you don't have setup sending mail from (X)Emacs, please copy the
21344 output buffer into your mail program, as it gives us important
21345 information about your Org-mode version and configuration."
21346 (interactive)
21347 (require 'reporter)
21348 (org-load-modules-maybe)
21349 (org-require-autoloaded-modules)
21350 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21351 (reporter-submit-bug-report
21352 "emacs-orgmode@gnu.org"
21353 (org-version nil 'full)
21354 (let (list)
21355 (save-window-excursion
21356 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21357 (delete-other-windows)
21358 (erase-buffer)
21359 (insert "You are about to submit a bug report to the Org-mode mailing list.
21361 We would like to add your full Org-mode and Outline configuration to the
21362 bug report. This greatly simplifies the work of the maintainer and
21363 other experts on the mailing list.
21365 HOWEVER, some variables you have customized may contain private
21366 information. The names of customers, colleagues, or friends, might
21367 appear in the form of file names, tags, todo states, or search strings.
21368 If you answer yes to the prompt, you might want to check and remove
21369 such private information before sending the email.")
21370 (add-text-properties (point-min) (point-max) '(face org-warning))
21371 (when (yes-or-no-p "Include your Org-mode configuration ")
21372 (mapatoms
21373 (lambda (v)
21374 (and (boundp v)
21375 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21376 (or (and (symbol-value v)
21377 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21378 (and
21379 (get v 'custom-type) (get v 'standard-value)
21380 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21381 (push v list)))))
21382 (kill-buffer (get-buffer "*Warn about privacy*"))
21383 list))
21384 nil nil
21385 "Remember to cover the basics, that is, what you expected to happen and
21386 what in fact did happen. You don't know how to make a good report? See
21388 http://orgmode.org/manual/Feedback.html#Feedback
21390 Your bug report will be posted to the Org-mode mailing list.
21391 ------------------------------------------------------------------------")
21392 (save-excursion
21393 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21394 (replace-match "\\1Bug: \\3 [\\2]")))))
21397 (defun org-install-agenda-files-menu ()
21398 (let ((bl (buffer-list)))
21399 (save-excursion
21400 (while bl
21401 (set-buffer (pop bl))
21402 (if (derived-mode-p 'org-mode) (setq bl nil)))
21403 (when (derived-mode-p 'org-mode)
21404 (easy-menu-change
21405 '("Org") "File List for Agenda"
21406 (append
21407 (list
21408 ["Edit File List" (org-edit-agenda-file-list) t]
21409 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21410 ["Remove Current File from List" org-remove-file t]
21411 ["Cycle through agenda files" org-cycle-agenda-files t]
21412 ["Occur in all agenda files" org-occur-in-agenda-files t]
21413 "--")
21414 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21416 ;;;; Documentation
21418 (defun org-require-autoloaded-modules ()
21419 (interactive)
21420 (mapc 'require
21421 '(org-agenda org-archive org-attach org-clock org-colview org-id
21422 org-table org-timer)))
21424 ;;;###autoload
21425 (defun org-reload (&optional uncompiled)
21426 "Reload all org lisp files.
21427 With prefix arg UNCOMPILED, load the uncompiled versions."
21428 (interactive "P")
21429 (require 'loadhist)
21430 (let* ((org-dir (org-find-library-dir "org"))
21431 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21432 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21433 (remove-re (mapconcat 'identity
21434 (mapcar (lambda (f) (concat "^" f "$"))
21435 (list (if (featurep 'xemacs)
21436 "org-colview"
21437 "org-colview-xemacs")
21438 "org" "org-loaddefs" "org-version"))
21439 "\\|"))
21440 (feats (delete-dups
21441 (mapcar 'file-name-sans-extension
21442 (mapcar 'file-name-nondirectory
21443 (delq nil
21444 (mapcar 'feature-file
21445 features))))))
21446 (lfeat (append
21447 (sort
21448 (setq feats
21449 (delq nil (mapcar
21450 (lambda (f)
21451 (if (and (string-match feature-re f)
21452 (not (string-match remove-re f)))
21453 f nil))
21454 feats)))
21455 'string-lessp)
21456 (list "org-version" "org")))
21457 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21458 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21459 load-uncore load-misses)
21460 (setq load-misses
21461 (delq 't
21462 (mapcar (lambda (f)
21463 (or (org-load-noerror-mustsuffix (concat org-dir f))
21464 (and (string= org-dir contrib-dir)
21465 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21466 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21467 (add-to-list 'load-uncore f 'append)
21470 lfeat)))
21471 (if load-uncore
21472 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21473 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21474 (if load-misses
21475 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21476 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21477 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21479 ;;;###autoload
21480 (defun org-customize ()
21481 "Call the customize function with org as argument."
21482 (interactive)
21483 (org-load-modules-maybe)
21484 (org-require-autoloaded-modules)
21485 (customize-browse 'org))
21487 (defun org-create-customize-menu ()
21488 "Create a full customization menu for Org-mode, insert it into the menu."
21489 (interactive)
21490 (org-load-modules-maybe)
21491 (org-require-autoloaded-modules)
21492 (if (fboundp 'customize-menu-create)
21493 (progn
21494 (easy-menu-change
21495 '("Org") "Customize"
21496 `(["Browse Org group" org-customize t]
21497 "--"
21498 ,(customize-menu-create 'org)
21499 ["Set" Custom-set t]
21500 ["Save" Custom-save t]
21501 ["Reset to Current" Custom-reset-current t]
21502 ["Reset to Saved" Custom-reset-saved t]
21503 ["Reset to Standard Settings" Custom-reset-standard t]))
21504 (message "\"Org\"-menu now contains full customization menu"))
21505 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21507 ;;;; Miscellaneous stuff
21509 ;;; Generally useful functions
21511 (defsubst org-get-at-bol (property)
21512 "Get text property PROPERTY at the beginning of line."
21513 (get-text-property (point-at-bol) property))
21515 (defsubst org-get-at-eol (property n)
21516 "Get text property PROPERTY at the end of line less N characters."
21517 (get-text-property (- (point-at-eol) n) property))
21519 (defun org-find-text-property-in-string (prop s)
21520 "Return the first non-nil value of property PROP in string S."
21521 (or (get-text-property 0 prop s)
21522 (get-text-property (or (next-single-property-change 0 prop s) 0)
21523 prop s)))
21525 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21526 "Display the given MESSAGE as a warning."
21527 (if (fboundp 'display-warning)
21528 (display-warning 'org message
21529 (if (featurep 'xemacs) 'warning :warning))
21530 (let ((buf (get-buffer-create "*Org warnings*")))
21531 (with-current-buffer buf
21532 (goto-char (point-max))
21533 (insert "Warning (Org): " message)
21534 (unless (bolp)
21535 (newline)))
21536 (display-buffer buf)
21537 (sit-for 0))))
21539 (defun org-eval (form)
21540 "Eval FORM and return result."
21541 (condition-case error
21542 (eval form)
21543 (error (format "%%![Error: %s]" error))))
21545 (defun org-in-clocktable-p ()
21546 "Check if the cursor is in a clocktable."
21547 (let ((pos (point)) start)
21548 (save-excursion
21549 (end-of-line 1)
21550 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21551 (setq start (match-beginning 0))
21552 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21553 (>= (match-end 0) pos)
21554 start))))
21556 (defun org-in-verbatim-emphasis ()
21557 (save-match-data
21558 (and (org-in-regexp org-emph-re 2)
21559 (>= (point) (match-beginning 3))
21560 (<= (point) (match-end 4))
21561 (member (match-string 3) '("=" "~")))))
21563 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21564 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21565 (if (and marker (marker-buffer marker)
21566 (buffer-live-p (marker-buffer marker)))
21567 (progn
21568 (org-pop-to-buffer-same-window (marker-buffer marker))
21569 (if (or (> marker (point-max)) (< marker (point-min)))
21570 (widen))
21571 (goto-char marker)
21572 (org-show-context 'org-goto))
21573 (if bookmark
21574 (bookmark-jump bookmark)
21575 (error "Cannot find location"))))
21577 (defun org-quote-csv-field (s)
21578 "Quote field for inclusion in CSV material."
21579 (if (string-match "[\",]" s)
21580 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21583 (defun org-force-self-insert (N)
21584 "Needed to enforce self-insert under remapping."
21585 (interactive "p")
21586 (self-insert-command N))
21588 (defun org-string-width (s)
21589 "Compute width of string, ignoring invisible characters.
21590 This ignores character with invisibility property `org-link', and also
21591 characters with property `org-cwidth', because these will become invisible
21592 upon the next fontification round."
21593 (let (b l)
21594 (when (or (eq t buffer-invisibility-spec)
21595 (assq 'org-link buffer-invisibility-spec))
21596 (while (setq b (text-property-any 0 (length s)
21597 'invisible 'org-link s))
21598 (setq s (concat (substring s 0 b)
21599 (substring s (or (next-single-property-change
21600 b 'invisible s) (length s)))))))
21601 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21602 (setq s (concat (substring s 0 b)
21603 (substring s (or (next-single-property-change
21604 b 'org-cwidth s) (length s))))))
21605 (setq l (string-width s) b -1)
21606 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21607 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21610 (defun org-shorten-string (s maxlength)
21611 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21612 If the string is shorter or has length MAXLENGTH, just return the
21613 original string. If it is longer, the functions finds a space in the
21614 string, breaks this string off at that locations and adds three dots
21615 as ellipsis. Including the ellipsis, the string will not be longer
21616 than MAXLENGTH. If finding a good breaking point in the string does
21617 not work, the string is just chopped off in the middle of a word
21618 if necessary."
21619 (if (<= (length s) maxlength)
21621 (let* ((n (max (- maxlength 4) 1))
21622 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21623 (if (string-match re s)
21624 (concat (match-string 1 s) "...")
21625 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21627 (defun org-get-indentation (&optional line)
21628 "Get the indentation of the current line, interpreting tabs.
21629 When LINE is given, assume it represents a line and compute its indentation."
21630 (if line
21631 (if (string-match "^ *" (org-remove-tabs line))
21632 (match-end 0))
21633 (save-excursion
21634 (beginning-of-line 1)
21635 (skip-chars-forward " \t")
21636 (current-column))))
21638 (defun org-get-string-indentation (s)
21639 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21640 (let ((n -1) (i 0) (w tab-width) c)
21641 (catch 'exit
21642 (while (< (setq n (1+ n)) (length s))
21643 (setq c (aref s n))
21644 (cond ((= c ?\ ) (setq i (1+ i)))
21645 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21646 (t (throw 'exit t)))))
21649 (defun org-remove-tabs (s &optional width)
21650 "Replace tabulators in S with spaces.
21651 Assumes that s is a single line, starting in column 0."
21652 (setq width (or width tab-width))
21653 (while (string-match "\t" s)
21654 (setq s (replace-match
21655 (make-string
21656 (- (* width (/ (+ (match-beginning 0) width) width))
21657 (match-beginning 0)) ?\ )
21658 t t s)))
21661 (defun org-fix-indentation (line ind)
21662 "Fix indentation in LINE.
21663 IND is a cons cell with target and minimum indentation.
21664 If the current indentation in LINE is smaller than the minimum,
21665 leave it alone. If it is larger than ind, set it to the target."
21666 (let* ((l (org-remove-tabs line))
21667 (i (org-get-indentation l))
21668 (i1 (car ind)) (i2 (cdr ind)))
21669 (if (>= i i2) (setq l (substring line i2)))
21670 (if (> i1 0)
21671 (concat (make-string i1 ?\ ) l)
21672 l)))
21674 (defun org-remove-indentation (code &optional n)
21675 "Remove the maximum common indentation from the lines in CODE.
21676 N may optionally be the number of spaces to remove."
21677 (with-temp-buffer
21678 (insert code)
21679 (org-do-remove-indentation n)
21680 (buffer-string)))
21682 (defun org-do-remove-indentation (&optional n)
21683 "Remove the maximum common indentation from the buffer."
21684 (untabify (point-min) (point-max))
21685 (let ((min 10000) re)
21686 (if n
21687 (setq min n)
21688 (goto-char (point-min))
21689 (while (re-search-forward "^ *[^ \n]" nil t)
21690 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21691 (unless (or (= min 0) (= min 10000))
21692 (setq re (format "^ \\{%d\\}" min))
21693 (goto-char (point-min))
21694 (while (re-search-forward re nil t)
21695 (replace-match "")
21696 (end-of-line 1))
21697 min)))
21699 (defun org-fill-template (template alist)
21700 "Find each %key of ALIST in TEMPLATE and replace it."
21701 (let ((case-fold-search nil)
21702 entry key value)
21703 (setq alist (sort (copy-sequence alist)
21704 (lambda (a b) (< (length (car a)) (length (car b))))))
21705 (while (setq entry (pop alist))
21706 (setq template
21707 (replace-regexp-in-string
21708 (concat "%" (regexp-quote (car entry)))
21709 (or (cdr entry) "") template t t)))
21710 template))
21712 (defun org-base-buffer (buffer)
21713 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21714 (if (not buffer)
21715 buffer
21716 (or (buffer-base-buffer buffer)
21717 buffer)))
21719 (defsubst org-trim (s)
21720 "Remove whitespace at the beginning and the end of string S."
21721 (replace-regexp-in-string
21722 "\\`[ \t\n\r]+" ""
21723 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
21725 (defun org-wrap (string &optional width lines)
21726 "Wrap string to either a number of lines, or a width in characters.
21727 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21728 that costs. If there is a word longer than WIDTH, the text is actually
21729 wrapped to the length of that word.
21730 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21731 many lines, whatever width that takes.
21732 The return value is a list of lines, without newlines at the end."
21733 (let* ((words (org-split-string string "[ \t\n]+"))
21734 (maxword (apply 'max (mapcar 'org-string-width words)))
21735 w ll)
21736 (cond (width
21737 (org-do-wrap words (max maxword width)))
21738 (lines
21739 (setq w maxword)
21740 (setq ll (org-do-wrap words maxword))
21741 (if (<= (length ll) lines)
21743 (setq ll words)
21744 (while (> (length ll) lines)
21745 (setq w (1+ w))
21746 (setq ll (org-do-wrap words w)))
21747 ll))
21748 (t (error "Cannot wrap this")))))
21750 (defun org-do-wrap (words width)
21751 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21752 (let (lines line)
21753 (while words
21754 (setq line (pop words))
21755 (while (and words (< (+ (length line) (length (car words))) width))
21756 (setq line (concat line " " (pop words))))
21757 (setq lines (push line lines)))
21758 (nreverse lines)))
21760 (defun org-split-string (string &optional separators)
21761 "Splits STRING into substrings at SEPARATORS.
21762 No empty strings are returned if there are matches at the beginning
21763 and end of string."
21764 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21765 (start 0)
21766 notfirst
21767 (list nil))
21768 (while (and (string-match rexp string
21769 (if (and notfirst
21770 (= start (match-beginning 0))
21771 (< start (length string)))
21772 (1+ start) start))
21773 (< (match-beginning 0) (length string)))
21774 (setq notfirst t)
21775 (or (eq (match-beginning 0) 0)
21776 (and (eq (match-beginning 0) (match-end 0))
21777 (eq (match-beginning 0) start))
21778 (setq list
21779 (cons (substring string start (match-beginning 0))
21780 list)))
21781 (setq start (match-end 0)))
21782 (or (eq start (length string))
21783 (setq list
21784 (cons (substring string start)
21785 list)))
21786 (nreverse list)))
21788 (defun org-quote-vert (s)
21789 "Replace \"|\" with \"\\vert\"."
21790 (while (string-match "|" s)
21791 (setq s (replace-match "\\vert" t t s)))
21794 (defun org-uuidgen-p (s)
21795 "Is S an ID created by UUIDGEN?"
21796 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21798 (defun org-in-src-block-p (&optional inside)
21799 "Whether point is in a code source block.
21800 When INSIDE is non-nil, don't consider we are within a src block
21801 when point is at #+BEGIN_SRC or #+END_SRC."
21802 (let ((case-fold-search t) ov)
21803 (or (and (setq ov (overlays-at (point)))
21804 (memq 'org-block-background
21805 (overlay-properties (car ov))))
21806 (and (not inside)
21807 (save-match-data
21808 (save-excursion
21809 (beginning-of-line)
21810 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21812 (defun org-context ()
21813 "Return a list of contexts of the current cursor position.
21814 If several contexts apply, all are returned.
21815 Each context entry is a list with a symbol naming the context, and
21816 two positions indicating start and end of the context. Possible
21817 contexts are:
21819 :headline anywhere in a headline
21820 :headline-stars on the leading stars in a headline
21821 :todo-keyword on a TODO keyword (including DONE) in a headline
21822 :tags on the TAGS in a headline
21823 :priority on the priority cookie in a headline
21824 :item on the first line of a plain list item
21825 :item-bullet on the bullet/number of a plain list item
21826 :checkbox on the checkbox in a plain list item
21827 :table in an org-mode table
21828 :table-special on a special filed in a table
21829 :table-table in a table.el table
21830 :clocktable in a clocktable
21831 :src-block in a source block
21832 :link on a hyperlink
21833 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21834 :target on a <<target>>
21835 :radio-target on a <<<radio-target>>>
21836 :latex-fragment on a LaTeX fragment
21837 :latex-preview on a LaTeX fragment with overlaid preview image
21839 This function expects the position to be visible because it uses font-lock
21840 faces as a help to recognize the following contexts: :table-special, :link,
21841 and :keyword."
21842 (let* ((f (get-text-property (point) 'face))
21843 (faces (if (listp f) f (list f)))
21844 (case-fold-search t)
21845 (p (point)) clist o)
21846 ;; First the large context
21847 (cond
21848 ((org-at-heading-p t)
21849 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21850 (when (progn
21851 (beginning-of-line 1)
21852 (looking-at org-todo-line-tags-regexp))
21853 (push (org-point-in-group p 1 :headline-stars) clist)
21854 (push (org-point-in-group p 2 :todo-keyword) clist)
21855 (push (org-point-in-group p 4 :tags) clist))
21856 (goto-char p)
21857 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21858 (if (looking-at "\\[#[A-Z0-9]\\]")
21859 (push (org-point-in-group p 0 :priority) clist)))
21861 ((org-at-item-p)
21862 (push (org-point-in-group p 2 :item-bullet) clist)
21863 (push (list :item (point-at-bol)
21864 (save-excursion (org-end-of-item) (point)))
21865 clist)
21866 (and (org-at-item-checkbox-p)
21867 (push (org-point-in-group p 0 :checkbox) clist)))
21869 ((org-at-table-p)
21870 (push (list :table (org-table-begin) (org-table-end)) clist)
21871 (if (memq 'org-formula faces)
21872 (push (list :table-special
21873 (previous-single-property-change p 'face)
21874 (next-single-property-change p 'face)) clist)))
21875 ((org-at-table-p 'any)
21876 (push (list :table-table) clist)))
21877 (goto-char p)
21879 (let ((case-fold-search t))
21880 ;; New the "medium" contexts: clocktables, source blocks
21881 (cond ((org-in-clocktable-p)
21882 (push (list :clocktable
21883 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21884 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21885 (match-beginning 1))
21886 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21887 (match-end 0))) clist))
21888 ((org-in-src-block-p)
21889 (push (list :src-block
21890 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21891 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21892 (match-beginning 1))
21893 (and (search-forward "#+END_SRC" nil t)
21894 (match-beginning 0))) clist))))
21895 (goto-char p)
21897 ;; Now the small context
21898 (cond
21899 ((org-at-timestamp-p)
21900 (push (org-point-in-group p 0 :timestamp) clist))
21901 ((memq 'org-link faces)
21902 (push (list :link
21903 (previous-single-property-change p 'face)
21904 (next-single-property-change p 'face)) clist))
21905 ((memq 'org-special-keyword faces)
21906 (push (list :keyword
21907 (previous-single-property-change p 'face)
21908 (next-single-property-change p 'face)) clist))
21909 ((org-at-target-p)
21910 (push (org-point-in-group p 0 :target) clist)
21911 (goto-char (1- (match-beginning 0)))
21912 (if (looking-at org-radio-target-regexp)
21913 (push (org-point-in-group p 0 :radio-target) clist))
21914 (goto-char p))
21915 ((setq o (car (delq nil
21916 (mapcar
21917 (lambda (x)
21918 (if (memq x org-latex-fragment-image-overlays) x))
21919 (overlays-at (point))))))
21920 (push (list :latex-fragment
21921 (overlay-start o) (overlay-end o)) clist)
21922 (push (list :latex-preview
21923 (overlay-start o) (overlay-end o)) clist))
21924 ((org-inside-LaTeX-fragment-p)
21925 ;; FIXME: positions wrong.
21926 (push (list :latex-fragment (point) (point)) clist)))
21928 (setq clist (nreverse (delq nil clist)))
21929 clist))
21931 ;; FIXME: Compare with at-regexp-p Do we need both?
21932 (defun org-in-regexp (re &optional nlines visually)
21933 "Check if point is inside a match of regexp.
21934 Normally only the current line is checked, but you can include NLINES extra
21935 lines both before and after point into the search.
21936 If VISUALLY is set, require that the cursor is not after the match but
21937 really on, so that the block visually is on the match."
21938 (catch 'exit
21939 (let ((pos (point))
21940 (eol (point-at-eol (+ 1 (or nlines 0))))
21941 (inc (if visually 1 0)))
21942 (save-excursion
21943 (beginning-of-line (- 1 (or nlines 0)))
21944 (while (re-search-forward re eol t)
21945 (if (and (<= (match-beginning 0) pos)
21946 (>= (+ inc (match-end 0)) pos))
21947 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21949 (defun org-at-regexp-p (regexp)
21950 "Is point inside a match of REGEXP in the current line?"
21951 (catch 'exit
21952 (save-excursion
21953 (let ((pos (point)) (end (point-at-eol)))
21954 (beginning-of-line 1)
21955 (while (re-search-forward regexp end t)
21956 (if (and (<= (match-beginning 0) pos)
21957 (>= (match-end 0) pos))
21958 (throw 'exit t)))
21959 nil))))
21961 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21962 "Non-nil when point is between matches of START-RE and END-RE.
21964 Also return a non-nil value when point is on one of the matches.
21966 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21967 buffer positions. Default values are the positions of headlines
21968 surrounding the point.
21970 The functions returns a cons cell whose car (resp. cdr) is the
21971 position before START-RE (resp. after END-RE)."
21972 (save-match-data
21973 (let ((pos (point))
21974 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21975 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21976 beg end)
21977 (save-excursion
21978 ;; Point is on a block when on START-RE or if START-RE can be
21979 ;; found before it...
21980 (and (or (org-at-regexp-p start-re)
21981 (re-search-backward start-re limit-up t))
21982 (setq beg (match-beginning 0))
21983 ;; ... and END-RE after it...
21984 (goto-char (match-end 0))
21985 (re-search-forward end-re limit-down t)
21986 (> (setq end (match-end 0)) pos)
21987 ;; ... without another START-RE in-between.
21988 (goto-char (match-beginning 0))
21989 (not (re-search-backward start-re (1+ beg) t))
21990 ;; Return value.
21991 (cons beg end))))))
21993 (defun org-in-block-p (names)
21994 "Non-nil when point belongs to a block whose name belongs to NAMES.
21996 NAMES is a list of strings containing names of blocks.
21998 Return first block name matched, or nil. Beware that in case of
21999 nested blocks, the returned name may not belong to the closest
22000 block from point."
22001 (save-match-data
22002 (catch 'exit
22003 (let ((case-fold-search t)
22004 (lim-up (save-excursion (outline-previous-heading)))
22005 (lim-down (save-excursion (outline-next-heading))))
22006 (mapc (lambda (name)
22007 (let ((n (regexp-quote name)))
22008 (when (org-between-regexps-p
22009 (concat "^[ \t]*#\\+begin_" n)
22010 (concat "^[ \t]*#\\+end_" n)
22011 lim-up lim-down)
22012 (throw 'exit n))))
22013 names))
22014 nil)))
22016 (defun org-in-drawer-p ()
22017 "Non-nil if point is within a drawer.
22018 If point is within a drawer, return it, as parsed data."
22019 (let ((element (save-match-data (org-element-at-point))))
22020 (while (and element (not (memq (org-element-type element)
22021 '(drawer property-drawer))))
22022 (setq element (org-element-property :parent element)))
22023 element))
22025 (defun org-occur-in-agenda-files (regexp &optional nlines)
22026 "Call `multi-occur' with buffers for all agenda files."
22027 (interactive "sOrg-files matching: \np")
22028 (let* ((files (org-agenda-files))
22029 (tnames (mapcar 'file-truename files))
22030 (extra org-agenda-text-search-extra-files)
22032 (when (eq (car extra) 'agenda-archives)
22033 (setq extra (cdr extra))
22034 (setq files (org-add-archive-files files)))
22035 (while (setq f (pop extra))
22036 (unless (member (file-truename f) tnames)
22037 (add-to-list 'files f 'append)
22038 (add-to-list 'tnames (file-truename f) 'append)))
22039 (multi-occur
22040 (mapcar (lambda (x)
22041 (with-current-buffer
22042 (or (get-file-buffer x) (find-file-noselect x))
22043 (widen)
22044 (current-buffer)))
22045 files)
22046 regexp)))
22048 (if (boundp 'occur-mode-find-occurrence-hook)
22049 ;; Emacs 23
22050 (add-hook 'occur-mode-find-occurrence-hook
22051 (lambda ()
22052 (when (derived-mode-p 'org-mode)
22053 (org-reveal))))
22054 ;; Emacs 22
22055 (defadvice occur-mode-goto-occurrence
22056 (after org-occur-reveal activate)
22057 (and (derived-mode-p 'org-mode) (org-reveal)))
22058 (defadvice occur-mode-goto-occurrence-other-window
22059 (after org-occur-reveal activate)
22060 (and (derived-mode-p 'org-mode) (org-reveal)))
22061 (defadvice occur-mode-display-occurrence
22062 (after org-occur-reveal activate)
22063 (when (derived-mode-p 'org-mode)
22064 (let ((pos (occur-mode-find-occurrence)))
22065 (with-current-buffer (marker-buffer pos)
22066 (save-excursion
22067 (goto-char pos)
22068 (org-reveal)))))))
22070 (defun org-occur-link-in-agenda-files ()
22071 "Create a link and search for it in the agendas.
22072 The link is not stored in `org-stored-links', it is just created
22073 for the search purpose."
22074 (interactive)
22075 (let ((link (condition-case nil
22076 (org-store-link nil)
22077 (error "Unable to create a link to here"))))
22078 (org-occur-in-agenda-files (regexp-quote link))))
22080 (defun org-reverse-string (string)
22081 "Return the reverse of STRING."
22082 (apply 'string (reverse (string-to-list string))))
22084 (defun org-uniquify-alist (alist)
22085 "Merge elements of ALIST with the same key.
22087 For example, in this alist:
22089 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22090 => '((a 1 3) (b 2))
22092 merge (a 1) and (a 3) into (a 1 3).
22094 The function returns the new ALIST."
22095 (let (rtn)
22096 (mapc
22097 (lambda (e)
22098 (let (n)
22099 (if (not (assoc (car e) rtn))
22100 (push e rtn)
22101 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22102 (setq rtn (assq-delete-all (car e) rtn))
22103 (push n rtn))))
22104 alist)
22105 rtn))
22107 (defun org-delete-all (elts list)
22108 "Remove all elements in ELTS from LIST."
22109 (while elts
22110 (setq list (delete (pop elts) list)))
22111 list)
22113 (defun org-count (cl-item cl-seq)
22114 "Count the number of occurrences of ITEM in SEQ.
22115 Taken from `count' in cl-seq.el with all keyword arguments removed."
22116 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22117 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22118 (while (< cl-start cl-end)
22119 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22120 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22121 (setq cl-start (1+ cl-start)))
22122 cl-count))
22124 (defun org-remove-if (predicate seq)
22125 "Remove everything from SEQ that fulfills PREDICATE."
22126 (let (res e)
22127 (while seq
22128 (setq e (pop seq))
22129 (if (not (funcall predicate e)) (push e res)))
22130 (nreverse res)))
22132 (defun org-remove-if-not (predicate seq)
22133 "Remove everything from SEQ that does not fulfill PREDICATE."
22134 (let (res e)
22135 (while seq
22136 (setq e (pop seq))
22137 (if (funcall predicate e) (push e res)))
22138 (nreverse res)))
22140 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22141 "Reduce two-argument FUNCTION across SEQ.
22142 Taken from `reduce' in cl-seq.el with all keyword arguments but
22143 \":initial-value\" removed."
22144 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22145 (cadr (memq :initial-value cl-keys)))
22146 (cl-seq (pop cl-seq))
22147 (t (funcall cl-func)))))
22148 (while cl-seq
22149 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22150 cl-accum))
22152 (defun org-every (pred seq)
22153 "Return true if PREDICATE is true of every element of SEQ.
22154 Adapted from `every' in cl.el."
22155 (catch 'org-every
22156 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22159 (defun org-some (pred seq)
22160 "Return true if PREDICATE is true of any element of SEQ.
22161 Adapted from `some' in cl.el."
22162 (catch 'org-some
22163 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22164 nil))
22166 (defun org-back-over-empty-lines ()
22167 "Move backwards over whitespace, to the beginning of the first empty line.
22168 Returns the number of empty lines passed."
22169 (let ((pos (point)))
22170 (if (cdr (assoc 'heading org-blank-before-new-entry))
22171 (skip-chars-backward " \t\n\r")
22172 (unless (eobp)
22173 (forward-line -1)))
22174 (beginning-of-line 2)
22175 (goto-char (min (point) pos))
22176 (count-lines (point) pos)))
22178 (defun org-skip-whitespace ()
22179 (skip-chars-forward " \t\n\r"))
22181 (defun org-point-in-group (point group &optional context)
22182 "Check if POINT is in match-group GROUP.
22183 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22184 match. If the match group does not exist or point is not inside it,
22185 return nil."
22186 (and (match-beginning group)
22187 (>= point (match-beginning group))
22188 (<= point (match-end group))
22189 (if context
22190 (list context (match-beginning group) (match-end group))
22191 t)))
22193 (defun org-switch-to-buffer-other-window (&rest args)
22194 "Switch to buffer in a second window on the current frame.
22195 In particular, do not allow pop-up frames.
22196 Returns the newly created buffer."
22197 (org-no-popups
22198 (apply 'switch-to-buffer-other-window args)))
22200 (defun org-combine-plists (&rest plists)
22201 "Create a single property list from all plists in PLISTS.
22202 The process starts by copying the first list, and then setting properties
22203 from the other lists. Settings in the last list are the most significant
22204 ones and overrule settings in the other lists."
22205 (let ((rtn (copy-sequence (pop plists)))
22206 p v ls)
22207 (while plists
22208 (setq ls (pop plists))
22209 (while ls
22210 (setq p (pop ls) v (pop ls))
22211 (setq rtn (plist-put rtn p v))))
22212 rtn))
22214 (defun org-replace-escapes (string table)
22215 "Replace %-escapes in STRING with values in TABLE.
22216 TABLE is an association list with keys like \"%a\" and string values.
22217 The sequences in STRING may contain normal field width and padding information,
22218 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22219 so values can contain further %-escapes if they are define later in TABLE."
22220 (let ((tbl (copy-alist table))
22221 (case-fold-search nil)
22222 (pchg 0)
22223 e re rpl)
22224 (while (setq e (pop tbl))
22225 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22226 (when (and (cdr e) (string-match re (cdr e)))
22227 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22228 (safe "SREF"))
22229 (add-text-properties 0 3 (list 'sref sref) safe)
22230 (setcdr e (replace-match safe t t (cdr e)))))
22231 (while (string-match re string)
22232 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22233 (cdr e)))
22234 (setq string (replace-match rpl t t string))))
22235 (while (setq pchg (next-property-change pchg string))
22236 (let ((sref (get-text-property pchg 'sref string)))
22237 (when (and sref (string-match "SREF" string pchg))
22238 (setq string (replace-match sref t t string)))))
22239 string))
22241 (defun org-sublist (list start end)
22242 "Return a section of LIST, from START to END.
22243 Counting starts at 1."
22244 (let (rtn (c start))
22245 (setq list (nthcdr (1- start) list))
22246 (while (and list (<= c end))
22247 (push (pop list) rtn)
22248 (setq c (1+ c)))
22249 (nreverse rtn)))
22251 (defun org-find-base-buffer-visiting (file)
22252 "Like `find-buffer-visiting' but always return the base buffer and
22253 not an indirect buffer."
22254 (let ((buf (or (get-file-buffer file)
22255 (find-buffer-visiting file))))
22256 (if buf
22257 (or (buffer-base-buffer buf) buf)
22258 nil)))
22260 (defun org-image-file-name-regexp (&optional extensions)
22261 "Return regexp matching the file names of images.
22262 If EXTENSIONS is given, only match these."
22263 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22264 (image-file-name-regexp)
22265 (let ((image-file-name-extensions
22266 (or extensions
22267 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22268 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22269 (concat "\\."
22270 (regexp-opt (nconc (mapcar 'upcase
22271 image-file-name-extensions)
22272 image-file-name-extensions)
22274 "\\'"))))
22276 (defun org-file-image-p (file &optional extensions)
22277 "Return non-nil if FILE is an image."
22278 (save-match-data
22279 (string-match (org-image-file-name-regexp extensions) file)))
22281 (defun org-get-cursor-date (&optional with-time)
22282 "Return the date at cursor in as a time.
22283 This works in the calendar and in the agenda, anywhere else it just
22284 returns the current time.
22285 If WITH-TIME is non-nil, returns the time of the event at point (in
22286 the agenda) or the current time of the day."
22287 (let (date day defd tp tm hod mod)
22288 (when with-time
22289 (setq tp (get-text-property (point) 'time))
22290 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22291 (setq hod (string-to-number (match-string 1 tp))
22292 mod (string-to-number (match-string 2 tp))))
22293 (or tp (setq hod (nth 2 (decode-time (current-time)))
22294 mod (nth 1 (decode-time (current-time))))))
22295 (cond
22296 ((eq major-mode 'calendar-mode)
22297 (setq date (calendar-cursor-to-date)
22298 defd (encode-time 0 (or mod 0) (or hod 0)
22299 (nth 1 date) (nth 0 date) (nth 2 date))))
22300 ((eq major-mode 'org-agenda-mode)
22301 (setq day (get-text-property (point) 'day))
22302 (if day
22303 (setq date (calendar-gregorian-from-absolute day)
22304 defd (encode-time 0 (or mod 0) (or hod 0)
22305 (nth 1 date) (nth 0 date) (nth 2 date))))))
22306 (or defd (current-time))))
22308 (defun org-mark-subtree (&optional up)
22309 "Mark the current subtree.
22310 This puts point at the start of the current subtree, and mark at
22311 the end. If a numeric prefix UP is given, move up into the
22312 hierarchy of headlines by UP levels before marking the subtree."
22313 (interactive "P")
22314 (org-with-limited-levels
22315 (cond ((org-at-heading-p) (beginning-of-line))
22316 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22317 (t (outline-previous-visible-heading 1))))
22318 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22319 (if (org-called-interactively-p 'any)
22320 (call-interactively 'org-mark-element)
22321 (org-mark-element)))
22324 ;;; Indentation
22326 (defun org--get-expected-indentation (element contentsp)
22327 "Expected indentation column for current line, according to ELEMENT.
22328 ELEMENT is an element containing point. CONTENTSP is non-nil
22329 when indentation is to be computed according to contents of
22330 ELEMENT."
22331 (let ((type (org-element-type element))
22332 (start (org-element-property :begin element)))
22333 (org-with-wide-buffer
22334 (cond
22335 (contentsp
22336 (case type
22337 (footnote-definition 0)
22338 ((headline inlinetask nil)
22339 (if (not org-adapt-indentation) 0
22340 (let ((level (org-current-level)))
22341 (if level (1+ level) 0))))
22342 ((item plain list)
22343 (org-list-item-body-column
22344 (or (org-element-property :post-affiliated element) start)))
22345 (otherwise
22346 (goto-char start)
22347 (org-get-indentation))))
22348 ((memq type '(headline inlinetask nil))
22349 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22350 (org--get-expected-indentation element t)
22352 ((eq type 'footnote-definition) 0)
22353 ;; First paragraph of a footnote definition or an item.
22354 ;; Indent like parent.
22355 ((< (line-beginning-position) start)
22356 (org--get-expected-indentation
22357 (org-element-property :parent element) t))
22358 ;; At first line: indent according to previous sibling, if any,
22359 ;; ignoring footnote definitions and inline tasks, or parent's
22360 ;; contents.
22361 ((= (line-beginning-position) start)
22362 (catch 'exit
22363 (while t
22364 (if (= (point-min) start) (throw 'exit 0)
22365 (goto-char (1- start))
22366 (let ((previous (org-element-at-point)))
22367 (while (let ((parent (org-element-property :parent previous)))
22368 (and parent
22369 (setq previous parent)
22370 (<= (org-element-property :end parent) start))))
22371 (cond ((or (not previous)
22372 (> (org-element-property :end previous) start))
22373 (throw 'exit (org--get-expected-indentation previous t)))
22374 ((memq (org-element-type previous)
22375 '(footnote-definition inlinetask))
22376 (setq start (org-element-property :begin previous)))
22377 (t (goto-char (org-element-property :begin previous))
22378 (throw 'exit (org-get-indentation)))))))))
22379 ;; Otherwise, move to the first non-blank line above.
22381 (beginning-of-line)
22382 (let ((pos (point)))
22383 (skip-chars-backward " \r\t\n")
22384 (cond
22385 ;; Two blank lines end a footnote definition or a plain
22386 ;; list. When we indent an empty line after them, the
22387 ;; containing list or footnote definition is over, so it
22388 ;; qualifies as a previous sibling. Therefore, we indent
22389 ;; like its first line.
22390 ((and (memq type '(footnote-definition plain-list))
22391 (> (count-lines (point) pos) 2))
22392 (goto-char start)
22393 (org-get-indentation))
22394 ;; Line above is the first one of a paragraph at the
22395 ;; beginning of an item or a footnote definition. Indent
22396 ;; like parent.
22397 ((< (line-beginning-position) start)
22398 (org--get-expected-indentation
22399 (org-element-property :parent element) t))
22400 ;; POS is after contents in a greater element. Indent like
22401 ;; the beginning of the element.
22403 ;; As a special case, if point is at the end of a footnote
22404 ;; definition or an item, indent like the very last element
22405 ;; within.
22406 ((let ((cend (org-element-property :contents-end element)))
22407 (and cend (<= cend pos)))
22408 (if (memq type '(footnote-definition item plain-list))
22409 (org--get-expected-indentation (org-element-at-point) nil)
22410 (goto-char start)
22411 (org-get-indentation)))
22412 ;; In any other case, indent like the current line.
22413 (t (org-get-indentation)))))))))
22415 (defun org--align-node-property ()
22416 "Align node property at point.
22417 Alignment is done according to `org-property-format', which see."
22418 (when (save-excursion
22419 (beginning-of-line)
22420 (looking-at org-property-re))
22421 (replace-match
22422 (concat (match-string 4)
22423 (format org-property-format (match-string 1) (match-string 3)))
22424 t t)))
22426 (defun org-indent-line ()
22427 "Indent line depending on context.
22429 Indentation is done according to the following rules:
22431 - Footnote definitions, headlines and inline tasks have to
22432 start at column 0.
22434 - On the very first line of an element, consider, in order, the
22435 next rules until one matches:
22437 1. If there's a sibling element before, ignoring footnote
22438 definitions and inline tasks, indent like its first line.
22440 2. If element has a parent, indent like its contents. More
22441 precisely, if parent is an item, indent after the
22442 description part, if any, or the bullet (see
22443 ``org-list-description-max-indent'). Else, indent like
22444 parent's first line.
22446 3. Otherwise, indent relatively to current level, if
22447 `org-adapt-indentation' is non-nil, or to left margin.
22449 - On a blank line at the end of a plain list, an item, or
22450 a footnote definition, indent like the very last element
22451 within.
22453 - In the code part of a source block, use language major mode
22454 to indent current line if `org-src-tab-acts-natively' is
22455 non-nil. If it is nil, do nothing.
22457 - Otherwise, indent like the first non-blank line above.
22459 The function doesn't indent an item as it could break the whole
22460 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22461 \\[org-shiftmetaright].
22463 Also align node properties according to `org-property-format'."
22464 (interactive)
22465 (cond
22466 (orgstruct-is-++
22467 (let ((indent-line-function
22468 (cadadr (assq 'indent-line-function org-fb-vars))))
22469 (indent-according-to-mode)))
22470 ((org-at-heading-p) 'noindent)
22472 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22473 (type (org-element-type element)))
22474 (cond ((and (memq type '(plain-list item))
22475 (= (line-beginning-position)
22476 (or (org-element-property :post-affiliated element)
22477 (org-element-property :begin element))))
22478 'noindent)
22479 ((and (eq type 'src-block)
22480 org-src-tab-acts-natively
22481 (> (line-beginning-position)
22482 (org-element-property :post-affiliated element))
22483 (< (line-beginning-position)
22484 (org-with-wide-buffer
22485 (goto-char (org-element-property :end element))
22486 (skip-chars-backward " \r\t\n")
22487 (line-beginning-position))))
22488 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
22489 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB"))))
22491 (let ((column (org--get-expected-indentation element nil)))
22492 ;; Preserve current column.
22493 (if (<= (current-column) (current-indentation))
22494 (org-indent-line-to column)
22495 (save-excursion (org-indent-line-to column))))
22496 ;; Align node property. Also preserve current column.
22497 (when (eq type 'node-property)
22498 (let ((column (current-column)))
22499 (org--align-node-property)
22500 (org-move-to-column column)))))))))
22502 (defun org-indent-region (start end)
22503 "Indent each non-blank line in the region.
22504 Called from a program, START and END specify the region to
22505 indent. The function will not indent contents of example blocks,
22506 verse blocks and export blocks as leading white spaces are
22507 assumed to be significant there."
22508 (interactive "r")
22509 (save-excursion
22510 (goto-char start)
22511 (beginning-of-line)
22512 (let ((indent-to
22513 (lambda (ind pos)
22514 ;; Set IND as indentation for all lines between point and
22515 ;; POS or END, whichever comes first. Blank lines are
22516 ;; ignored. Leave point after POS once done.
22517 (let ((limit (copy-marker (min end pos))))
22518 (while (< (point) limit)
22519 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22520 (forward-line))
22521 (set-marker limit nil))))
22522 (end (copy-marker end)))
22523 (while (< (point) end)
22524 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22525 (let* ((element (org-element-at-point))
22526 (type (org-element-type element))
22527 (element-end (copy-marker (org-element-property :end element)))
22528 (ind (org--get-expected-indentation element nil)))
22529 (if (or (memq type '(paragraph table table-row))
22530 (not (or (org-element-property :contents-begin element)
22531 (memq type
22532 '(example-block export-block src-block)))))
22533 ;; Elements here are indented as a single block. Also
22534 ;; align node properties.
22535 (progn
22536 (when (eq type 'node-property)
22537 (org--align-node-property)
22538 (beginning-of-line))
22539 (funcall indent-to ind element-end))
22540 ;; Elements in this category consist of three parts:
22541 ;; before the contents, the contents, and after the
22542 ;; contents. The contents are treated specially,
22543 ;; according to the element type, or not indented at
22544 ;; all. Other parts are indented as a single block.
22545 (let* ((post (copy-marker
22546 (or (org-element-property :post-affiliated element)
22547 (org-element-property :begin element))))
22548 (cbeg
22549 (copy-marker
22550 (cond
22551 ((not (org-element-property :contents-begin element))
22552 ;; Fake contents for source blocks.
22553 (org-with-wide-buffer
22554 (goto-char post)
22555 (forward-line)
22556 (point)))
22557 ((memq type '(footnote-definition item plain-list))
22558 ;; Contents in these elements could start on
22559 ;; the same line as the beginning of the
22560 ;; element. Make sure we start indenting
22561 ;; from the second line.
22562 (org-with-wide-buffer
22563 (goto-char post)
22564 (forward-line)
22565 (point)))
22566 (t (org-element-property :contents-begin element)))))
22567 (cend (copy-marker
22568 (or (org-element-property :contents-end element)
22569 ;; Fake contents for source blocks.
22570 (org-with-wide-buffer
22571 (goto-char element-end)
22572 (skip-chars-backward " \r\t\n")
22573 (line-beginning-position))))))
22574 (funcall indent-to ind cbeg)
22575 (when (< (point) end)
22576 (case type
22577 ((example-block export-block verse-block))
22578 (src-block
22579 ;; In a source block, indent source code according
22580 ;; to language major mode, but only if
22581 ;; `org-src-tab-acts-natively' is non-nil.
22582 (when (and (< (point) end) org-src-tab-acts-natively)
22583 (ignore-errors
22584 (let (org-src-strip-leading-and-trailing-blank-lines
22585 ;; Region boundaries in edit buffer.
22586 (start (1+ (- (point) cbeg)))
22587 (end (- (min cend end) cbeg)))
22588 (org-babel-do-in-edit-buffer
22589 (indent-region start end))))))
22590 (t (org-indent-region (point) (min cend end))))
22591 (goto-char (min cend end))
22592 (when (< (point) end) (funcall indent-to ind element-end)))
22593 (set-marker post nil)
22594 (set-marker cbeg nil)
22595 (set-marker cend nil)))
22596 (set-marker element-end nil))))
22597 (set-marker end nil))))
22599 (defun org-indent-drawer ()
22600 "Indent the drawer at point."
22601 (interactive)
22602 (unless (save-excursion
22603 (beginning-of-line)
22604 (org-looking-at-p org-drawer-regexp))
22605 (user-error "Not at a drawer"))
22606 (let ((element (org-element-at-point)))
22607 (unless (memq (org-element-type element) '(drawer property-drawer))
22608 (user-error "Not at a drawer"))
22609 (org-with-wide-buffer
22610 (org-indent-region (org-element-property :begin element)
22611 (org-element-property :end element))))
22612 (message "Drawer at point indented"))
22614 (defun org-indent-block ()
22615 "Indent the block at point."
22616 (interactive)
22617 (unless (save-excursion
22618 (beginning-of-line)
22619 (let ((case-fold-search t))
22620 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22621 (user-error "Not at a block"))
22622 (let ((element (org-element-at-point)))
22623 (unless (memq (org-element-type element)
22624 '(comment-block center-block example-block export-block
22625 quote-block special-block src-block
22626 verse-block))
22627 (user-error "Not at a block"))
22628 (org-with-wide-buffer
22629 (org-indent-region (org-element-property :begin element)
22630 (org-element-property :end element))))
22631 (message "Block at point indented"))
22634 ;;; Filling
22636 ;; We use our own fill-paragraph and auto-fill functions.
22638 ;; `org-fill-paragraph' relies on adaptive filling and context
22639 ;; checking. Appropriate `fill-prefix' is computed with
22640 ;; `org-adaptive-fill-function'.
22642 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22643 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22644 ;; `org-adaptive-fill-function' value. Internally,
22645 ;; `org-comment-line-break-function' breaks the line.
22647 ;; `org-setup-filling' installs filling and auto-filling related
22648 ;; variables during `org-mode' initialization.
22650 (defvar org-element-paragraph-separate) ; org-element.el
22651 (defun org-setup-filling ()
22652 (require 'org-element)
22653 ;; Prevent auto-fill from inserting unwanted new items.
22654 (when (boundp 'fill-nobreak-predicate)
22655 (org-set-local
22656 'fill-nobreak-predicate
22657 (org-uniquify
22658 (append fill-nobreak-predicate
22659 '(org-fill-line-break-nobreak-p
22660 org-fill-paragraph-with-timestamp-nobreak-p)))))
22661 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22662 (org-set-local 'paragraph-start paragraph-ending)
22663 (org-set-local 'paragraph-separate paragraph-ending))
22664 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22665 (org-set-local 'auto-fill-inhibit-regexp nil)
22666 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22667 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22668 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22670 (defun org-fill-line-break-nobreak-p ()
22671 "Non-nil when a new line at point would create an Org line break."
22672 (save-excursion
22673 (skip-chars-backward "[ \t]")
22674 (skip-chars-backward "\\\\")
22675 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22677 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22678 "Non-nil when a new line at point would split a timestamp."
22679 (and (org-at-timestamp-p t)
22680 (not (looking-at org-ts-regexp-both))))
22682 (declare-function message-in-body-p "message" ())
22683 (defvar orgtbl-line-start-regexp) ; From org-table.el
22684 (defun org-adaptive-fill-function ()
22685 "Compute a fill prefix for the current line.
22686 Return fill prefix, as a string, or nil if current line isn't
22687 meant to be filled. For convenience, if `adaptive-fill-regexp'
22688 matches in paragraphs or comments, use it."
22689 (catch 'exit
22690 (when (derived-mode-p 'message-mode)
22691 (save-excursion
22692 (beginning-of-line)
22693 (cond ((or (not (message-in-body-p))
22694 (looking-at orgtbl-line-start-regexp))
22695 (throw 'exit nil))
22696 ((looking-at message-cite-prefix-regexp)
22697 (throw 'exit (match-string-no-properties 0)))
22698 ((looking-at org-outline-regexp)
22699 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22700 (org-with-wide-buffer
22701 (let* ((p (line-beginning-position))
22702 (element (save-excursion
22703 (beginning-of-line)
22704 (or (ignore-errors (org-element-at-point))
22705 (user-error "An element cannot be parsed line %d"
22706 (line-number-at-pos (point))))))
22707 (type (org-element-type element))
22708 (post-affiliated (org-element-property :post-affiliated element)))
22709 (unless (and post-affiliated (< p post-affiliated))
22710 (case type
22711 (comment
22712 (save-excursion
22713 (beginning-of-line)
22714 (looking-at "[ \t]*")
22715 (concat (match-string 0) "# ")))
22716 (footnote-definition "")
22717 ((item plain-list)
22718 (make-string (org-list-item-body-column
22719 (or post-affiliated
22720 (org-element-property :begin element)))
22721 ? ))
22722 (paragraph
22723 ;; Fill prefix is usually the same as the current line,
22724 ;; unless the paragraph is at the beginning of an item.
22725 (let ((parent (org-element-property :parent element)))
22726 (save-excursion
22727 (beginning-of-line)
22728 (cond ((eq (org-element-type parent) 'item)
22729 (make-string (org-list-item-body-column
22730 (org-element-property :begin parent))
22731 ? ))
22732 ((and adaptive-fill-regexp
22733 ;; Locally disable
22734 ;; `adaptive-fill-function' to let
22735 ;; `fill-context-prefix' handle
22736 ;; `adaptive-fill-regexp' variable.
22737 (let (adaptive-fill-function)
22738 (fill-context-prefix
22739 post-affiliated
22740 (org-element-property :end element)))))
22741 ((looking-at "[ \t]+") (match-string 0))
22742 (t "")))))
22743 (comment-block
22744 ;; Only fill contents if P is within block boundaries.
22745 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22746 (forward-line)
22747 (point)))
22748 (cend (save-excursion
22749 (goto-char (org-element-property :end element))
22750 (skip-chars-backward " \r\t\n")
22751 (line-beginning-position))))
22752 (when (and (>= p cbeg) (< p cend))
22753 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22754 (match-string 0)
22755 ""))))))))))
22757 (declare-function message-goto-body "message" ())
22758 (defvar message-cite-prefix-regexp) ; From message.el
22759 (defun org-fill-paragraph (&optional justify)
22760 "Fill element at point, when applicable.
22762 This function only applies to comment blocks, comments, example
22763 blocks and paragraphs. Also, as a special case, re-align table
22764 when point is at one.
22766 If JUSTIFY is non-nil (interactively, with prefix argument),
22767 justify as well. If `sentence-end-double-space' is non-nil, then
22768 period followed by one space does not end a sentence, so don't
22769 break a line there. The variable `fill-column' controls the
22770 width for filling.
22772 For convenience, when point is at a plain list, an item or
22773 a footnote definition, try to fill the first paragraph within."
22774 (interactive)
22775 (if (and (derived-mode-p 'message-mode)
22776 (or (not (message-in-body-p))
22777 (save-excursion (move-beginning-of-line 1)
22778 (looking-at message-cite-prefix-regexp))))
22779 ;; First ensure filling is correct in message-mode.
22780 (let ((fill-paragraph-function
22781 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22782 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22783 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22784 (paragraph-separate
22785 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22786 (fill-paragraph nil))
22787 (with-syntax-table org-mode-transpose-word-syntax-table
22788 ;; Move to end of line in order to get the first paragraph
22789 ;; within a plain list or a footnote definition.
22790 (let ((element (save-excursion
22791 (end-of-line)
22792 (or (ignore-errors (org-element-at-point))
22793 (user-error "An element cannot be parsed line %d"
22794 (line-number-at-pos (point)))))))
22795 ;; First check if point is in a blank line at the beginning of
22796 ;; the buffer. In that case, ignore filling.
22797 (case (org-element-type element)
22798 ;; Use major mode filling function is src blocks.
22799 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22800 ;; Align Org tables, leave table.el tables as-is.
22801 (table-row (org-table-align) t)
22802 (table
22803 (when (eq (org-element-property :type element) 'org)
22804 (save-excursion
22805 (goto-char (org-element-property :post-affiliated element))
22806 (org-table-align)))
22808 (paragraph
22809 ;; Paragraphs may contain `line-break' type objects.
22810 (let ((beg (max (point-min)
22811 (org-element-property :contents-begin element)))
22812 (end (min (point-max)
22813 (org-element-property :contents-end element))))
22814 ;; Do nothing if point is at an affiliated keyword.
22815 (if (< (line-end-position) beg) t
22816 (when (derived-mode-p 'message-mode)
22817 ;; In `message-mode', do not fill following citation
22818 ;; in current paragraph nor text before message body.
22819 (let ((body-start (save-excursion (message-goto-body))))
22820 (when body-start (setq beg (max body-start beg))))
22821 (when (save-excursion
22822 (re-search-forward
22823 (concat "^" message-cite-prefix-regexp) end t))
22824 (setq end (match-beginning 0))))
22825 ;; Fill paragraph, taking line breaks into account.
22826 ;; For that, slice the paragraph using line breaks as
22827 ;; separators, and fill the parts in reverse order to
22828 ;; avoid messing with markers.
22829 (save-excursion
22830 (goto-char end)
22831 (mapc
22832 (lambda (pos)
22833 (fill-region-as-paragraph pos (point) justify)
22834 (goto-char pos))
22835 ;; Find the list of ending positions for line breaks
22836 ;; in the current paragraph. Add paragraph
22837 ;; beginning to include first slice.
22838 (nreverse
22839 (cons beg
22840 (org-element-map
22841 (org-element--parse-objects
22842 beg end nil (org-element-restriction 'paragraph))
22843 'line-break
22844 (lambda (lb) (org-element-property :end lb)))))))
22845 t)))
22846 ;; Contents of `comment-block' type elements should be
22847 ;; filled as plain text, but only if point is within block
22848 ;; markers.
22849 (comment-block
22850 (let* ((case-fold-search t)
22851 (beg (save-excursion
22852 (goto-char (org-element-property :begin element))
22853 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22854 (forward-line)
22855 (point)))
22856 (end (save-excursion
22857 (goto-char (org-element-property :end element))
22858 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22859 (line-beginning-position))))
22860 (if (or (< (point) beg) (> (point) end)) t
22861 (fill-region-as-paragraph
22862 (save-excursion (end-of-line)
22863 (re-search-backward "^[ \t]*$" beg 'move)
22864 (line-beginning-position))
22865 (save-excursion (beginning-of-line)
22866 (re-search-forward "^[ \t]*$" end 'move)
22867 (line-beginning-position))
22868 justify))))
22869 ;; Fill comments.
22870 (comment
22871 (let ((begin (org-element-property :post-affiliated element))
22872 (end (org-element-property :end element)))
22873 (when (and (>= (point) begin) (<= (point) end))
22874 (let ((begin (save-excursion
22875 (end-of-line)
22876 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22877 (progn (forward-line) (point))
22878 begin)))
22879 (end (save-excursion
22880 (end-of-line)
22881 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22882 (1- (line-beginning-position))
22883 (skip-chars-backward " \r\t\n")
22884 (line-end-position)))))
22885 ;; Do not fill comments when at a blank line.
22886 (when (> end begin)
22887 (let ((fill-prefix
22888 (save-excursion
22889 (beginning-of-line)
22890 (looking-at "[ \t]*#")
22891 (let ((comment-prefix (match-string 0)))
22892 (goto-char (match-end 0))
22893 (if (looking-at adaptive-fill-regexp)
22894 (concat comment-prefix (match-string 0))
22895 (concat comment-prefix " "))))))
22896 (save-excursion
22897 (fill-region-as-paragraph begin end justify))))))
22899 ;; Ignore every other element.
22900 (otherwise t))))))
22902 (defun org-auto-fill-function ()
22903 "Auto-fill function."
22904 ;; Check if auto-filling is meaningful.
22905 (let ((fc (current-fill-column)))
22906 (when (and fc (> (current-column) fc))
22907 (let* ((fill-prefix (org-adaptive-fill-function))
22908 ;; Enforce empty fill prefix, if required. Otherwise, it
22909 ;; will be computed again.
22910 (adaptive-fill-mode (not (equal fill-prefix ""))))
22911 (when fill-prefix (do-auto-fill))))))
22913 (defun org-comment-line-break-function (&optional soft)
22914 "Break line at point and indent, continuing comment if within one.
22915 The inserted newline is marked hard if variable
22916 `use-hard-newlines' is true, unless optional argument SOFT is
22917 non-nil."
22918 (if soft (insert-and-inherit ?\n) (newline 1))
22919 (save-excursion (forward-char -1) (delete-horizontal-space))
22920 (delete-horizontal-space)
22921 (indent-to-left-margin)
22922 (insert-before-markers-and-inherit fill-prefix))
22925 ;;; Fixed Width Areas
22927 (defun org-toggle-fixed-width ()
22928 "Toggle fixed-width markup.
22930 Add or remove fixed-width markup on current line, whenever it
22931 makes sense. Return an error otherwise.
22933 If a region is active and if it contains only fixed-width areas
22934 or blank lines, remove all fixed-width markup in it. If the
22935 region contains anything else, convert all non-fixed-width lines
22936 to fixed-width ones.
22938 Blank lines at the end of the region are ignored unless the
22939 region only contains such lines."
22940 (interactive)
22941 (if (not (org-region-active-p))
22942 ;; No region:
22944 ;; Remove fixed width marker only in a fixed-with element.
22946 ;; Add fixed width maker in paragraphs, in blank lines after
22947 ;; elements or at the beginning of a headline or an inlinetask,
22948 ;; and before any one-line elements (e.g., a clock).
22949 (progn
22950 (beginning-of-line)
22951 (let* ((element (org-element-at-point))
22952 (type (org-element-type element)))
22953 (cond
22954 ((and (eq type 'fixed-width)
22955 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22956 (replace-match
22957 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22958 ((and (memq type '(babel-call clock comment diary-sexp headline
22959 horizontal-rule keyword paragraph
22960 planning))
22961 (or (not (org-element-property :post-affiliated element))
22962 (<= (org-element-property :post-affiliated element)
22963 (point))))
22964 (skip-chars-forward " \t")
22965 (insert ": "))
22966 ((and (org-looking-at-p "[ \t]*$")
22967 (or (eq type 'inlinetask)
22968 (save-excursion
22969 (skip-chars-forward " \r\t\n")
22970 (<= (org-element-property :end element) (point)))))
22971 (delete-region (point) (line-end-position))
22972 (org-indent-line)
22973 (insert ": "))
22974 (t (user-error "Cannot insert a fixed-width line here")))))
22975 ;; Region active.
22976 (let* ((begin (save-excursion
22977 (goto-char (region-beginning))
22978 (line-beginning-position)))
22979 (end (copy-marker
22980 (save-excursion
22981 (goto-char (region-end))
22982 (unless (eolp) (beginning-of-line))
22983 (if (save-excursion (re-search-backward "\\S-" begin t))
22984 (progn (skip-chars-backward " \r\t\n") (point))
22985 (point)))))
22986 (all-fixed-width-p
22987 (catch 'not-all-p
22988 (save-excursion
22989 (goto-char begin)
22990 (skip-chars-forward " \r\t\n")
22991 (when (eobp) (throw 'not-all-p nil))
22992 (while (< (point) end)
22993 (let ((element (org-element-at-point)))
22994 (if (eq (org-element-type element) 'fixed-width)
22995 (goto-char (org-element-property :end element))
22996 (throw 'not-all-p nil))))
22997 t))))
22998 (if all-fixed-width-p
22999 (save-excursion
23000 (goto-char begin)
23001 (while (< (point) end)
23002 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23003 (replace-match
23004 "" nil nil nil
23005 (if (= (line-end-position) (match-end 0)) 0 1)))
23006 (forward-line)))
23007 (let ((min-ind (point-max)))
23008 ;; Find minimum indentation across all lines.
23009 (save-excursion
23010 (goto-char begin)
23011 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23012 (setq min-ind 0)
23013 (catch 'zerop
23014 (while (< (point) end)
23015 (unless (org-looking-at-p "[ \t]*$")
23016 (let ((ind (org-get-indentation)))
23017 (setq min-ind (min min-ind ind))
23018 (when (zerop ind) (throw 'zerop t))))
23019 (forward-line)))))
23020 ;; Loop over all lines and add fixed-width markup everywhere
23021 ;; but in fixed-width lines.
23022 (save-excursion
23023 (goto-char begin)
23024 (while (< (point) end)
23025 (cond
23026 ((org-at-heading-p)
23027 (insert ": ")
23028 (forward-line)
23029 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23030 (insert ":")
23031 (forward-line)))
23032 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23033 (let* ((element (org-element-at-point))
23034 (element-end (org-element-property :end element)))
23035 (if (eq (org-element-type element) 'fixed-width)
23036 (progn (goto-char element-end)
23037 (skip-chars-backward " \r\t\n")
23038 (forward-line))
23039 (let ((limit (min end element-end)))
23040 (while (< (point) limit)
23041 (org-move-to-column min-ind t)
23042 (insert ": ")
23043 (forward-line))))))
23045 (org-move-to-column min-ind t)
23046 (insert ": ")
23047 (forward-line)))))))
23048 (set-marker end nil))))
23051 ;;; Comments
23053 ;; Org comments syntax is quite complex. It requires the entire line
23054 ;; to be just a comment. Also, even with the right syntax at the
23055 ;; beginning of line, some some elements (i.e. verse-block or
23056 ;; example-block) don't accept comments. Usual Emacs comment commands
23057 ;; cannot cope with those requirements. Therefore, Org replaces them.
23059 ;; Org still relies on `comment-dwim', but cannot trust
23060 ;; `comment-only-p'. So, `comment-region-function' and
23061 ;; `uncomment-region-function' both point
23062 ;; to`org-comment-or-uncomment-region'. Eventually,
23063 ;; `org-insert-comment' takes care of insertion of comments at the
23064 ;; beginning of line.
23066 ;; `org-setup-comments-handling' install comments related variables
23067 ;; during `org-mode' initialization.
23069 (defun org-setup-comments-handling ()
23070 (interactive)
23071 (org-set-local 'comment-use-syntax nil)
23072 (org-set-local 'comment-start "# ")
23073 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23074 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23075 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23076 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23078 (defun org-insert-comment ()
23079 "Insert an empty comment above current line.
23080 If the line is empty, insert comment at its beginning. When
23081 point is within a source block, comment according to the related
23082 major mode."
23083 (if (let ((element (org-element-at-point)))
23084 (and (eq (org-element-type element) 'src-block)
23085 (< (save-excursion
23086 (goto-char (org-element-property :post-affiliated element))
23087 (line-end-position))
23088 (point))
23089 (> (save-excursion
23090 (goto-char (org-element-property :end element))
23091 (skip-chars-backward " \r\t\n")
23092 (line-beginning-position))
23093 (point))))
23094 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
23095 (beginning-of-line)
23096 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23097 (open-line 1))
23098 (org-indent-line)
23099 (insert "# ")))
23101 (defvar comment-empty-lines) ; From newcomment.el.
23102 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23103 "Comment or uncomment each non-blank line in the region.
23104 Uncomment each non-blank line between BEG and END if it only
23105 contains commented lines. Otherwise, comment them. If region is
23106 strictly within a source block, use appropriate comment syntax."
23107 (if (let ((element (org-element-at-point)))
23108 (and (eq (org-element-type element) 'src-block)
23109 (< (save-excursion
23110 (goto-char (org-element-property :post-affiliated element))
23111 (line-end-position))
23112 beg)
23113 (>= (save-excursion
23114 (goto-char (org-element-property :end element))
23115 (skip-chars-backward " \r\t\n")
23116 (line-beginning-position))
23117 end)))
23118 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
23119 (save-restriction
23120 ;; Restrict region
23121 (narrow-to-region (save-excursion (goto-char beg)
23122 (skip-chars-forward " \r\t\n" end)
23123 (line-beginning-position))
23124 (save-excursion (goto-char end)
23125 (skip-chars-backward " \r\t\n" beg)
23126 (line-end-position)))
23127 (let ((uncommentp
23128 ;; UNCOMMENTP is non-nil when every non blank line between
23129 ;; BEG and END is a comment.
23130 (save-excursion
23131 (goto-char (point-min))
23132 (while (and (not (eobp))
23133 (let ((element (org-element-at-point)))
23134 (and (eq (org-element-type element) 'comment)
23135 (goto-char (min (point-max)
23136 (org-element-property
23137 :end element)))))))
23138 (eobp))))
23139 (if uncommentp
23140 ;; Only blank lines and comments in region: uncomment it.
23141 (save-excursion
23142 (goto-char (point-min))
23143 (while (not (eobp))
23144 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23145 (replace-match "" nil nil nil 1))
23146 (forward-line)))
23147 ;; Comment each line in region.
23148 (let ((min-indent (point-max)))
23149 ;; First find the minimum indentation across all lines.
23150 (save-excursion
23151 (goto-char (point-min))
23152 (while (and (not (eobp)) (not (zerop min-indent)))
23153 (unless (looking-at "[ \t]*$")
23154 (setq min-indent (min min-indent (current-indentation))))
23155 (forward-line)))
23156 ;; Then loop over all lines.
23157 (save-excursion
23158 (goto-char (point-min))
23159 (while (not (eobp))
23160 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23161 ;; Don't get fooled by invisible text (e.g. link path)
23162 ;; when moving to column MIN-INDENT.
23163 (let ((buffer-invisibility-spec nil))
23164 (org-move-to-column min-indent t))
23165 (insert comment-start))
23166 (forward-line)))))))))
23168 (defun org-comment-dwim (arg)
23169 (interactive "*P")
23170 "Call `comment-dwim' within a source edit buffer if needed."
23171 (if (org-in-src-block-p)
23172 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
23173 (call-interactively #'comment-dwim)))
23176 ;;; Planning
23178 ;; This section contains tools to operate on timestamp objects, as
23179 ;; returned by, e.g. `org-element-context'.
23181 (defun org-timestamp-has-time-p (timestamp)
23182 "Non-nil when TIMESTAMP has a time specified."
23183 (org-element-property :hour-start timestamp))
23185 (defun org-timestamp-format (timestamp format &optional end utc)
23186 "Format a TIMESTAMP element into a string.
23188 FORMAT is a format specifier to be passed to
23189 `format-time-string'.
23191 When optional argument END is non-nil, use end of date-range or
23192 time-range, if possible.
23194 When optional argument UTC is non-nil, time will be expressed as
23195 Universal Time."
23196 (format-time-string
23197 format
23198 (apply 'encode-time
23199 (cons 0
23200 (mapcar
23201 (lambda (prop) (or (org-element-property prop timestamp) 0))
23202 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23203 '(:minute-start :hour-start :day-start :month-start
23204 :year-start)))))
23205 utc))
23207 (defun org-timestamp-split-range (timestamp &optional end)
23208 "Extract a timestamp object from a date or time range.
23210 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23211 the end of the range. Otherwise, extract its start.
23213 Return a new timestamp object sharing the same parent as
23214 TIMESTAMP."
23215 (let ((type (org-element-property :type timestamp)))
23216 (if (memq type '(active inactive diary)) timestamp
23217 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23218 ;; Set new type.
23219 (org-element-put-property
23220 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23221 ;; Copy start properties over end properties if END is
23222 ;; non-nil. Otherwise, copy end properties over `start' ones.
23223 (let ((p-alist '((:minute-start . :minute-end)
23224 (:hour-start . :hour-end)
23225 (:day-start . :day-end)
23226 (:month-start . :month-end)
23227 (:year-start . :year-end))))
23228 (dolist (p-cell p-alist)
23229 (org-element-put-property
23230 split-ts
23231 (funcall (if end 'car 'cdr) p-cell)
23232 (org-element-property
23233 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23234 ;; Eventually refresh `:raw-value'.
23235 (org-element-put-property split-ts :raw-value nil)
23236 (org-element-put-property
23237 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23239 (defun org-timestamp-translate (timestamp &optional boundary)
23240 "Apply `org-translate-time' on a TIMESTAMP object.
23241 When optional argument BOUNDARY is non-nil, it is either the
23242 symbol `start' or `end'. In this case, only translate the
23243 starting or ending part of TIMESTAMP if it is a date or time
23244 range. Otherwise, translate both parts."
23245 (if (and (not boundary)
23246 (memq (org-element-property :type timestamp)
23247 '(active-range inactive-range)))
23248 (concat
23249 (org-translate-time
23250 (org-element-property :raw-value
23251 (org-timestamp-split-range timestamp)))
23252 "--"
23253 (org-translate-time
23254 (org-element-property :raw-value
23255 (org-timestamp-split-range timestamp t))))
23256 (org-translate-time
23257 (org-element-property
23258 :raw-value
23259 (if (not boundary) timestamp
23260 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23264 ;;; Other stuff.
23266 (defun org-reftex-citation ()
23267 "Use reftex-citation to insert a citation into the buffer.
23268 This looks for a line like
23270 #+BIBLIOGRAPHY: foo plain option:-d
23272 and derives from it that foo.bib is the bibliography file relevant
23273 for this document. It then installs the necessary environment for RefTeX
23274 to work in this buffer and calls `reftex-citation' to insert a citation
23275 into the buffer.
23277 Export of such citations to both LaTeX and HTML is handled by the contributed
23278 package ox-bibtex by Taru Karttunen."
23279 (interactive)
23280 (let ((reftex-docstruct-symbol 'rds)
23281 (reftex-cite-format "\\cite{%l}")
23282 rds bib)
23283 (save-excursion
23284 (save-restriction
23285 (widen)
23286 (let ((case-fold-search t)
23287 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23288 (if (not (save-excursion
23289 (or (re-search-forward re nil t)
23290 (re-search-backward re nil t))))
23291 (user-error "No bibliography defined in file")
23292 (setq bib (concat (match-string 1) ".bib")
23293 rds (list (list 'bib bib)))))))
23294 (call-interactively 'reftex-citation)))
23296 ;;;; Functions extending outline functionality
23298 (defun org-beginning-of-line (&optional arg)
23299 "Go to the beginning of the current line. If that is invisible, continue
23300 to a visible line beginning. This makes the function of C-a more intuitive.
23301 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23302 first attempt, and only move to after the tags when the cursor is already
23303 beyond the end of the headline."
23304 (interactive "P")
23305 (let ((pos (point))
23306 (special (if (consp org-special-ctrl-a/e)
23307 (car org-special-ctrl-a/e)
23308 org-special-ctrl-a/e))
23309 deactivate-mark refpos)
23310 (if (org-bound-and-true-p visual-line-mode)
23311 (beginning-of-visual-line 1)
23312 (beginning-of-line 1))
23313 (if (and arg (fboundp 'move-beginning-of-line))
23314 (call-interactively 'move-beginning-of-line)
23315 (if (bobp)
23317 (backward-char 1)
23318 (if (org-truely-invisible-p)
23319 (while (and (not (bobp)) (org-truely-invisible-p))
23320 (backward-char 1)
23321 (beginning-of-line 1))
23322 (forward-char 1))))
23323 (when special
23324 (cond
23325 ((and (looking-at org-complex-heading-regexp)
23326 (= (char-after (match-end 1)) ?\ ))
23327 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23328 (point-at-eol)))
23329 (goto-char
23330 (if (eq special t)
23331 (cond ((> pos refpos) refpos)
23332 ((= pos (point)) refpos)
23333 (t (point)))
23334 (cond ((> pos (point)) (point))
23335 ((not (eq last-command this-command)) (point))
23336 (t refpos)))))
23337 ((org-at-item-p)
23338 ;; Being at an item and not looking at an the item means point
23339 ;; was previously moved to beginning of a visual line, which
23340 ;; doesn't contain the item. Therefore, do nothing special,
23341 ;; just stay here.
23342 (when (looking-at org-list-full-item-re)
23343 ;; Set special position at first white space character after
23344 ;; bullet, and check-box, if any.
23345 (let ((after-bullet
23346 (let ((box (match-end 3)))
23347 (if (not box) (match-end 1)
23348 (let ((after (char-after box)))
23349 (if (and after (= after ? )) (1+ box) box))))))
23350 ;; Special case: Move point to special position when
23351 ;; currently after it or at beginning of line.
23352 (if (eq special t)
23353 (when (or (> pos after-bullet) (= (point) pos))
23354 (goto-char after-bullet))
23355 ;; Reversed case: Move point to special position when
23356 ;; point was already at beginning of line and command is
23357 ;; repeated.
23358 (when (and (= (point) pos) (eq last-command this-command))
23359 (goto-char after-bullet))))))))
23360 (org-no-warnings
23361 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23362 (setq disable-point-adjustment
23363 (or (not (invisible-p (point)))
23364 (not (invisible-p (max (point-min) (1- (point))))))))
23366 (defun org-end-of-line (&optional arg)
23367 "Go to the end of the line.
23368 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23369 tags on the first attempt, and only move to after the tags when
23370 the cursor is already beyond the end of the headline."
23371 (interactive "P")
23372 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23373 org-special-ctrl-a/e))
23374 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23375 'end-of-visual-line)
23376 ((fboundp 'move-end-of-line) 'move-end-of-line)
23377 (t 'end-of-line)))
23378 deactivate-mark)
23379 (if (or (not special) arg) (call-interactively move-fun)
23380 (let* ((element (save-excursion (beginning-of-line)
23381 (org-element-at-point)))
23382 (type (org-element-type element)))
23383 (cond
23384 ((memq type '(headline inlinetask))
23385 (let ((pos (point)))
23386 (beginning-of-line 1)
23387 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23388 (if (eq special t)
23389 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23390 (goto-char (match-beginning 1))
23391 (goto-char (match-end 0)))
23392 (if (or (< pos (match-end 0))
23393 (not (eq this-command last-command)))
23394 (goto-char (match-end 0))
23395 (goto-char (match-beginning 1))))
23396 (call-interactively move-fun))))
23397 ((outline-invisible-p (line-end-position))
23398 ;; If element is hidden, `move-end-of-line' would put point
23399 ;; after it. Use `end-of-line' to stay on current line.
23400 (call-interactively 'end-of-line))
23401 (t (call-interactively move-fun)))))
23402 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23403 (setq disable-point-adjustment
23404 (or (not (invisible-p (point)))
23405 (not (invisible-p (max (point-min) (1- (point))))))))
23407 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23408 (define-key org-mode-map "\C-e" 'org-end-of-line)
23410 (defun org-backward-sentence (&optional arg)
23411 "Go to beginning of sentence, or beginning of table field.
23412 This will call `backward-sentence' or `org-table-beginning-of-field',
23413 depending on context."
23414 (interactive "P")
23415 (cond
23416 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23417 (t (call-interactively 'backward-sentence))))
23419 (defun org-forward-sentence (&optional arg)
23420 "Go to end of sentence, or end of table field.
23421 This will call `forward-sentence' or `org-table-end-of-field',
23422 depending on context."
23423 (interactive "P")
23424 (cond
23425 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23426 (t (call-interactively 'forward-sentence))))
23428 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23429 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23431 (defun org-kill-line (&optional arg)
23432 "Kill line, to tags or end of line."
23433 (interactive "P")
23434 (cond
23435 ((or (not org-special-ctrl-k)
23436 (bolp)
23437 (not (org-at-heading-p)))
23438 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23439 org-ctrl-k-protect-subtree)
23440 (if (or (eq org-ctrl-k-protect-subtree 'error)
23441 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23442 (user-error "C-k aborted as it would kill a hidden subtree")))
23443 (call-interactively
23444 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23445 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23446 (kill-region (point) (match-beginning 1))
23447 (org-set-tags nil t))
23448 (t (kill-region (point) (point-at-eol)))))
23450 (define-key org-mode-map "\C-k" 'org-kill-line)
23452 (defun org-yank (&optional arg)
23453 "Yank. If the kill is a subtree, treat it specially.
23454 This command will look at the current kill and check if is a single
23455 subtree, or a series of subtrees[1]. If it passes the test, and if the
23456 cursor is at the beginning of a line or after the stars of a currently
23457 empty headline, then the yank is handled specially. How exactly depends
23458 on the value of the following variables, both set by default.
23460 org-yank-folded-subtrees
23461 When set, the subtree(s) will be folded after insertion, but only
23462 if doing so would now swallow text after the yanked text.
23464 org-yank-adjusted-subtrees
23465 When set, the subtree will be promoted or demoted in order to
23466 fit into the local outline tree structure, which means that the level
23467 will be adjusted so that it becomes the smaller one of the two
23468 *visible* surrounding headings.
23470 Any prefix to this command will cause `yank' to be called directly with
23471 no special treatment. In particular, a simple \\[universal-argument] prefix \
23472 will just
23473 plainly yank the text as it is.
23475 \[1] The test checks if the first non-white line is a heading
23476 and if there are no other headings with fewer stars."
23477 (interactive "P")
23478 (org-yank-generic 'yank arg))
23480 (defun org-yank-generic (command arg)
23481 "Perform some yank-like command.
23483 This function implements the behavior described in the `org-yank'
23484 documentation. However, it has been generalized to work for any
23485 interactive command with similar behavior."
23487 ;; pretend to be command COMMAND
23488 (setq this-command command)
23490 (if arg
23491 (call-interactively command)
23493 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23494 (and (org-kill-is-subtree-p)
23495 (or (bolp)
23496 (and (looking-at "[ \t]*$")
23497 (string-match
23498 "\\`\\*+\\'"
23499 (buffer-substring (point-at-bol) (point)))))))
23500 swallowp)
23501 (cond
23502 ((and subtreep org-yank-folded-subtrees)
23503 (let ((beg (point))
23504 end)
23505 (if (and subtreep org-yank-adjusted-subtrees)
23506 (org-paste-subtree nil nil 'for-yank)
23507 (call-interactively command))
23509 (setq end (point))
23510 (goto-char beg)
23511 (when (and (bolp) subtreep
23512 (not (setq swallowp
23513 (org-yank-folding-would-swallow-text beg end))))
23514 (org-with-limited-levels
23515 (or (looking-at org-outline-regexp)
23516 (re-search-forward org-outline-regexp-bol end t))
23517 (while (and (< (point) end) (looking-at org-outline-regexp))
23518 (hide-subtree)
23519 (org-cycle-show-empty-lines 'folded)
23520 (condition-case nil
23521 (outline-forward-same-level 1)
23522 (error (goto-char end))))))
23523 (when swallowp
23524 (message
23525 "Inserted text not folded because that would swallow text"))
23527 (goto-char end)
23528 (skip-chars-forward " \t\n\r")
23529 (beginning-of-line 1)
23530 (push-mark beg 'nomsg)))
23531 ((and subtreep org-yank-adjusted-subtrees)
23532 (let ((beg (point-at-bol)))
23533 (org-paste-subtree nil nil 'for-yank)
23534 (push-mark beg 'nomsg)))
23536 (call-interactively command))))))
23538 (defun org-yank-folding-would-swallow-text (beg end)
23539 "Would hide-subtree at BEG swallow any text after END?"
23540 (let (level)
23541 (org-with-limited-levels
23542 (save-excursion
23543 (goto-char beg)
23544 (when (or (looking-at org-outline-regexp)
23545 (re-search-forward org-outline-regexp-bol end t))
23546 (setq level (org-outline-level)))
23547 (goto-char end)
23548 (skip-chars-forward " \t\r\n\v\f")
23549 (if (or (eobp)
23550 (and (bolp) (looking-at org-outline-regexp)
23551 (<= (org-outline-level) level)))
23552 nil ; Nothing would be swallowed
23553 t))))) ; something would swallow
23555 (define-key org-mode-map "\C-y" 'org-yank)
23557 (defun org-truely-invisible-p ()
23558 "Check if point is at a character currently not visible.
23559 This version does not only check the character property, but also
23560 `visible-mode'."
23561 ;; Early versions of noutline don't have `outline-invisible-p'.
23562 (if (org-bound-and-true-p visible-mode)
23564 (outline-invisible-p)))
23566 (defun org-invisible-p2 ()
23567 "Check if point is at a character currently not visible."
23568 (save-excursion
23569 (if (and (eolp) (not (bobp))) (backward-char 1))
23570 ;; Early versions of noutline don't have `outline-invisible-p'.
23571 (outline-invisible-p)))
23573 (defun org-back-to-heading (&optional invisible-ok)
23574 "Call `outline-back-to-heading', but provide a better error message."
23575 (condition-case nil
23576 (outline-back-to-heading invisible-ok)
23577 (error (error "Before first headline at position %d in buffer %s"
23578 (point) (current-buffer)))))
23580 (defun org-before-first-heading-p ()
23581 "Before first heading?"
23582 (save-excursion
23583 (end-of-line)
23584 (null (re-search-backward org-outline-regexp-bol nil t))))
23586 (defun org-at-heading-p (&optional ignored)
23587 (outline-on-heading-p t))
23588 ;; Compatibility alias with Org versions < 7.8.03
23589 (defalias 'org-on-heading-p 'org-at-heading-p)
23591 (defun org-in-commented-heading-p (&optional no-inheritance)
23592 "Non-nil if point is under a commented heading.
23593 This function also checks ancestors of the current headline,
23594 unless optional argument NO-INHERITANCE is non-nil."
23595 (cond
23596 ((org-before-first-heading-p) nil)
23597 ((let ((headline (nth 4 (org-heading-components))))
23598 (and headline
23599 (let ((case-fold-search nil))
23600 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23601 headline)))))
23602 (no-inheritance nil)
23604 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23606 (defun org-at-comment-p nil
23607 "Is cursor in a commented line?"
23608 (save-excursion
23609 (save-match-data
23610 (beginning-of-line)
23611 (looking-at "^[ \t]*# "))))
23613 (defun org-at-drawer-p nil
23614 "Is cursor at a drawer keyword?"
23615 (save-excursion
23616 (move-beginning-of-line 1)
23617 (looking-at org-drawer-regexp)))
23619 (defun org-at-block-p nil
23620 "Is cursor at a block keyword?"
23621 (save-excursion
23622 (move-beginning-of-line 1)
23623 (looking-at org-block-regexp)))
23625 (defun org-point-at-end-of-empty-headline ()
23626 "If point is at the end of an empty headline, return t, else nil.
23627 If the heading only contains a TODO keyword, it is still still considered
23628 empty."
23629 (and (looking-at "[ \t]*$")
23630 (when org-todo-line-regexp
23631 (save-excursion
23632 (beginning-of-line 1)
23633 (let ((case-fold-search nil))
23634 (looking-at org-todo-line-regexp)
23635 (string= (match-string 3) ""))))))
23637 (defun org-at-heading-or-item-p ()
23638 (or (org-at-heading-p) (org-at-item-p)))
23640 (defun org-at-target-p ()
23641 (or (org-in-regexp org-radio-target-regexp)
23642 (org-in-regexp org-target-regexp)))
23643 ;; Compatibility alias with Org versions < 7.8.03
23644 (defalias 'org-on-target-p 'org-at-target-p)
23646 (defun org-up-heading-all (arg)
23647 "Move to the heading line of which the present line is a subheading.
23648 This function considers both visible and invisible heading lines.
23649 With argument, move up ARG levels."
23650 (if (fboundp 'outline-up-heading-all)
23651 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23652 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23654 (defun org-up-heading-safe ()
23655 "Move to the heading line of which the present line is a subheading.
23656 This version will not throw an error. It will return the level of the
23657 headline found, or nil if no higher level is found.
23659 Also, this function will be a lot faster than `outline-up-heading',
23660 because it relies on stars being the outline starters. This can really
23661 make a significant difference in outlines with very many siblings."
23662 (let (start-level re)
23663 (org-back-to-heading t)
23664 (setq start-level (funcall outline-level))
23665 (if (equal start-level 1)
23667 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23668 (if (re-search-backward re nil t)
23669 (funcall outline-level)))))
23671 (defun org-first-sibling-p ()
23672 "Is this heading the first child of its parents?"
23673 (interactive)
23674 (let ((re org-outline-regexp-bol)
23675 level l)
23676 (unless (org-at-heading-p t)
23677 (user-error "Not at a heading"))
23678 (setq level (funcall outline-level))
23679 (save-excursion
23680 (if (not (re-search-backward re nil t))
23682 (setq l (funcall outline-level))
23683 (< l level)))))
23685 (defun org-goto-sibling (&optional previous)
23686 "Goto the next sibling, even if it is invisible.
23687 When PREVIOUS is set, go to the previous sibling instead. Returns t
23688 when a sibling was found. When none is found, return nil and don't
23689 move point."
23690 (let ((fun (if previous 're-search-backward 're-search-forward))
23691 (pos (point))
23692 (re org-outline-regexp-bol)
23693 level l)
23694 (when (condition-case nil (org-back-to-heading t) (error nil))
23695 (setq level (funcall outline-level))
23696 (catch 'exit
23697 (or previous (forward-char 1))
23698 (while (funcall fun re nil t)
23699 (setq l (funcall outline-level))
23700 (when (< l level) (goto-char pos) (throw 'exit nil))
23701 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23702 (goto-char pos)
23703 nil))))
23705 (defun org-show-siblings ()
23706 "Show all siblings of the current headline."
23707 (save-excursion
23708 (while (org-goto-sibling) (org-flag-heading nil)))
23709 (save-excursion
23710 (while (org-goto-sibling 'previous)
23711 (org-flag-heading nil))))
23713 (defun org-goto-first-child ()
23714 "Goto the first child, even if it is invisible.
23715 Return t when a child was found. Otherwise don't move point and
23716 return nil."
23717 (let (level (pos (point)) (re org-outline-regexp-bol))
23718 (when (condition-case nil (org-back-to-heading t) (error nil))
23719 (setq level (outline-level))
23720 (forward-char 1)
23721 (if (and (re-search-forward re nil t) (> (outline-level) level))
23722 (progn (goto-char (match-beginning 0)) t)
23723 (goto-char pos) nil))))
23725 (defun org-show-hidden-entry ()
23726 "Show an entry where even the heading is hidden."
23727 (save-excursion
23728 (org-show-entry)))
23730 (defun org-flag-heading (flag &optional entry)
23731 "Flag the current heading. FLAG non-nil means make invisible.
23732 When ENTRY is non-nil, show the entire entry."
23733 (save-excursion
23734 (org-back-to-heading t)
23735 ;; Check if we should show the entire entry
23736 (if entry
23737 (progn
23738 (org-show-entry)
23739 (save-excursion
23740 (and (outline-next-heading)
23741 (org-flag-heading nil))))
23742 (outline-flag-region (max (point-min) (1- (point)))
23743 (save-excursion (outline-end-of-heading) (point))
23744 flag))))
23746 (defun org-get-next-sibling ()
23747 "Move to next heading of the same level, and return point.
23748 If there is no such heading, return nil.
23749 This is like outline-next-sibling, but invisible headings are ok."
23750 (let ((level (funcall outline-level)))
23751 (outline-next-heading)
23752 (while (and (not (eobp)) (> (funcall outline-level) level))
23753 (outline-next-heading))
23754 (if (or (eobp) (< (funcall outline-level) level))
23756 (point))))
23758 (defun org-get-last-sibling ()
23759 "Move to previous heading of the same level, and return point.
23760 If there is no such heading, return nil."
23761 (let ((opoint (point))
23762 (level (funcall outline-level)))
23763 (outline-previous-heading)
23764 (when (and (/= (point) opoint) (outline-on-heading-p t))
23765 (while (and (> (funcall outline-level) level)
23766 (not (bobp)))
23767 (outline-previous-heading))
23768 (if (< (funcall outline-level) level)
23770 (point)))))
23772 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23773 "Goto to the end of a subtree."
23774 ;; This contains an exact copy of the original function, but it uses
23775 ;; `org-back-to-heading', to make it work also in invisible
23776 ;; trees. And is uses an invisible-ok argument.
23777 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23778 ;; Furthermore, when used inside Org, finding the end of a large subtree
23779 ;; with many children and grandchildren etc, this can be much faster
23780 ;; than the outline version.
23781 (org-back-to-heading invisible-ok)
23782 (let ((first t)
23783 (level (funcall outline-level)))
23784 (if (and (derived-mode-p 'org-mode) (< level 1000))
23785 ;; A true heading (not a plain list item), in Org-mode
23786 ;; This means we can easily find the end by looking
23787 ;; only for the right number of stars. Using a regexp to do
23788 ;; this is so much faster than using a Lisp loop.
23789 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23790 (forward-char 1)
23791 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23792 ;; something else, do it the slow way
23793 (while (and (not (eobp))
23794 (or first (> (funcall outline-level) level)))
23795 (setq first nil)
23796 (outline-next-heading)))
23797 (unless to-heading
23798 (if (memq (preceding-char) '(?\n ?\^M))
23799 (progn
23800 ;; Go to end of line before heading
23801 (forward-char -1)
23802 (if (memq (preceding-char) '(?\n ?\^M))
23803 ;; leave blank line before heading
23804 (forward-char -1))))))
23805 (point))
23807 (defun org-end-of-meta-data-and-drawers ()
23808 "Jump to the first text after meta data and drawers in the current entry.
23809 This will move over empty lines, lines with planning time stamps,
23810 clocking lines, and drawers."
23811 (org-back-to-heading t)
23812 (let ((end (save-excursion (outline-next-heading) (point)))
23813 (re (concat "\\(" org-drawer-regexp "\\)"
23814 "\\|" "[ \t]*" org-keyword-time-regexp)))
23815 (forward-line 1)
23816 (while (re-search-forward re end t)
23817 (if (not (match-end 1))
23818 ;; empty or planning line
23819 (forward-line 1)
23820 ;; a drawer, find the end
23821 (re-search-forward "^[ \t]*:END:" end 'move)
23822 (forward-line 1)))
23823 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23824 (point)))
23826 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23827 "Move forward to the ARG'th subheading at same level as this one.
23828 Stop at the first and last subheadings of a superior heading.
23829 Normally this only looks at visible headings, but when INVISIBLE-OK is
23830 non-nil it will also look at invisible ones."
23831 (interactive "p")
23832 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23833 (if (and arg (< arg 0))
23834 (goto-char (point-min))
23835 (outline-next-heading))
23836 (org-at-heading-p)
23837 (let ((level (- (match-end 0) (match-beginning 0) 1))
23838 (f (if (and arg (< arg 0))
23839 're-search-backward
23840 're-search-forward))
23841 (count (if arg (abs arg) 1))
23842 (result (point)))
23843 (while (and (prog1 (> count 0)
23844 (forward-char (if (and arg (< arg 0)) -1 1)))
23845 (funcall f org-outline-regexp-bol nil 'move))
23846 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23847 (cond ((< l level) (setq count 0))
23848 ((and (= l level)
23849 (or invisible-ok
23850 (progn
23851 (goto-char (line-beginning-position))
23852 (not (outline-invisible-p)))))
23853 (setq count (1- count))
23854 (when (eq l level)
23855 (setq result (point)))))))
23856 (goto-char result))
23857 (beginning-of-line 1)))
23859 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23860 "Move backward to the ARG'th subheading at same level as this one.
23861 Stop at the first and last subheadings of a superior heading."
23862 (interactive "p")
23863 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23865 (defun org-next-block (arg &optional backward block-regexp)
23866 "Jump to the next block.
23867 With a prefix argument ARG, jump forward ARG many source blocks.
23868 When BACKWARD is non-nil, jump to the previous block.
23869 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23870 (interactive "p")
23871 (let ((re (or block-regexp org-block-regexp))
23872 (re-search-fn (or (and backward 're-search-backward)
23873 're-search-forward)))
23874 (if (looking-at re) (forward-char 1))
23875 (condition-case nil
23876 (funcall re-search-fn re nil nil arg)
23877 (error (user-error "No %s code blocks"
23878 (if backward "previous" "further" ))))
23879 (goto-char (match-beginning 0)) (org-show-context)))
23881 (defun org-previous-block (arg &optional block-regexp)
23882 "Jump to the previous block.
23883 With a prefix argument ARG, jump backward ARG many source blocks.
23884 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23885 (interactive "p")
23886 (org-next-block arg t block-regexp))
23888 (defun org-forward-paragraph ()
23889 "Move forward to beginning of next paragraph or equivalent.
23891 The function moves point to the beginning of the next visible
23892 structural element, which can be a paragraph, a table, a list
23893 item, etc. It also provides some special moves for convenience:
23895 - On an affiliated keyword, jump to the beginning of the
23896 relative element.
23897 - On an item or a footnote definition, move to the second
23898 element inside, if any.
23899 - On a table or a property drawer, jump after it.
23900 - On a verse or source block, stop after blank lines."
23901 (interactive)
23902 (when (eobp) (user-error "Cannot move further down"))
23903 (let* ((deactivate-mark nil)
23904 (element (org-element-at-point))
23905 (type (org-element-type element))
23906 (post-affiliated (org-element-property :post-affiliated element))
23907 (contents-begin (org-element-property :contents-begin element))
23908 (contents-end (org-element-property :contents-end element))
23909 (end (let ((end (org-element-property :end element)) (parent element))
23910 (while (and (setq parent (org-element-property :parent parent))
23911 (= (org-element-property :contents-end parent) end))
23912 (setq end (org-element-property :end parent)))
23913 end)))
23914 (cond ((not element)
23915 (skip-chars-forward " \r\t\n")
23916 (or (eobp) (beginning-of-line)))
23917 ;; On affiliated keywords, move to element's beginning.
23918 ((and post-affiliated (< (point) post-affiliated))
23919 (goto-char post-affiliated))
23920 ;; At a table row, move to the end of the table. Similarly,
23921 ;; at a node property, move to the end of the property
23922 ;; drawer.
23923 ((memq type '(node-property table-row))
23924 (goto-char (org-element-property
23925 :end (org-element-property :parent element))))
23926 ((memq type '(property-drawer table)) (goto-char end))
23927 ;; Consider blank lines as separators in verse and source
23928 ;; blocks to ease editing.
23929 ((memq type '(src-block verse-block))
23930 (when (eq type 'src-block)
23931 (setq contents-end
23932 (save-excursion (goto-char end)
23933 (skip-chars-backward " \r\t\n")
23934 (line-beginning-position))))
23935 (beginning-of-line)
23936 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23937 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23938 (goto-char end)
23939 (skip-chars-forward " \r\t\n")
23940 (if (= (point) contents-end) (goto-char end)
23941 (beginning-of-line))))
23942 ;; With no contents, just skip element.
23943 ((not contents-begin) (goto-char end))
23944 ;; If contents are invisible, skip the element altogether.
23945 ((outline-invisible-p (line-end-position))
23946 (case type
23947 (headline
23948 (org-with-limited-levels (outline-next-visible-heading 1)))
23949 ;; At a plain list, make sure we move to the next item
23950 ;; instead of skipping the whole list.
23951 (plain-list (forward-char)
23952 (org-forward-paragraph))
23953 (otherwise (goto-char end))))
23954 ((>= (point) contents-end) (goto-char end))
23955 ((>= (point) contents-begin)
23956 ;; This can only happen on paragraphs and plain lists.
23957 (case type
23958 (paragraph (goto-char end))
23959 ;; At a plain list, try to move to second element in
23960 ;; first item, if possible.
23961 (plain-list (end-of-line)
23962 (org-forward-paragraph))))
23963 ;; When contents start on the middle of a line (e.g. in
23964 ;; items and footnote definitions), try to reach first
23965 ;; element starting after current line.
23966 ((> (line-end-position) contents-begin)
23967 (end-of-line)
23968 (org-forward-paragraph))
23969 (t (goto-char contents-begin)))))
23971 (defun org-backward-paragraph ()
23972 "Move backward to start of previous paragraph or equivalent.
23974 The function moves point to the beginning of the current
23975 structural element, which can be a paragraph, a table, a list
23976 item, etc., or to the beginning of the previous visible one if
23977 point is already there. It also provides some special moves for
23978 convenience:
23980 - On an affiliated keyword, jump to the first one.
23981 - On a table or a property drawer, move to its beginning.
23982 - On a verse or source block, stop before blank lines."
23983 (interactive)
23984 (when (bobp) (user-error "Cannot move further up"))
23985 (let* ((deactivate-mark nil)
23986 (element (org-element-at-point))
23987 (type (org-element-type element))
23988 (contents-begin (org-element-property :contents-begin element))
23989 (contents-end (org-element-property :contents-end element))
23990 (post-affiliated (org-element-property :post-affiliated element))
23991 (begin (org-element-property :begin element)))
23992 (cond
23993 ((not element) (goto-char (point-min)))
23994 ((= (point) begin)
23995 (backward-char)
23996 (org-backward-paragraph))
23997 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23998 ((memq type '(node-property table-row))
23999 (goto-char (org-element-property
24000 :post-affiliated (org-element-property :parent element))))
24001 ((memq type '(property-drawer table)) (goto-char begin))
24002 ((memq type '(src-block verse-block))
24003 (when (eq type 'src-block)
24004 (setq contents-begin
24005 (save-excursion (goto-char begin) (forward-line) (point))))
24006 (if (= (point) contents-begin) (goto-char post-affiliated)
24007 ;; Inside a verse block, see blank lines as paragraph
24008 ;; separators.
24009 (let ((origin (point)))
24010 (skip-chars-backward " \r\t\n" contents-begin)
24011 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24012 (skip-chars-forward " \r\t\n" origin)
24013 (if (= (point) origin) (goto-char contents-begin)
24014 (beginning-of-line))))))
24015 ((not contents-begin) (goto-char (or post-affiliated begin)))
24016 ((eq type 'paragraph)
24017 (goto-char contents-begin)
24018 ;; When at first paragraph in an item or a footnote definition,
24019 ;; move directly to beginning of line.
24020 (let ((parent-contents
24021 (org-element-property
24022 :contents-begin (org-element-property :parent element))))
24023 (when (and parent-contents (= parent-contents contents-begin))
24024 (beginning-of-line))))
24025 ;; At the end of a greater element, move to the beginning of the
24026 ;; last element within.
24027 ((>= (point) contents-end)
24028 (goto-char (1- contents-end))
24029 (org-backward-paragraph))
24030 (t (goto-char (or post-affiliated begin))))
24031 ;; Ensure we never leave point invisible.
24032 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24034 (defun org-forward-element ()
24035 "Move forward by one element.
24036 Move to the next element at the same level, when possible."
24037 (interactive)
24038 (cond ((eobp) (user-error "Cannot move further down"))
24039 ((org-with-limited-levels (org-at-heading-p))
24040 (let ((origin (point)))
24041 (goto-char (org-end-of-subtree nil t))
24042 (unless (org-with-limited-levels (org-at-heading-p))
24043 (goto-char origin)
24044 (user-error "Cannot move further down"))))
24046 (let* ((elem (org-element-at-point))
24047 (end (org-element-property :end elem))
24048 (parent (org-element-property :parent elem)))
24049 (cond ((and parent (= (org-element-property :contents-end parent) end))
24050 (goto-char (org-element-property :end parent)))
24051 ((integer-or-marker-p end) (goto-char end))
24052 (t (message "No element at point")))))))
24054 (defun org-backward-element ()
24055 "Move backward by one element.
24056 Move to the previous element at the same level, when possible."
24057 (interactive)
24058 (cond ((bobp) (user-error "Cannot move further up"))
24059 ((org-with-limited-levels (org-at-heading-p))
24060 ;; At a headline, move to the previous one, if any, or stay
24061 ;; here.
24062 (let ((origin (point)))
24063 (org-with-limited-levels (org-backward-heading-same-level 1))
24064 ;; When current headline has no sibling above, move to its
24065 ;; parent.
24066 (when (= (point) origin)
24067 (or (org-with-limited-levels (org-up-heading-safe))
24068 (progn (goto-char origin)
24069 (user-error "Cannot move further up"))))))
24071 (let* ((elem (org-element-at-point))
24072 (beg (org-element-property :begin elem)))
24073 (cond
24074 ;; Move to beginning of current element if point isn't
24075 ;; there already.
24076 ((null beg) (message "No element at point"))
24077 ((/= (point) beg) (goto-char beg))
24078 (t (goto-char beg)
24079 (skip-chars-backward " \r\t\n")
24080 (unless (bobp)
24081 (let ((prev (org-element-at-point)))
24082 (goto-char (org-element-property :begin prev))
24083 (while (and (setq prev (org-element-property :parent prev))
24084 (<= (org-element-property :end prev) beg))
24085 (goto-char (org-element-property :begin prev)))))))))))
24087 (defun org-up-element ()
24088 "Move to upper element."
24089 (interactive)
24090 (if (org-with-limited-levels (org-at-heading-p))
24091 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24092 (let* ((elem (org-element-at-point))
24093 (parent (org-element-property :parent elem)))
24094 (if parent (goto-char (org-element-property :begin parent))
24095 (if (org-with-limited-levels (org-before-first-heading-p))
24096 (user-error "No surrounding element")
24097 (org-with-limited-levels (org-back-to-heading)))))))
24099 (defvar org-element-greater-elements)
24100 (defun org-down-element ()
24101 "Move to inner element."
24102 (interactive)
24103 (let ((element (org-element-at-point)))
24104 (cond
24105 ((memq (org-element-type element) '(plain-list table))
24106 (goto-char (org-element-property :contents-begin element))
24107 (forward-char))
24108 ((memq (org-element-type element) org-element-greater-elements)
24109 ;; If contents are hidden, first disclose them.
24110 (when (outline-invisible-p (line-end-position)) (org-cycle))
24111 (goto-char (or (org-element-property :contents-begin element)
24112 (user-error "No content for this element"))))
24113 (t (user-error "No inner element")))))
24115 (defun org-drag-element-backward ()
24116 "Move backward element at point."
24117 (interactive)
24118 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24119 (let* ((elem (org-element-at-point))
24120 (prev-elem
24121 (save-excursion
24122 (goto-char (org-element-property :begin elem))
24123 (skip-chars-backward " \r\t\n")
24124 (unless (bobp)
24125 (let* ((beg (org-element-property :begin elem))
24126 (prev (org-element-at-point))
24127 (up prev))
24128 (while (and (setq up (org-element-property :parent up))
24129 (<= (org-element-property :end prev) beg))
24130 (setq prev up))
24131 prev)))))
24132 ;; Error out if no previous element or previous element is
24133 ;; a parent of the current one.
24134 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24135 (user-error "Cannot drag element backward")
24136 (let ((pos (point)))
24137 (org-element-swap-A-B prev-elem elem)
24138 (goto-char (+ (org-element-property :begin prev-elem)
24139 (- pos (org-element-property :begin elem)))))))))
24141 (defun org-drag-element-forward ()
24142 "Move forward element at point."
24143 (interactive)
24144 (let* ((pos (point))
24145 (elem (org-element-at-point)))
24146 (when (= (point-max) (org-element-property :end elem))
24147 (user-error "Cannot drag element forward"))
24148 (goto-char (org-element-property :end elem))
24149 (let ((next-elem (org-element-at-point)))
24150 (when (or (org-element-nested-p elem next-elem)
24151 (and (eq (org-element-type next-elem) 'headline)
24152 (not (eq (org-element-type elem) 'headline))))
24153 (goto-char pos)
24154 (user-error "Cannot drag element forward"))
24155 ;; Compute new position of point: it's shifted by NEXT-ELEM
24156 ;; body's length (without final blanks) and by the length of
24157 ;; blanks between ELEM and NEXT-ELEM.
24158 (let ((size-next (- (save-excursion
24159 (goto-char (org-element-property :end next-elem))
24160 (skip-chars-backward " \r\t\n")
24161 (forward-line)
24162 ;; Small correction if buffer doesn't end
24163 ;; with a newline character.
24164 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24165 (org-element-property :begin next-elem)))
24166 (size-blank (- (org-element-property :end elem)
24167 (save-excursion
24168 (goto-char (org-element-property :end elem))
24169 (skip-chars-backward " \r\t\n")
24170 (forward-line)
24171 (point)))))
24172 (org-element-swap-A-B elem next-elem)
24173 (goto-char (+ pos size-next size-blank))))))
24175 (defun org-drag-line-forward (arg)
24176 "Drag the line at point ARG lines forward."
24177 (interactive "p")
24178 (dotimes (n (abs arg))
24179 (let ((c (current-column)))
24180 (if (< 0 arg)
24181 (progn
24182 (beginning-of-line 2)
24183 (transpose-lines 1)
24184 (beginning-of-line 0))
24185 (transpose-lines 1)
24186 (beginning-of-line -1))
24187 (org-move-to-column c))))
24189 (defun org-drag-line-backward (arg)
24190 "Drag the line at point ARG lines backward."
24191 (interactive "p")
24192 (org-drag-line-forward (- arg)))
24194 (defun org-mark-element ()
24195 "Put point at beginning of this element, mark at end.
24197 Interactively, if this command is repeated or (in Transient Mark
24198 mode) if the mark is active, it marks the next element after the
24199 ones already marked."
24200 (interactive)
24201 (let (deactivate-mark)
24202 (if (and (org-called-interactively-p 'any)
24203 (or (and (eq last-command this-command) (mark t))
24204 (and transient-mark-mode mark-active)))
24205 (set-mark
24206 (save-excursion
24207 (goto-char (mark))
24208 (goto-char (org-element-property :end (org-element-at-point)))))
24209 (let ((element (org-element-at-point)))
24210 (end-of-line)
24211 (push-mark (org-element-property :end element) t t)
24212 (goto-char (org-element-property :begin element))))))
24214 (defun org-narrow-to-element ()
24215 "Narrow buffer to current element."
24216 (interactive)
24217 (let ((elem (org-element-at-point)))
24218 (cond
24219 ((eq (car elem) 'headline)
24220 (narrow-to-region
24221 (org-element-property :begin elem)
24222 (org-element-property :end elem)))
24223 ((memq (car elem) org-element-greater-elements)
24224 (narrow-to-region
24225 (org-element-property :contents-begin elem)
24226 (org-element-property :contents-end elem)))
24228 (narrow-to-region
24229 (org-element-property :begin elem)
24230 (org-element-property :end elem))))))
24232 (defun org-transpose-element ()
24233 "Transpose current and previous elements, keeping blank lines between.
24234 Point is moved after both elements."
24235 (interactive)
24236 (org-skip-whitespace)
24237 (let ((end (org-element-property :end (org-element-at-point))))
24238 (org-drag-element-backward)
24239 (goto-char end)))
24241 (defun org-unindent-buffer ()
24242 "Un-indent the visible part of the buffer.
24243 Relative indentation (between items, inside blocks, etc.) isn't
24244 modified."
24245 (interactive)
24246 (unless (eq major-mode 'org-mode)
24247 (user-error "Cannot un-indent a buffer not in Org mode"))
24248 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24249 unindent-tree ; For byte-compiler.
24250 (unindent-tree
24251 (function
24252 (lambda (contents)
24253 (mapc
24254 (lambda (element)
24255 (if (memq (org-element-type element) '(headline section))
24256 (funcall unindent-tree (org-element-contents element))
24257 (save-excursion
24258 (save-restriction
24259 (narrow-to-region
24260 (org-element-property :begin element)
24261 (org-element-property :end element))
24262 (org-do-remove-indentation)))))
24263 (reverse contents))))))
24264 (funcall unindent-tree (org-element-contents parse-tree))))
24266 (defun org-show-subtree ()
24267 "Show everything after this heading at deeper levels."
24268 (interactive)
24269 (outline-flag-region
24270 (point)
24271 (save-excursion
24272 (org-end-of-subtree t t))
24273 nil))
24275 (defun org-show-entry ()
24276 "Show the body directly following this heading.
24277 Show the heading too, if it is currently invisible."
24278 (interactive)
24279 (save-excursion
24280 (condition-case nil
24281 (progn
24282 (org-back-to-heading t)
24283 (outline-flag-region
24284 (max (point-min) (1- (point)))
24285 (save-excursion
24286 (if (re-search-forward
24287 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24288 (match-beginning 1)
24289 (point-max)))
24290 nil)
24291 (org-cycle-hide-drawers 'children))
24292 (error nil))))
24294 (defun org-make-options-regexp (kwds &optional extra)
24295 "Make a regular expression for keyword lines."
24296 (concat
24297 "^[ \t]*#\\+\\("
24298 (mapconcat 'regexp-quote kwds "\\|")
24299 (if extra (concat "\\|" extra))
24300 "\\):[ \t]*\\(.*\\)"))
24302 ;; Make isearch reveal the necessary context
24303 (defun org-isearch-end ()
24304 "Reveal context after isearch exits."
24305 (when isearch-success ; only if search was successful
24306 (if (featurep 'xemacs)
24307 ;; Under XEmacs, the hook is run in the correct place,
24308 ;; we directly show the context.
24309 (org-show-context 'isearch)
24310 ;; In Emacs the hook runs *before* restoring the overlays.
24311 ;; So we have to use a one-time post-command-hook to do this.
24312 ;; (Emacs 22 has a special variable, see function `org-mode')
24313 (unless (and (boundp 'isearch-mode-end-hook-quit)
24314 isearch-mode-end-hook-quit)
24315 ;; Only when the isearch was not quitted.
24316 (org-add-hook 'post-command-hook 'org-isearch-post-command
24317 'append 'local)))
24318 (org-fix-ellipsis-at-bol)))
24320 (defun org-isearch-post-command ()
24321 "Remove self from hook, and show context."
24322 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24323 (org-show-context 'isearch))
24326 ;;;; Integration with and fixes for other packages
24328 ;;; Imenu support
24330 (defvar org-imenu-markers nil
24331 "All markers currently used by Imenu.")
24332 (make-variable-buffer-local 'org-imenu-markers)
24334 (defun org-imenu-new-marker (&optional pos)
24335 "Return a new marker for use by Imenu, and remember the marker."
24336 (let ((m (make-marker)))
24337 (move-marker m (or pos (point)))
24338 (push m org-imenu-markers)
24341 (defun org-imenu-get-tree ()
24342 "Produce the index for Imenu."
24343 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24344 (setq org-imenu-markers nil)
24345 (let* ((n org-imenu-depth)
24346 (re (concat "^" (org-get-limited-outline-regexp)))
24347 (subs (make-vector (1+ n) nil))
24348 (last-level 0)
24349 m level head0 head)
24350 (save-excursion
24351 (save-restriction
24352 (widen)
24353 (goto-char (point-max))
24354 (while (re-search-backward re nil t)
24355 (setq level (org-reduced-level (funcall outline-level)))
24356 (when (and (<= level n)
24357 (looking-at org-complex-heading-regexp)
24358 (setq head0 (org-match-string-no-properties 4)))
24359 (setq head (org-link-display-format head0)
24360 m (org-imenu-new-marker))
24361 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24362 (if (>= level last-level)
24363 (push (cons head m) (aref subs level))
24364 (push (cons head (aref subs (1+ level))) (aref subs level))
24365 (loop for i from (1+ level) to n do (aset subs i nil)))
24366 (setq last-level level)))))
24367 (aref subs 1)))
24369 (eval-after-load "imenu"
24370 '(progn
24371 (add-hook 'imenu-after-jump-hook
24372 (lambda ()
24373 (if (derived-mode-p 'org-mode)
24374 (org-show-context 'org-goto))))))
24376 (defun org-link-display-format (link)
24377 "Replace a link with its the description.
24378 If there is no description, use the link target."
24379 (save-match-data
24380 (if (string-match org-bracket-link-analytic-regexp link)
24381 (replace-match (if (match-end 5)
24382 (match-string 5 link)
24383 (concat (match-string 1 link)
24384 (match-string 3 link)))
24385 nil t link)
24386 link)))
24388 (defun org-toggle-link-display ()
24389 "Toggle the literal or descriptive display of links."
24390 (interactive)
24391 (if org-descriptive-links
24392 (progn (org-remove-from-invisibility-spec '(org-link))
24393 (org-restart-font-lock)
24394 (setq org-descriptive-links nil))
24395 (progn (add-to-invisibility-spec '(org-link))
24396 (org-restart-font-lock)
24397 (setq org-descriptive-links t))))
24399 ;; Speedbar support
24401 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24402 "Overlay marking the agenda restriction line in speedbar.")
24403 (overlay-put org-speedbar-restriction-lock-overlay
24404 'face 'org-agenda-restriction-lock)
24405 (overlay-put org-speedbar-restriction-lock-overlay
24406 'help-echo "Agendas are currently limited to this item.")
24407 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24409 (defun org-speedbar-set-agenda-restriction ()
24410 "Restrict future agenda commands to the location at point in speedbar.
24411 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24412 (interactive)
24413 (require 'org-agenda)
24414 (let (p m tp np dir txt)
24415 (cond
24416 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24417 'org-imenu t))
24418 (setq m (get-text-property p 'org-imenu-marker))
24419 (with-current-buffer (marker-buffer m)
24420 (goto-char m)
24421 (org-agenda-set-restriction-lock 'subtree)))
24422 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24423 'speedbar-function 'speedbar-find-file))
24424 (setq tp (previous-single-property-change
24425 (1+ p) 'speedbar-function)
24426 np (next-single-property-change
24427 tp 'speedbar-function)
24428 dir (speedbar-line-directory)
24429 txt (buffer-substring-no-properties (or tp (point-min))
24430 (or np (point-max))))
24431 (with-current-buffer (find-file-noselect
24432 (let ((default-directory dir))
24433 (expand-file-name txt)))
24434 (unless (derived-mode-p 'org-mode)
24435 (user-error "Cannot restrict to non-Org-mode file"))
24436 (org-agenda-set-restriction-lock 'file)))
24437 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24438 (move-overlay org-speedbar-restriction-lock-overlay
24439 (point-at-bol) (point-at-eol))
24440 (setq current-prefix-arg nil)
24441 (org-agenda-maybe-redo)))
24443 (defvar speedbar-file-key-map)
24444 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24445 (eval-after-load "speedbar"
24446 '(progn
24447 (speedbar-add-supported-extension ".org")
24448 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24449 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24450 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24451 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24452 (add-hook 'speedbar-visiting-tag-hook
24453 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24455 ;;; Fixes and Hacks for problems with other packages
24457 (defun org-mode-flyspell-verify ()
24458 "Function used for `flyspell-generic-check-word-predicate'."
24459 (if (org-at-heading-p)
24460 ;; At a headline or an inlinetask, check title only. This is
24461 ;; faster than relying on `org-element-at-point'.
24462 (and (save-excursion (beginning-of-line)
24463 (and (let ((case-fold-search t))
24464 (not (looking-at "\\*+ END[ \t]*$")))
24465 (looking-at org-complex-heading-regexp)))
24466 (match-beginning 4)
24467 (>= (point) (match-beginning 4))
24468 (or (not (match-beginning 5))
24469 (< (point) (match-beginning 5))))
24470 (let* ((element (org-element-at-point))
24471 (post-affiliated (org-element-property :post-affiliated element))
24472 (object-check
24473 (function
24474 ;; Non-nil if checks can be done for object at point.
24475 (lambda ()
24476 (let ((object (save-excursion
24477 (when (org-looking-at-p "\\>") (backward-char))
24478 (org-element-context element))))
24479 (case (org-element-type object)
24480 ;; Prevent checks in links due to keybinding conflict
24481 ;; with Flyspell.
24482 ((code entity export-snippet inline-babel-call
24483 inline-src-block line-break latex-fragment link macro
24484 statistics-cookie target timestamp verbatim)
24485 nil)
24486 (footnote-reference
24487 ;; Only in inline footnotes, within the definition.
24488 (and (eq (org-element-property :type object) 'inline)
24489 (< (save-excursion
24490 (goto-char (org-element-property :begin object))
24491 (search-forward ":" nil t 2))
24492 (point))))
24493 (otherwise t)))))))
24494 (cond
24495 ;; Ignore checks in all affiliated keywords but captions.
24496 ((and post-affiliated (< (point) post-affiliated))
24497 (and (save-excursion
24498 (beginning-of-line)
24499 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24500 (> (point) (match-end 0))
24501 (funcall object-check)))
24502 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24503 ((and org-log-into-drawer
24504 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24505 (parent element))
24506 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24507 (setq parent (org-element-property :parent parent)))
24508 (and parent
24509 (eq (compare-strings
24510 log nil nil
24511 (org-element-property :drawer-name parent) nil nil t)
24512 t))))
24513 nil)
24515 (case (org-element-type element)
24516 ((comment quote-section) t)
24517 (comment-block
24518 ;; Allow checks between block markers, not on them.
24519 (and (> (line-beginning-position)
24520 (org-element-property :post-affiliated element))
24521 (save-excursion
24522 (end-of-line)
24523 (skip-chars-forward " \r\t\n")
24524 (< (point) (org-element-property :end element)))))
24525 ;; Arbitrary list of keywords where checks are meaningful.
24526 ;; Make sure point is on the value part of the element.
24527 (keyword
24528 (and (member (org-element-property :key element)
24529 '("DESCRIPTION" "TITLE"))
24530 (< (save-excursion
24531 (beginning-of-line) (search-forward ":") (point))
24532 (point))))
24533 ;; Check is globally allowed in paragraphs verse blocks and
24534 ;; table rows (after affiliated keywords) but some objects
24535 ;; must not be affected.
24536 ((paragraph table-row verse-block)
24537 (and (>= (point) (org-element-property :contents-begin element))
24538 (< (point) (org-element-property :contents-end element))
24539 (funcall object-check)))))))))
24540 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24542 (defun org-remove-flyspell-overlays-in (beg end)
24543 "Remove flyspell overlays in region."
24544 (and (org-bound-and-true-p flyspell-mode)
24545 (fboundp 'flyspell-delete-region-overlays)
24546 (flyspell-delete-region-overlays beg end)))
24548 (defvar flyspell-delayed-commands)
24549 (eval-after-load "flyspell"
24550 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24552 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24553 (eval-after-load "bookmark"
24554 '(if (boundp 'bookmark-after-jump-hook)
24555 ;; We can use the hook
24556 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24557 ;; Hook not available, use advice
24558 (defadvice bookmark-jump (after org-make-visible activate)
24559 "Make the position visible."
24560 (org-bookmark-jump-unhide))))
24562 ;; Make sure saveplace shows the location if it was hidden
24563 (eval-after-load "saveplace"
24564 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24565 "Make the position visible."
24566 (org-bookmark-jump-unhide)))
24568 ;; Make sure ecb shows the location if it was hidden
24569 (eval-after-load "ecb"
24570 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24571 "Make hierarchy visible when jumping into location from ECB tree buffer."
24572 (if (derived-mode-p 'org-mode)
24573 (org-show-context))))
24575 (defun org-bookmark-jump-unhide ()
24576 "Unhide the current position, to show the bookmark location."
24577 (and (derived-mode-p 'org-mode)
24578 (or (outline-invisible-p)
24579 (save-excursion (goto-char (max (point-min) (1- (point))))
24580 (outline-invisible-p)))
24581 (org-show-context 'bookmark-jump)))
24583 (defun org-mark-jump-unhide ()
24584 "Make the point visible with `org-show-context' after jumping to the mark."
24585 (when (and (derived-mode-p 'org-mode)
24586 (outline-invisible-p))
24587 (org-show-context 'mark-goto)))
24589 (eval-after-load "simple"
24590 '(defadvice pop-to-mark-command (after org-make-visible activate)
24591 "Make the point visible with `org-show-context'."
24592 (org-mark-jump-unhide)))
24594 (eval-after-load "simple"
24595 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24596 "Make the point visible with `org-show-context'."
24597 (org-mark-jump-unhide)))
24599 (eval-after-load "simple"
24600 '(defadvice pop-global-mark (after org-make-visible activate)
24601 "Make the point visible with `org-show-context'."
24602 (org-mark-jump-unhide)))
24604 ;; Make session.el ignore our circular variable
24605 (defvar session-globals-exclude)
24606 (eval-after-load "session"
24607 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24609 ;;;; Finish up
24611 (provide 'org)
24613 (run-hooks 'org-load-hook)
24615 ;;; org.el ends here