Fix radio target update
[org-mode.git] / lisp / org.el
blob14e8cee7d201a96a3a003013f6b35a89c0af72ae
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))
4380 ;;;###autoload
4381 (defun turn-on-orgtbl ()
4382 "Unconditionally turn on `orgtbl-mode'."
4383 (require 'org-table)
4384 (orgtbl-mode 1))
4386 (defun org-at-table-p (&optional table-type)
4387 "Return t if the cursor is inside an org-type table.
4388 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4389 (if org-enable-table-editor
4390 (save-excursion
4391 (beginning-of-line 1)
4392 (looking-at (if table-type org-table-any-line-regexp
4393 org-table-line-regexp)))
4394 nil))
4395 (defsubst org-table-p () (org-at-table-p))
4397 (defun org-at-table.el-p ()
4398 "Return t if and only if we are at a table.el table."
4399 (and (org-at-table-p 'any)
4400 (save-excursion
4401 (goto-char (org-table-begin 'any))
4402 (looking-at org-table1-hline-regexp))))
4404 (defun org-table-recognize-table.el ()
4405 "If there is a table.el table nearby, recognize it and move into it."
4406 (if org-table-tab-recognizes-table.el
4407 (if (org-at-table.el-p)
4408 (progn
4409 (beginning-of-line 1)
4410 (if (looking-at org-table-dataline-regexp)
4412 (if (looking-at org-table1-hline-regexp)
4413 (progn
4414 (beginning-of-line 2)
4415 (if (looking-at org-table-any-border-regexp)
4416 (beginning-of-line -1)))))
4417 (if (re-search-forward "|" (org-table-end t) t)
4418 (progn
4419 (require 'table)
4420 (if (table--at-cell-p (point))
4422 (message "recognizing table.el table...")
4423 (table-recognize-table)
4424 (message "recognizing table.el table...done")))
4425 (error "This should not happen"))
4427 nil)
4428 nil))
4430 (defun org-at-table-hline-p ()
4431 "Return t if the cursor is inside a hline in a table."
4432 (if org-enable-table-editor
4433 (save-excursion
4434 (beginning-of-line 1)
4435 (looking-at org-table-hline-regexp))
4436 nil))
4438 (defun org-table-map-tables (function &optional quietly)
4439 "Apply FUNCTION to the start of all tables in the buffer."
4440 (save-excursion
4441 (save-restriction
4442 (widen)
4443 (goto-char (point-min))
4444 (while (re-search-forward org-table-any-line-regexp nil t)
4445 (unless quietly
4446 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4447 (beginning-of-line 1)
4448 (when (and (looking-at org-table-line-regexp)
4449 ;; Exclude tables in src/example/verbatim/clocktable blocks
4450 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4451 (save-excursion (funcall function))
4452 (or (looking-at org-table-line-regexp)
4453 (forward-char 1)))
4454 (re-search-forward org-table-any-border-regexp nil 1))))
4455 (unless quietly (message "Mapping tables: done")))
4457 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4458 (declare-function org-clock-update-mode-line "org-clock" ())
4459 (declare-function org-resolve-clocks "org-clock"
4460 (&optional also-non-dangling-p prompt last-valid))
4462 (defun org-at-TBLFM-p (&optional pos)
4463 "Return t when point (or POS) is in #+TBLFM line."
4464 (save-excursion
4465 (let ((pos pos)))
4466 (goto-char (or pos (point)))
4467 (beginning-of-line 1)
4468 (looking-at org-TBLFM-regexp)))
4470 (defvar org-clock-start-time)
4471 (defvar org-clock-marker (make-marker)
4472 "Marker recording the last clock-in.")
4473 (defvar org-clock-hd-marker (make-marker)
4474 "Marker recording the last clock-in, but the headline position.")
4475 (defvar org-clock-heading ""
4476 "The heading of the current clock entry.")
4477 (defun org-clock-is-active ()
4478 "Return the buffer where the clock is currently running.
4479 Return nil if no clock is running."
4480 (marker-buffer org-clock-marker))
4482 (defun org-check-running-clock ()
4483 "Check if the current buffer contains the running clock.
4484 If yes, offer to stop it and to save the buffer with the changes."
4485 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4486 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4487 (buffer-name))))
4488 (org-clock-out)
4489 (when (y-or-n-p "Save changed buffer?")
4490 (save-buffer))))
4492 (defun org-clocktable-try-shift (dir n)
4493 "Check if this line starts a clock table, if yes, shift the time block."
4494 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4495 (org-clocktable-shift dir n)))
4497 ;;;###autoload
4498 (defun org-clock-persistence-insinuate ()
4499 "Set up hooks for clock persistence."
4500 (require 'org-clock)
4501 (add-hook 'org-mode-hook 'org-clock-load)
4502 (add-hook 'kill-emacs-hook 'org-clock-save))
4504 (defgroup org-archive nil
4505 "Options concerning archiving in Org-mode."
4506 :tag "Org Archive"
4507 :group 'org-structure)
4509 (defcustom org-archive-location "%s_archive::"
4510 "The location where subtrees should be archived.
4512 The value of this variable is a string, consisting of two parts,
4513 separated by a double-colon. The first part is a filename and
4514 the second part is a headline.
4516 When the filename is omitted, archiving happens in the same file.
4517 %s in the filename will be replaced by the current file
4518 name (without the directory part). Archiving to a different file
4519 is useful to keep archived entries from contributing to the
4520 Org-mode Agenda.
4522 The archived entries will be filed as subtrees of the specified
4523 headline. When the headline is omitted, the subtrees are simply
4524 filed away at the end of the file, as top-level entries. Also in
4525 the heading you can use %s to represent the file name, this can be
4526 useful when using the same archive for a number of different files.
4528 Here are a few examples:
4529 \"%s_archive::\"
4530 If the current file is Projects.org, archive in file
4531 Projects.org_archive, as top-level trees. This is the default.
4533 \"::* Archived Tasks\"
4534 Archive in the current file, under the top-level headline
4535 \"* Archived Tasks\".
4537 \"~/org/archive.org::\"
4538 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4540 \"~/org/archive.org::* From %s\"
4541 Archive in file ~/org/archive.org (absolute path), under headlines
4542 \"From FILENAME\" where file name is the current file name.
4544 \"~/org/datetree.org::datetree/* Finished Tasks\"
4545 The \"datetree/\" string is special, signifying to archive
4546 items to the datetree. Items are placed in either the CLOSED
4547 date of the item, or the current date if there is no CLOSED date.
4548 The heading will be a subentry to the current date. There doesn't
4549 need to be a heading, but there always needs to be a slash after
4550 datetree. For example, to store archived items directly in the
4551 datetree, use \"~/org/datetree.org::datetree/\".
4553 \"basement::** Finished Tasks\"
4554 Archive in file ./basement (relative path), as level 3 trees
4555 below the level 2 heading \"** Finished Tasks\".
4557 You may set this option on a per-file basis by adding to the buffer a
4558 line like
4560 #+ARCHIVE: basement::** Finished Tasks
4562 You may also define it locally for a subtree by setting an ARCHIVE property
4563 in the entry. If such a property is found in an entry, or anywhere up
4564 the hierarchy, it will be used."
4565 :group 'org-archive
4566 :type 'string)
4568 (defcustom org-agenda-skip-archived-trees t
4569 "Non-nil means the agenda will skip any items located in archived trees.
4570 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4571 variable is no longer recommended, you should leave it at the value t.
4572 Instead, use the key `v' to cycle the archives-mode in the agenda."
4573 :group 'org-archive
4574 :group 'org-agenda-skip
4575 :type 'boolean)
4577 (defcustom org-columns-skip-archived-trees t
4578 "Non-nil means ignore archived trees when creating column view."
4579 :group 'org-archive
4580 :group 'org-properties
4581 :type 'boolean)
4583 (defcustom org-cycle-open-archived-trees nil
4584 "Non-nil means `org-cycle' will open archived trees.
4585 An archived tree is a tree marked with the tag ARCHIVE.
4586 When nil, archived trees will stay folded. You can still open them with
4587 normal outline commands like `show-all', but not with the cycling commands."
4588 :group 'org-archive
4589 :group 'org-cycle
4590 :type 'boolean)
4592 (defcustom org-sparse-tree-open-archived-trees nil
4593 "Non-nil means sparse tree construction shows matches in archived trees.
4594 When nil, matches in these trees are highlighted, but the trees are kept in
4595 collapsed state."
4596 :group 'org-archive
4597 :group 'org-sparse-trees
4598 :type 'boolean)
4600 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4601 "The default date type when building a sparse tree.
4602 When this is nil, a date is a scheduled or a deadline timestamp.
4603 Otherwise, these types are allowed:
4605 all: all timestamps
4606 active: only active timestamps (<...>)
4607 inactive: only inactive timestamps (<...)
4608 scheduled: only scheduled timestamps
4609 deadline: only deadline timestamps"
4610 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4611 (const :tag "All timestamps" all)
4612 (const :tag "Only active timestamps" active)
4613 (const :tag "Only inactive timestamps" inactive)
4614 (const :tag "Only scheduled timestamps" scheduled)
4615 (const :tag "Only deadline timestamps" deadline)
4616 (const :tag "Only closed timestamps" closed))
4617 :version "24.3"
4618 :group 'org-sparse-trees)
4620 (defun org-cycle-hide-archived-subtrees (state)
4621 "Re-hide all archived subtrees after a visibility state change."
4622 (when (and (not org-cycle-open-archived-trees)
4623 (not (memq state '(overview folded))))
4624 (save-excursion
4625 (let* ((globalp (memq state '(contents all)))
4626 (beg (if globalp (point-min) (point)))
4627 (end (if globalp (point-max) (org-end-of-subtree t))))
4628 (org-hide-archived-subtrees beg end)
4629 (goto-char beg)
4630 (if (looking-at (concat ".*:" org-archive-tag ":"))
4631 (message "%s" (substitute-command-keys
4632 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4634 (defun org-force-cycle-archived ()
4635 "Cycle subtree even if it is archived."
4636 (interactive)
4637 (setq this-command 'org-cycle)
4638 (let ((org-cycle-open-archived-trees t))
4639 (call-interactively 'org-cycle)))
4641 (defun org-hide-archived-subtrees (beg end)
4642 "Re-hide all archived subtrees after a visibility state change."
4643 (save-excursion
4644 (let* ((re (concat ":" org-archive-tag ":")))
4645 (goto-char beg)
4646 (while (re-search-forward re end t)
4647 (when (org-at-heading-p)
4648 (org-flag-subtree t)
4649 (org-end-of-subtree t))))))
4651 (declare-function outline-end-of-heading "outline" ())
4652 (declare-function outline-flag-region "outline" (from to flag))
4653 (defun org-flag-subtree (flag)
4654 (save-excursion
4655 (org-back-to-heading t)
4656 (outline-end-of-heading)
4657 (outline-flag-region (point)
4658 (progn (org-end-of-subtree t) (point))
4659 flag)))
4661 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4663 ;; Declare Column View Code
4665 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4666 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4667 (declare-function org-columns-compute "org-colview" (property))
4669 ;; Declare ID code
4671 (declare-function org-id-store-link "org-id")
4672 (declare-function org-id-locations-load "org-id")
4673 (declare-function org-id-locations-save "org-id")
4674 (defvar org-id-track-globally)
4676 ;;; Variables for pre-computed regular expressions, all buffer local
4678 (defvar org-todo-regexp nil
4679 "Matches any of the TODO state keywords.")
4680 (make-variable-buffer-local 'org-todo-regexp)
4681 (defvar org-not-done-regexp nil
4682 "Matches any of the TODO state keywords except the last one.")
4683 (make-variable-buffer-local 'org-not-done-regexp)
4684 (defvar org-not-done-heading-regexp nil
4685 "Matches a TODO headline that is not done.")
4686 (make-variable-buffer-local 'org-not-done-regexp)
4687 (defvar org-todo-line-regexp nil
4688 "Matches a headline and puts TODO state into group 2 if present.")
4689 (make-variable-buffer-local 'org-todo-line-regexp)
4690 (defvar org-complex-heading-regexp nil
4691 "Matches a headline and puts everything into groups:
4692 group 1: the stars
4693 group 2: The todo keyword, maybe
4694 group 3: Priority cookie
4695 group 4: True headline
4696 group 5: Tags")
4697 (make-variable-buffer-local 'org-complex-heading-regexp)
4698 (defvar org-complex-heading-regexp-format nil
4699 "Printf format to make regexp to match an exact headline.
4700 This regexp will match the headline of any node which has the
4701 exact headline text that is put into the format, but may have any
4702 TODO state, priority and tags.")
4703 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4704 (defvar org-todo-line-tags-regexp nil
4705 "Matches a headline and puts TODO state into group 2 if present.
4706 Also put tags into group 4 if tags are present.")
4707 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4708 (defvar org-ds-keyword-length 12
4709 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4710 (make-variable-buffer-local 'org-ds-keyword-length)
4711 (defvar org-deadline-regexp nil
4712 "Matches the DEADLINE keyword.")
4713 (make-variable-buffer-local 'org-deadline-regexp)
4714 (defvar org-deadline-time-regexp nil
4715 "Matches the DEADLINE keyword together with a time stamp.")
4716 (make-variable-buffer-local 'org-deadline-time-regexp)
4717 (defvar org-deadline-time-hour-regexp nil
4718 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4719 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4720 (defvar org-deadline-line-regexp nil
4721 "Matches the DEADLINE keyword and the rest of the line.")
4722 (make-variable-buffer-local 'org-deadline-line-regexp)
4723 (defvar org-scheduled-regexp nil
4724 "Matches the SCHEDULED keyword.")
4725 (make-variable-buffer-local 'org-scheduled-regexp)
4726 (defvar org-scheduled-time-regexp nil
4727 "Matches the SCHEDULED keyword together with a time stamp.")
4728 (make-variable-buffer-local 'org-scheduled-time-regexp)
4729 (defvar org-scheduled-time-hour-regexp nil
4730 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4731 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4732 (defvar org-closed-time-regexp nil
4733 "Matches the CLOSED keyword together with a time stamp.")
4734 (make-variable-buffer-local 'org-closed-time-regexp)
4736 (defvar org-keyword-time-regexp nil
4737 "Matches any of the 4 keywords, together with the time stamp.")
4738 (make-variable-buffer-local 'org-keyword-time-regexp)
4739 (defvar org-keyword-time-not-clock-regexp nil
4740 "Matches any of the 3 keywords, together with the time stamp.")
4741 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4742 (defvar org-maybe-keyword-time-regexp nil
4743 "Matches a timestamp, possibly preceded by a keyword.")
4744 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4745 (defvar org-all-time-keywords nil
4746 "List of time keywords.")
4747 (make-variable-buffer-local 'org-all-time-keywords)
4749 (defconst org-plain-time-of-day-regexp
4750 (concat
4751 "\\(\\<[012]?[0-9]"
4752 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4753 "\\(--?"
4754 "\\(\\<[012]?[0-9]"
4755 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4756 "\\)?")
4757 "Regular expression to match a plain time or time range.
4758 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4759 groups carry important information:
4760 0 the full match
4761 1 the first time, range or not
4762 8 the second time, if it is a range.")
4764 (defconst org-plain-time-extension-regexp
4765 (concat
4766 "\\(\\<[012]?[0-9]"
4767 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4768 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4769 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4770 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4771 groups carry important information:
4772 0 the full match
4773 7 hours of duration
4774 9 minutes of duration")
4776 (defconst org-stamp-time-of-day-regexp
4777 (concat
4778 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4779 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4780 "\\(--?"
4781 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4782 "Regular expression to match a timestamp time or time range.
4783 After a match, the following groups carry important information:
4784 0 the full match
4785 1 date plus weekday, for back referencing to make sure both times are on the same day
4786 2 the first time, range or not
4787 4 the second time, if it is a range.")
4789 (defconst org-startup-options
4790 '(("fold" org-startup-folded t)
4791 ("overview" org-startup-folded t)
4792 ("nofold" org-startup-folded nil)
4793 ("showall" org-startup-folded nil)
4794 ("showeverything" org-startup-folded showeverything)
4795 ("content" org-startup-folded content)
4796 ("indent" org-startup-indented t)
4797 ("noindent" org-startup-indented nil)
4798 ("hidestars" org-hide-leading-stars t)
4799 ("showstars" org-hide-leading-stars nil)
4800 ("odd" org-odd-levels-only t)
4801 ("oddeven" org-odd-levels-only nil)
4802 ("align" org-startup-align-all-tables t)
4803 ("noalign" org-startup-align-all-tables nil)
4804 ("inlineimages" org-startup-with-inline-images t)
4805 ("noinlineimages" org-startup-with-inline-images nil)
4806 ("latexpreview" org-startup-with-latex-preview t)
4807 ("nolatexpreview" org-startup-with-latex-preview nil)
4808 ("customtime" org-display-custom-times t)
4809 ("logdone" org-log-done time)
4810 ("lognotedone" org-log-done note)
4811 ("nologdone" org-log-done nil)
4812 ("lognoteclock-out" org-log-note-clock-out t)
4813 ("nolognoteclock-out" org-log-note-clock-out nil)
4814 ("logrepeat" org-log-repeat state)
4815 ("lognoterepeat" org-log-repeat note)
4816 ("logdrawer" org-log-into-drawer t)
4817 ("nologdrawer" org-log-into-drawer nil)
4818 ("logstatesreversed" org-log-states-order-reversed t)
4819 ("nologstatesreversed" org-log-states-order-reversed nil)
4820 ("nologrepeat" org-log-repeat nil)
4821 ("logreschedule" org-log-reschedule time)
4822 ("lognotereschedule" org-log-reschedule note)
4823 ("nologreschedule" org-log-reschedule nil)
4824 ("logredeadline" org-log-redeadline time)
4825 ("lognoteredeadline" org-log-redeadline note)
4826 ("nologredeadline" org-log-redeadline nil)
4827 ("logrefile" org-log-refile time)
4828 ("lognoterefile" org-log-refile note)
4829 ("nologrefile" org-log-refile nil)
4830 ("fninline" org-footnote-define-inline t)
4831 ("nofninline" org-footnote-define-inline nil)
4832 ("fnlocal" org-footnote-section nil)
4833 ("fnauto" org-footnote-auto-label t)
4834 ("fnprompt" org-footnote-auto-label nil)
4835 ("fnconfirm" org-footnote-auto-label confirm)
4836 ("fnplain" org-footnote-auto-label plain)
4837 ("fnadjust" org-footnote-auto-adjust t)
4838 ("nofnadjust" org-footnote-auto-adjust nil)
4839 ("constcgs" constants-unit-system cgs)
4840 ("constSI" constants-unit-system SI)
4841 ("noptag" org-tag-persistent-alist nil)
4842 ("hideblocks" org-hide-block-startup t)
4843 ("nohideblocks" org-hide-block-startup nil)
4844 ("beamer" org-startup-with-beamer-mode t)
4845 ("entitiespretty" org-pretty-entities t)
4846 ("entitiesplain" org-pretty-entities nil))
4847 "Variable associated with STARTUP options for org-mode.
4848 Each element is a list of three items: the startup options (as written
4849 in the #+STARTUP line), the corresponding variable, and the value to set
4850 this variable to if the option is found. An optional forth element PUSH
4851 means to push this value onto the list in the variable.")
4853 (defun org-update-property-plist (key val props)
4854 "Update PROPS with KEY and VAL."
4855 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4856 (key (if appending (substring key 0 (- (length key) 1)) key))
4857 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4858 (previous (cdr (assoc key props))))
4859 (if appending
4860 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4861 (cons (cons key val) remainder))))
4863 (defcustom org-group-tags t
4864 "When non-nil (the default), use group tags.
4865 This can be turned on/off through `org-toggle-tags-groups'."
4866 :group 'org-tags
4867 :group 'org-startup
4868 :type 'boolean)
4870 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4872 (defun org-toggle-tags-groups ()
4873 "Toggle support for group tags.
4874 Support for group tags is controlled by the option
4875 `org-group-tags', which is non-nil by default."
4876 (interactive)
4877 (setq org-group-tags (not org-group-tags))
4878 (cond ((and (derived-mode-p 'org-agenda-mode)
4879 org-group-tags)
4880 (org-agenda-redo))
4881 ((derived-mode-p 'org-mode)
4882 (let ((org-inhibit-startup t)) (org-mode))))
4883 (message "Groups tags support has been turned %s"
4884 (if org-group-tags "on" "off")))
4886 (defun org-set-regexps-and-options-for-tags ()
4887 "Precompute variables used for tags."
4888 (when (derived-mode-p 'org-mode)
4889 (org-set-local 'org-file-tags nil)
4890 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4891 (splitre "[ \t]+")
4892 (start 0)
4893 tags ftags key value)
4894 (save-excursion
4895 (save-restriction
4896 (widen)
4897 (goto-char (point-min))
4898 (while (re-search-forward re nil t)
4899 (setq key (upcase (org-match-string-no-properties 1))
4900 value (org-match-string-no-properties 2))
4901 (if (stringp value) (setq value (org-trim value)))
4902 (cond
4903 ((equal key "TAGS")
4904 (setq tags (append tags (if tags '("\\n") nil)
4905 (org-split-string value splitre))))
4906 ((equal key "FILETAGS")
4907 (when (string-match "\\S-" value)
4908 (setq ftags
4909 (append
4910 ftags
4911 (apply 'append
4912 (mapcar (lambda (x) (org-split-string x ":"))
4913 (org-split-string value)))))))))))
4914 ;; Process the file tags.
4915 (and ftags (org-set-local 'org-file-tags
4916 (mapcar 'org-add-prop-inherited ftags)))
4917 (org-set-local 'org-tag-groups-alist nil)
4918 ;; Process the tags.
4919 (when (and (not tags) org-tag-alist)
4920 (setq tags
4921 (mapcar
4922 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4923 ((eq (car tg) :endgroup) "}")
4924 ((eq (car tg) :grouptags) ":")
4925 ((eq (car tg) :newline) "\n")
4926 (t (concat (car tg)
4927 (if (characterp (cdr tg))
4928 (format "(%s)" (char-to-string (cdr tg))) "")))))
4929 org-tag-alist)))
4930 (let (e tgs g)
4931 (while (setq e (pop tags))
4932 (cond
4933 ((equal e "{")
4934 (progn (push '(:startgroup) tgs)
4935 (when (equal (nth 1 tags) ":")
4936 (push (list (replace-regexp-in-string
4937 "(.+)$" "" (nth 0 tags)))
4938 org-tag-groups-alist)
4939 (setq g 0))))
4940 ((equal e ":") (push '(:grouptags) tgs))
4941 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4942 ((equal e "\\n") (push '(:newline) tgs))
4943 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4944 (push (cons (match-string 1 e)
4945 (string-to-char (match-string 2 e))) tgs)
4946 (if (and g (> g 0))
4947 (setcar org-tag-groups-alist
4948 (append (car org-tag-groups-alist)
4949 (list (match-string 1 e)))))
4950 (if g (setq g (1+ g))))
4951 (t (push (list e) tgs)
4952 (if (and g (> g 0))
4953 (setcar org-tag-groups-alist
4954 (append (car org-tag-groups-alist) (list e))))
4955 (if g (setq g (1+ g))))))
4956 (org-set-local 'org-tag-alist nil)
4957 (while (setq e (pop tgs))
4958 (or (and (stringp (car e))
4959 (assoc (car e) org-tag-alist))
4960 (push e org-tag-alist)))
4961 ;; Return a list with tag variables
4962 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4964 (defvar org-ota nil)
4965 (defun org-set-regexps-and-options ()
4966 "Precompute regular expressions used in the current buffer."
4967 (when (derived-mode-p 'org-mode)
4968 (org-set-local 'org-todo-kwd-alist nil)
4969 (org-set-local 'org-todo-key-alist nil)
4970 (org-set-local 'org-todo-key-trigger nil)
4971 (org-set-local 'org-todo-keywords-1 nil)
4972 (org-set-local 'org-done-keywords nil)
4973 (org-set-local 'org-todo-heads nil)
4974 (org-set-local 'org-todo-sets nil)
4975 (org-set-local 'org-todo-log-states nil)
4976 (org-set-local 'org-file-properties nil)
4977 (let ((re (org-make-options-regexp
4978 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4979 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4980 "SETUPFILE" "OPTIONS")
4981 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4982 (splitre "[ \t]+")
4983 (scripts org-use-sub-superscripts)
4984 kwds kws0 kwsa key log value cat arch const links hw dws
4985 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4986 (start 0))
4987 (save-excursion
4988 (save-restriction
4989 (widen)
4990 (goto-char (point-min))
4991 (while
4992 (or (and
4993 ext-setup-or-nil
4994 (not org-ota)
4995 (let (ret)
4996 (with-temp-buffer
4997 (insert ext-setup-or-nil)
4998 (let ((major-mode 'org-mode) org-ota)
4999 (setq ret (save-match-data
5000 (org-set-regexps-and-options-for-tags)))))
5001 ;; Append setupfile tags to existing tags
5002 (setq org-ota t)
5003 (setq org-file-tags
5004 (delq nil (append org-file-tags (nth 0 ret)))
5005 org-tag-alist
5006 (delq nil (append org-tag-alist (nth 1 ret)))
5007 org-tag-groups-alist
5008 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5009 (and ext-setup-or-nil
5010 (string-match re ext-setup-or-nil start)
5011 (setq start (match-end 0)))
5012 (and (setq ext-setup-or-nil nil start 0)
5013 (re-search-forward re nil t)))
5014 (setq key (upcase (match-string 1 ext-setup-or-nil))
5015 value (org-match-string-no-properties 2 ext-setup-or-nil))
5016 (if (stringp value) (setq value (org-trim value)))
5017 (cond
5018 ((equal key "CATEGORY")
5019 (setq cat value))
5020 ((member key '("SEQ_TODO" "TODO"))
5021 (push (cons 'sequence (org-split-string value splitre)) kwds))
5022 ((equal key "TYP_TODO")
5023 (push (cons 'type (org-split-string value splitre)) kwds))
5024 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5025 ;; general TODO-like setup
5026 (push (cons (intern (downcase (match-string 1 key)))
5027 (org-split-string value splitre)) kwds))
5028 ((equal key "COLUMNS")
5029 (org-set-local 'org-columns-default-format value))
5030 ((equal key "LINK")
5031 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5032 (push (cons (match-string 1 value)
5033 (org-trim (match-string 2 value)))
5034 links)))
5035 ((equal key "PRIORITIES")
5036 (setq prio (org-split-string value " +")))
5037 ((equal key "PROPERTY")
5038 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5039 (setq props (org-update-property-plist (match-string 1 value)
5040 (match-string 2 value)
5041 props))))
5042 ((equal key "CONSTANTS")
5043 (org-table-set-constants))
5044 ((equal key "STARTUP")
5045 (let ((opts (org-split-string value splitre))
5046 l var val)
5047 (while (setq l (pop opts))
5048 (when (setq l (assoc l org-startup-options))
5049 (setq var (nth 1 l) val (nth 2 l))
5050 (if (not (nth 3 l))
5051 (set (make-local-variable var) val)
5052 (if (not (listp (symbol-value var)))
5053 (set (make-local-variable var) nil))
5054 (set (make-local-variable var) (symbol-value var))
5055 (add-to-list var val))))))
5056 ((equal key "ARCHIVE")
5057 (setq arch value)
5058 (remove-text-properties 0 (length arch)
5059 '(face t fontified t) arch))
5060 ((equal key "OPTIONS")
5061 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5062 (setq scripts (read (match-string 2 value)))))
5063 ((and (equal key "SETUPFILE")
5064 ;; Prevent checking in Gnus messages
5065 (not buffer-read-only))
5066 (setq setup-contents (org-file-contents
5067 (expand-file-name
5068 (org-remove-double-quotes value))
5069 'noerror))
5070 (if (not ext-setup-or-nil)
5071 (setq ext-setup-or-nil setup-contents start 0)
5072 (setq ext-setup-or-nil
5073 (concat (substring ext-setup-or-nil 0 start)
5074 "\n" setup-contents "\n"
5075 (substring ext-setup-or-nil start)))))))
5076 ;; search for property blocks
5077 (goto-char (point-min))
5078 (while (re-search-forward org-block-regexp nil t)
5079 (when (equal "PROPERTY" (upcase (match-string 1)))
5080 (setq value (replace-regexp-in-string
5081 "[\n\r]" " " (match-string 4)))
5082 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5083 (setq props (org-update-property-plist (match-string 1 value)
5084 (match-string 2 value)
5085 props)))))))
5086 (org-set-local 'org-use-sub-superscripts scripts)
5087 (when cat
5088 (org-set-local 'org-category (intern cat))
5089 (push (cons "CATEGORY" cat) props))
5090 (when prio
5091 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5092 (setq prio (mapcar 'string-to-char prio))
5093 (org-set-local 'org-highest-priority (nth 0 prio))
5094 (org-set-local 'org-lowest-priority (nth 1 prio))
5095 (org-set-local 'org-default-priority (nth 2 prio)))
5096 (and props (org-set-local 'org-file-properties (nreverse props)))
5097 (and arch (org-set-local 'org-archive-location arch))
5098 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5099 ;; Process the TODO keywords
5100 (unless kwds
5101 ;; Use the global values as if they had been given locally.
5102 (setq kwds (default-value 'org-todo-keywords))
5103 (if (stringp (car kwds))
5104 (setq kwds (list (cons org-todo-interpretation
5105 (default-value 'org-todo-keywords)))))
5106 (setq kwds (reverse kwds)))
5107 (setq kwds (nreverse kwds))
5108 (let (inter kws kw)
5109 (while (setq kws (pop kwds))
5110 (let ((kws (or
5111 (run-hook-with-args-until-success
5112 'org-todo-setup-filter-hook kws)
5113 kws)))
5114 (setq inter (pop kws) sep (member "|" kws)
5115 kws0 (delete "|" (copy-sequence kws))
5116 kwsa nil
5117 kws1 (mapcar
5118 (lambda (x)
5119 ;; 1 2
5120 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5121 (progn
5122 (setq kw (match-string 1 x)
5123 key (and (match-end 2) (match-string 2 x))
5124 log (org-extract-log-state-settings x))
5125 (push (cons kw (and key (string-to-char key))) kwsa)
5126 (and log (push log org-todo-log-states))
5128 (error "Invalid TODO keyword %s" x)))
5129 kws0)
5130 kwsa (if kwsa (append '((:startgroup))
5131 (nreverse kwsa)
5132 '((:endgroup))))
5133 hw (car kws1)
5134 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5135 tail (list inter hw (car dws) (org-last dws))))
5136 (add-to-list 'org-todo-heads hw 'append)
5137 (push kws1 org-todo-sets)
5138 (setq org-done-keywords (append org-done-keywords dws nil))
5139 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5140 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5141 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5142 (setq org-todo-sets (nreverse org-todo-sets)
5143 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5144 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5145 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5146 ;; Compute the regular expressions and other local variables.
5147 ;; Using `org-outline-regexp-bol' would complicate them much,
5148 ;; because of the fixed white space at the end of that string.
5149 (if (not org-done-keywords)
5150 (setq org-done-keywords (and org-todo-keywords-1
5151 (list (org-last org-todo-keywords-1)))))
5152 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5153 (length org-scheduled-string)
5154 (length org-clock-string)
5155 (length org-closed-string)))
5156 org-not-done-keywords
5157 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5158 org-todo-regexp
5159 (concat "\\("
5160 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5161 "\\)")
5162 org-not-done-regexp
5163 (concat "\\("
5164 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5165 "\\)")
5166 org-not-done-heading-regexp
5167 (format org-heading-keyword-regexp-format org-not-done-regexp)
5168 org-todo-line-regexp
5169 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5170 org-complex-heading-regexp
5171 (concat "^\\(\\*+\\)"
5172 "\\(?: +" org-todo-regexp "\\)?"
5173 "\\(?: +\\(\\[#.\\]\\)\\)?"
5174 "\\(?: +\\(.*?\\)\\)??"
5175 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5176 "[ \t]*$")
5177 org-complex-heading-regexp-format
5178 (concat "^\\(\\*+\\)"
5179 "\\(?: +" org-todo-regexp "\\)?"
5180 "\\(?: +\\(\\[#.\\]\\)\\)?"
5181 "\\(?: +"
5182 ;; Stats cookies can be stuck to body.
5183 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5184 "\\(%s\\)"
5185 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5186 "\\)"
5187 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5188 "[ \t]*$")
5189 org-todo-line-tags-regexp
5190 (concat "^\\(\\*+\\)"
5191 "\\(?: +" org-todo-regexp "\\)?"
5192 "\\(?: +\\(.*?\\)\\)??"
5193 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5194 "[ \t]*$")
5195 org-deadline-regexp (concat "\\<" org-deadline-string)
5196 org-deadline-time-regexp
5197 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5198 org-deadline-time-hour-regexp
5199 (concat "\\<" org-deadline-string
5200 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5201 org-deadline-line-regexp
5202 (concat "\\<\\(" org-deadline-string "\\).*")
5203 org-scheduled-regexp
5204 (concat "\\<" org-scheduled-string)
5205 org-scheduled-time-regexp
5206 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5207 org-scheduled-time-hour-regexp
5208 (concat "\\<" org-scheduled-string
5209 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5210 org-closed-time-regexp
5211 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5212 org-keyword-time-regexp
5213 (concat "\\<\\(" org-scheduled-string
5214 "\\|" org-deadline-string
5215 "\\|" org-closed-string
5216 "\\|" org-clock-string "\\)"
5217 " *[[<]\\([^]>]+\\)[]>]")
5218 org-keyword-time-not-clock-regexp
5219 (concat "\\<\\(" org-scheduled-string
5220 "\\|" org-deadline-string
5221 "\\|" org-closed-string
5222 "\\)"
5223 " *[[<]\\([^]>]+\\)[]>]")
5224 org-maybe-keyword-time-regexp
5225 (concat "\\(\\<\\(" org-scheduled-string
5226 "\\|" org-deadline-string
5227 "\\|" org-closed-string
5228 "\\|" org-clock-string "\\)\\)?"
5229 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5230 org-all-time-keywords
5231 (mapcar (lambda (w) (substring w 0 -1))
5232 (list org-scheduled-string org-deadline-string
5233 org-clock-string org-closed-string)))
5234 (setq org-ota nil)
5235 (org-compute-latex-and-related-regexp))))
5237 (defun org-file-contents (file &optional noerror)
5238 "Return the contents of FILE, as a string."
5239 (if (and file (file-readable-p file))
5240 (with-temp-buffer
5241 (insert-file-contents file)
5242 (buffer-string))
5243 (funcall (if noerror #'message #'error)
5244 "Cannot read file \"%s\"%s"
5245 file
5246 (let ((from (buffer-file-name (buffer-base-buffer))))
5247 (if from (concat " (referenced in file \"" from "\")") "")))))
5249 (defun org-extract-log-state-settings (x)
5250 "Extract the log state setting from a TODO keyword string.
5251 This will extract info from a string like \"WAIT(w@/!)\"."
5252 (let (kw key log1 log2)
5253 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5254 (setq kw (match-string 1 x)
5255 key (and (match-end 2) (match-string 2 x))
5256 log1 (and (match-end 3) (match-string 3 x))
5257 log2 (and (match-end 4) (match-string 4 x)))
5258 (and (or log1 log2)
5259 (list kw
5260 (and log1 (if (equal log1 "!") 'time 'note))
5261 (and log2 (if (equal log2 "!") 'time 'note)))))))
5263 (defun org-remove-keyword-keys (list)
5264 "Remove a pair of parenthesis at the end of each string in LIST."
5265 (mapcar (lambda (x)
5266 (if (string-match "(.*)$" x)
5267 (substring x 0 (match-beginning 0))
5269 list))
5271 (defun org-assign-fast-keys (alist)
5272 "Assign fast keys to a keyword-key alist.
5273 Respect keys that are already there."
5274 (let (new e (alt ?0))
5275 (while (setq e (pop alist))
5276 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5277 (cdr e)) ;; Key already assigned.
5278 (push e new)
5279 (let ((clist (string-to-list (downcase (car e))))
5280 (used (append new alist)))
5281 (when (= (car clist) ?@)
5282 (pop clist))
5283 (while (and clist (rassoc (car clist) used))
5284 (pop clist))
5285 (unless clist
5286 (while (rassoc alt used)
5287 (incf alt)))
5288 (push (cons (car e) (or (car clist) alt)) new))))
5289 (nreverse new)))
5291 ;;; Some variables used in various places
5293 (defvar org-window-configuration nil
5294 "Used in various places to store a window configuration.")
5295 (defvar org-selected-window nil
5296 "Used in various places to store a window configuration.")
5297 (defvar org-finish-function nil
5298 "Function to be called when `C-c C-c' is used.
5299 This is for getting out of special buffers like capture.")
5302 ;; FIXME: Occasionally check by commenting these, to make sure
5303 ;; no other functions uses these, forgetting to let-bind them.
5304 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5305 (defvar org-last-state)
5306 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5308 ;; Defined somewhere in this file, but used before definition.
5309 (defvar org-entities) ;; defined in org-entities.el
5310 (defvar org-struct-menu)
5311 (defvar org-org-menu)
5312 (defvar org-tbl-menu)
5314 ;;;; Define the Org-mode
5316 ;; We use a before-change function to check if a table might need
5317 ;; an update.
5318 (defvar org-table-may-need-update t
5319 "Indicates that a table might need an update.
5320 This variable is set by `org-before-change-function'.
5321 `org-table-align' sets it back to nil.")
5322 (defun org-before-change-function (beg end)
5323 "Every change indicates that a table might need an update."
5324 (setq org-table-may-need-update t))
5325 (defvar org-mode-map)
5326 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5327 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5328 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5329 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5330 (defvar org-table-buffer-is-an nil)
5332 (defvar bidi-paragraph-direction)
5333 (defvar buffer-face-mode-face)
5335 (require 'outline)
5336 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5337 (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"))
5338 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5340 ;; Other stuff we need.
5341 (require 'time-date)
5342 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5343 (require 'easymenu)
5344 (require 'overlay)
5346 ;; (require 'org-macs) moved higher up in the file before it is first used
5347 (require 'org-entities)
5348 ;; (require 'org-compat) moved higher up in the file before it is first used
5349 (require 'org-faces)
5350 (require 'org-list)
5351 (require 'org-pcomplete)
5352 (require 'org-src)
5353 (require 'org-footnote)
5354 (require 'org-macro)
5356 ;; babel
5357 (require 'ob)
5359 ;;;###autoload
5360 (define-derived-mode org-mode outline-mode "Org"
5361 "Outline-based notes management and organizer, alias
5362 \"Carsten's outline-mode for keeping track of everything.\"
5364 Org-mode develops organizational tasks around a NOTES file which
5365 contains information about projects as plain text. Org-mode is
5366 implemented on top of outline-mode, which is ideal to keep the content
5367 of large files well structured. It supports ToDo items, deadlines and
5368 time stamps, which magically appear in the diary listing of the Emacs
5369 calendar. Tables are easily created with a built-in table editor.
5370 Plain text URL-like links connect to websites, emails (VM), Usenet
5371 messages (Gnus), BBDB entries, and any files related to the project.
5372 For printing and sharing of notes, an Org-mode file (or a part of it)
5373 can be exported as a structured ASCII or HTML file.
5375 The following commands are available:
5377 \\{org-mode-map}"
5379 ;; Get rid of Outline menus, they are not needed
5380 ;; Need to do this here because define-derived-mode sets up
5381 ;; the keymap so late. Still, it is a waste to call this each time
5382 ;; we switch another buffer into org-mode.
5383 (if (featurep 'xemacs)
5384 (when (boundp 'outline-mode-menu-heading)
5385 ;; Assume this is Greg's port, it uses easymenu
5386 (easy-menu-remove outline-mode-menu-heading)
5387 (easy-menu-remove outline-mode-menu-show)
5388 (easy-menu-remove outline-mode-menu-hide))
5389 (define-key org-mode-map [menu-bar headings] 'undefined)
5390 (define-key org-mode-map [menu-bar hide] 'undefined)
5391 (define-key org-mode-map [menu-bar show] 'undefined))
5393 (org-load-modules-maybe)
5394 (easy-menu-add org-org-menu)
5395 (easy-menu-add org-tbl-menu)
5396 (org-install-agenda-files-menu)
5397 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5398 (add-to-invisibility-spec '(org-cwidth))
5399 (add-to-invisibility-spec '(org-hide-block . t))
5400 (when (featurep 'xemacs)
5401 (org-set-local 'line-move-ignore-invisible t))
5402 (org-set-local 'outline-regexp org-outline-regexp)
5403 (org-set-local 'outline-level 'org-outline-level)
5404 (setq bidi-paragraph-direction 'left-to-right)
5405 (when (and org-ellipsis
5406 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5407 (fboundp 'make-glyph-code))
5408 (unless org-display-table
5409 (setq org-display-table (make-display-table)))
5410 (set-display-table-slot
5411 org-display-table 4
5412 (vconcat (mapcar
5413 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5414 org-ellipsis)))
5415 (if (stringp org-ellipsis) org-ellipsis "..."))))
5416 (setq buffer-display-table org-display-table))
5417 (org-set-regexps-and-options-for-tags)
5418 (org-set-regexps-and-options)
5419 (org-set-font-lock-defaults)
5420 (when (and org-tag-faces (not org-tags-special-faces-re))
5421 ;; tag faces set outside customize.... force initialization.
5422 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5423 ;; Calc embedded
5424 (org-set-local 'calc-embedded-open-mode "# ")
5425 ;; Modify a few syntax entries
5426 (modify-syntax-entry ?@ "w")
5427 (modify-syntax-entry ?\" "\"")
5428 (modify-syntax-entry ?\\ "_")
5429 (modify-syntax-entry ?~ "_")
5430 (if org-startup-truncated (setq truncate-lines t))
5431 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5432 (org-set-local 'font-lock-unfontify-region-function
5433 'org-unfontify-region)
5434 ;; Activate before-change-function
5435 (org-set-local 'org-table-may-need-update t)
5436 (org-add-hook 'before-change-functions 'org-before-change-function nil
5437 'local)
5438 ;; Check for running clock before killing a buffer
5439 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5440 ;; Initialize macros templates.
5441 (org-macro-initialize-templates)
5442 ;; Initialize radio targets.
5443 (org-update-radio-target-regexp)
5444 ;; Indentation.
5445 (org-set-local 'indent-line-function 'org-indent-line)
5446 (org-set-local 'indent-region-function 'org-indent-region)
5447 ;; Filling and auto-filling.
5448 (org-setup-filling)
5449 ;; Comments.
5450 (org-setup-comments-handling)
5451 ;; Initialize cache.
5452 (org-element-cache-reset)
5453 ;; Beginning/end of defun
5454 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5455 (org-set-local 'end-of-defun-function
5456 (lambda ()
5457 (if (not (org-at-heading-p))
5458 (org-forward-element)
5459 (org-forward-element)
5460 (forward-char -1))))
5461 ;; Next error for sparse trees
5462 (org-set-local 'next-error-function 'org-occur-next-match)
5463 ;; Make sure dependence stuff works reliably, even for users who set it
5464 ;; too late :-(
5465 (if org-enforce-todo-dependencies
5466 (add-hook 'org-blocker-hook
5467 'org-block-todo-from-children-or-siblings-or-parent)
5468 (remove-hook 'org-blocker-hook
5469 'org-block-todo-from-children-or-siblings-or-parent))
5470 (if org-enforce-todo-checkbox-dependencies
5471 (add-hook 'org-blocker-hook
5472 'org-block-todo-from-checkboxes)
5473 (remove-hook 'org-blocker-hook
5474 'org-block-todo-from-checkboxes))
5476 ;; Align options lines
5477 (org-set-local
5478 'align-mode-rules-list
5479 '((org-in-buffer-settings
5480 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5481 (modes . '(org-mode)))))
5483 ;; Imenu
5484 (org-set-local 'imenu-create-index-function
5485 'org-imenu-get-tree)
5487 ;; Make isearch reveal context
5488 (if (or (featurep 'xemacs)
5489 (not (boundp 'outline-isearch-open-invisible-function)))
5490 ;; Emacs 21 and XEmacs make use of the hook
5491 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5492 ;; Emacs 22 deals with this through a special variable
5493 (org-set-local 'outline-isearch-open-invisible-function
5494 (lambda (&rest ignore) (org-show-context 'isearch)))
5495 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5497 ;; Setup the pcomplete hooks
5498 (set (make-local-variable 'pcomplete-command-completion-function)
5499 'org-pcomplete-initial)
5500 (set (make-local-variable 'pcomplete-command-name-function)
5501 'org-command-at-point)
5502 (set (make-local-variable 'pcomplete-default-completion-function)
5503 'ignore)
5504 (set (make-local-variable 'pcomplete-parse-arguments-function)
5505 'org-parse-arguments)
5506 (set (make-local-variable 'pcomplete-termination-string) "")
5507 (when (>= emacs-major-version 23)
5508 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5510 ;; If empty file that did not turn on org-mode automatically, make it to.
5511 (if (and org-insert-mode-line-in-empty-file
5512 (org-called-interactively-p 'any)
5513 (= (point-min) (point-max)))
5514 (insert "# -*- mode: org -*-\n\n"))
5515 (unless org-inhibit-startup
5516 (org-unmodified
5517 (and org-startup-with-beamer-mode (org-beamer-mode))
5518 (when org-startup-align-all-tables
5519 (org-table-map-tables 'org-table-align 'quietly))
5520 (when org-startup-with-inline-images
5521 (org-display-inline-images))
5522 (when org-startup-with-latex-preview
5523 (org-preview-latex-fragment))
5524 (unless org-inhibit-startup-visibility-stuff
5525 (org-set-startup-visibility))))
5526 ;; Try to set org-hide correctly
5527 (let ((foreground (org-find-invisible-foreground)))
5528 (if foreground
5529 (set-face-foreground 'org-hide foreground))))
5531 ;; Update `customize-package-emacs-version-alist'
5532 (add-to-list 'customize-package-emacs-version-alist
5533 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5534 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5535 ("8.2.6" . "24.4")))
5537 (defvar org-mode-transpose-word-syntax-table
5538 (let ((st (make-syntax-table)))
5539 (mapc (lambda(c) (modify-syntax-entry
5540 (string-to-char (car c)) "w p" st))
5541 org-emphasis-alist)
5542 st))
5544 (when (fboundp 'abbrev-table-put)
5545 (abbrev-table-put org-mode-abbrev-table
5546 :parents (list text-mode-abbrev-table)))
5548 (defsubst org-fix-ellipsis-at-bol ()
5549 (save-excursion (goto-char (window-start)) (recenter 0)))
5551 (defun org-find-invisible-foreground ()
5552 (let ((candidates (remove
5553 "unspecified-bg"
5554 (nconc
5555 (list (face-background 'default)
5556 (face-background 'org-default))
5557 (mapcar
5558 (lambda (alist)
5559 (when (boundp alist)
5560 (cdr (assoc 'background-color (symbol-value alist)))))
5561 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5562 (list (face-foreground 'org-hide))))))
5563 (car (remove nil candidates))))
5565 (defun org-current-time (&optional rounding-minutes past)
5566 "Current time, possibly rounded to ROUNDING-MINUTES.
5567 When ROUNDING-MINUTES is not an integer, fall back on the car of
5568 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5569 the rounding returns a past time."
5570 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5571 (car org-time-stamp-rounding-minutes)))
5572 (time (decode-time)) res)
5573 (if (< r 1)
5574 (current-time)
5575 (setq res
5576 (apply 'encode-time
5577 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5578 (nthcdr 2 time))))
5579 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5580 (seconds-to-time (- (org-float-time res) (* r 60)))
5581 res))))
5583 (defun org-today ()
5584 "Return today date, considering `org-extend-today-until'."
5585 (time-to-days
5586 (time-subtract (current-time)
5587 (list 0 (* 3600 org-extend-today-until) 0))))
5589 ;;;; Font-Lock stuff, including the activators
5591 (defvar org-mouse-map (make-sparse-keymap))
5592 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5593 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5594 (when org-mouse-1-follows-link
5595 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5596 (when org-tab-follows-link
5597 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5598 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5600 (require 'font-lock)
5602 (defconst org-non-link-chars "]\t\n\r<>")
5603 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5604 "file+sys" "news" "shell" "elisp" "doi" "message"
5605 "help"))
5606 (defvar org-link-types-re nil
5607 "Matches a link that has a url-like prefix like \"http:\"")
5608 (defvar org-link-re-with-space nil
5609 "Matches a link with spaces, optional angular brackets around it.")
5610 (defvar org-link-re-with-space2 nil
5611 "Matches a link with spaces, optional angular brackets around it.")
5612 (defvar org-link-re-with-space3 nil
5613 "Matches a link with spaces, only for internal part in bracket links.")
5614 (defvar org-angle-link-re nil
5615 "Matches link with angular brackets, spaces are allowed.")
5616 (defvar org-plain-link-re nil
5617 "Matches plain link, without spaces.")
5618 (defvar org-bracket-link-regexp nil
5619 "Matches a link in double brackets.")
5620 (defvar org-bracket-link-analytic-regexp nil
5621 "Regular expression used to analyze links.
5622 Here is what the match groups contain after a match:
5623 1: http:
5624 2: http
5625 3: path
5626 4: [desc]
5627 5: desc")
5628 (defvar org-bracket-link-analytic-regexp++ nil
5629 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5630 (defvar org-any-link-re nil
5631 "Regular expression matching any link.")
5633 (defconst org-match-sexp-depth 3
5634 "Number of stacked braces for sub/superscript matching.")
5636 (defun org-create-multibrace-regexp (left right n)
5637 "Create a regular expression which will match a balanced sexp.
5638 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5639 as single character strings.
5640 The regexp returned will match the entire expression including the
5641 delimiters. It will also define a single group which contains the
5642 match except for the outermost delimiters. The maximum depth of
5643 stacked delimiters is N. Escaping delimiters is not possible."
5644 (let* ((nothing (concat "[^" left right "]*?"))
5645 (or "\\|")
5646 (re nothing)
5647 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5648 (while (> n 1)
5649 (setq n (1- n)
5650 re (concat re or next)
5651 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5652 (concat left "\\(" re "\\)" right)))
5654 (defconst org-match-substring-regexp
5655 (concat
5656 "\\(\\S-\\)\\([_^]\\)\\("
5657 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5658 "\\|"
5659 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5660 "\\|"
5661 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5662 "The regular expression matching a sub- or superscript.")
5664 (defconst org-match-substring-with-braces-regexp
5665 (concat
5666 "\\(\\S-\\)\\([_^]\\)"
5667 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5668 "The regular expression matching a sub- or superscript, forcing braces.")
5670 (defun org-make-link-regexps ()
5671 "Update the link regular expressions.
5672 This should be called after the variable `org-link-types' has changed."
5673 (let ((types-re (regexp-opt org-link-types t)))
5674 (setq org-link-types-re
5675 (concat "\\`" types-re ":")
5676 org-link-re-with-space
5677 (concat "<?" types-re ":"
5678 "\\([^" org-non-link-chars " ]"
5679 "[^" org-non-link-chars "]*"
5680 "[^" org-non-link-chars " ]\\)>?")
5681 org-link-re-with-space2
5682 (concat "<?" types-re ":"
5683 "\\([^" org-non-link-chars " ]"
5684 "[^\t\n\r]*"
5685 "[^" org-non-link-chars " ]\\)>?")
5686 org-link-re-with-space3
5687 (concat "<?" types-re ":"
5688 "\\([^" org-non-link-chars " ]"
5689 "[^\t\n\r]*\\)")
5690 org-angle-link-re
5691 (concat "<" types-re ":"
5692 "\\([^" org-non-link-chars " ]"
5693 "[^" org-non-link-chars "]*"
5694 "\\)>")
5695 org-plain-link-re
5696 (concat
5697 "\\<" types-re ":"
5698 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5699 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5700 org-bracket-link-regexp
5701 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5702 org-bracket-link-analytic-regexp
5703 (concat
5704 "\\[\\["
5705 "\\(" types-re ":\\)?"
5706 "\\([^]]+\\)"
5707 "\\]"
5708 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5709 "\\]")
5710 org-bracket-link-analytic-regexp++
5711 (concat
5712 "\\[\\["
5713 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5714 "\\([^]]+\\)"
5715 "\\]"
5716 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5717 "\\]")
5718 org-any-link-re
5719 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5720 org-angle-link-re "\\)\\|\\("
5721 org-plain-link-re "\\)"))))
5723 (org-make-link-regexps)
5725 (defvar org-emph-face nil)
5727 (defun org-do-emphasis-faces (limit)
5728 "Run through the buffer and emphasize strings."
5729 (let (rtn a)
5730 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5731 (let* ((border (char-after (match-beginning 3)))
5732 (bre (regexp-quote (char-to-string border))))
5733 (if (and (not (= border (char-after (match-beginning 4))))
5734 (not (save-match-data
5735 (string-match (concat bre ".*" bre)
5736 (replace-regexp-in-string
5737 "\n" " "
5738 (substring (match-string 2) 1 -1))))))
5739 (progn
5740 (setq rtn t)
5741 (setq a (assoc (match-string 3) org-emphasis-alist))
5742 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5743 'face
5744 (nth 1 a))
5745 (and (nth 2 a)
5746 (org-remove-flyspell-overlays-in
5747 (match-beginning 0) (match-end 0)))
5748 (add-text-properties (match-beginning 2) (match-end 2)
5749 '(font-lock-multiline t org-emphasis t))
5750 (when org-hide-emphasis-markers
5751 (add-text-properties (match-end 4) (match-beginning 5)
5752 '(invisible org-link))
5753 (add-text-properties (match-beginning 3) (match-end 3)
5754 '(invisible org-link))))))
5755 (goto-char (1+ (match-beginning 0))))
5756 rtn))
5758 (defun org-emphasize (&optional char)
5759 "Insert or change an emphasis, i.e. a font like bold or italic.
5760 If there is an active region, change that region to a new emphasis.
5761 If there is no region, just insert the marker characters and position
5762 the cursor between them.
5763 CHAR should be the marker character. If it is a space, it means to
5764 remove the emphasis of the selected region.
5765 If CHAR is not given (for example in an interactive call) it will be
5766 prompted for."
5767 (interactive)
5768 (let ((erc org-emphasis-regexp-components)
5769 (prompt "")
5770 (string "") beg end move c s)
5771 (if (org-region-active-p)
5772 (setq beg (region-beginning) end (region-end)
5773 string (buffer-substring beg end))
5774 (setq move t))
5776 (unless char
5777 (message "Emphasis marker or tag: [%s]"
5778 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5779 (setq char (read-char-exclusive)))
5780 (if (equal char ?\ )
5781 (setq s "" move nil)
5782 (unless (assoc (char-to-string char) org-emphasis-alist)
5783 (user-error "No such emphasis marker: \"%c\"" char))
5784 (setq s (char-to-string char)))
5785 (while (and (> (length string) 1)
5786 (equal (substring string 0 1) (substring string -1))
5787 (assoc (substring string 0 1) org-emphasis-alist))
5788 (setq string (substring string 1 -1)))
5789 (setq string (concat s string s))
5790 (if beg (delete-region beg end))
5791 (unless (or (bolp)
5792 (string-match (concat "[" (nth 0 erc) "\n]")
5793 (char-to-string (char-before (point)))))
5794 (insert " "))
5795 (unless (or (eobp)
5796 (string-match (concat "[" (nth 1 erc) "\n]")
5797 (char-to-string (char-after (point)))))
5798 (insert " ") (backward-char 1))
5799 (insert string)
5800 (and move (backward-char 1))))
5802 (defconst org-nonsticky-props
5803 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5805 (defsubst org-rear-nonsticky-at (pos)
5806 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5808 (defun org-activate-plain-links (limit)
5809 "Run through the buffer and add overlays to links."
5810 (let (f hl)
5811 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5812 (not (org-in-src-block-p)))
5813 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5814 (setq f (get-text-property (match-beginning 0) 'face))
5815 (setq hl (org-match-string-no-properties 0))
5816 (if (or (eq f 'org-tag)
5817 (and (listp f) (memq 'org-tag f)))
5819 (add-text-properties (match-beginning 0) (match-end 0)
5820 (list 'mouse-face 'highlight
5821 'face 'org-link
5822 'htmlize-link `(:uri ,hl)
5823 'keymap org-mouse-map))
5824 (org-rear-nonsticky-at (match-end 0)))
5825 t)))
5827 (defun org-activate-code (limit)
5828 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5829 (progn
5830 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5831 (remove-text-properties (match-beginning 0) (match-end 0)
5832 '(display t invisible t intangible t))
5833 t)))
5835 (defcustom org-src-fontify-natively t
5836 "When non-nil, fontify code in code blocks."
5837 :type 'boolean
5838 :version "24.4"
5839 :package-version '(Org . "8.3")
5840 :group 'org-appearance
5841 :group 'org-babel)
5843 (defcustom org-allow-promoting-top-level-subtree nil
5844 "When non-nil, allow promoting a top level subtree.
5845 The leading star of the top level headline will be replaced
5846 by a #."
5847 :type 'boolean
5848 :version "24.1"
5849 :group 'org-appearance)
5851 (defun org-fontify-meta-lines-and-blocks (limit)
5852 (condition-case nil
5853 (org-fontify-meta-lines-and-blocks-1 limit)
5854 (error (message "org-mode fontification error"))))
5856 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5857 "Fontify #+ lines and blocks."
5858 (let ((case-fold-search t))
5859 (if (re-search-forward
5860 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5861 limit t)
5862 (let ((beg (match-beginning 0))
5863 (block-start (match-end 0))
5864 (block-end nil)
5865 (lang (match-string 7))
5866 (beg1 (line-beginning-position 2))
5867 (dc1 (downcase (match-string 2)))
5868 (dc3 (downcase (match-string 3)))
5869 end end1 quoting block-type ovl)
5870 (cond
5871 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5872 ;; a single line of backend-specific content
5873 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5874 (remove-text-properties (match-beginning 0) (match-end 0)
5875 '(display t invisible t intangible t))
5876 (add-text-properties (match-beginning 1) (match-end 3)
5877 '(font-lock-fontified t face org-meta-line))
5878 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5879 '(font-lock-fontified t face org-block))
5880 ; for backend-specific code
5882 ((and (match-end 4) (equal dc3 "+begin"))
5883 ;; Truly a block
5884 (setq block-type (downcase (match-string 5))
5885 quoting (member block-type org-protecting-blocks))
5886 (when (re-search-forward
5887 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5888 nil t) ;; on purpose, we look further than LIMIT
5889 (setq end (min (point-max) (match-end 0))
5890 end1 (min (point-max) (1- (match-beginning 0))))
5891 (setq block-end (match-beginning 0))
5892 (when quoting
5893 (org-remove-flyspell-overlays-in beg1 end1)
5894 (remove-text-properties beg end
5895 '(display t invisible t intangible t)))
5896 (add-text-properties
5897 beg end '(font-lock-fontified t font-lock-multiline t))
5898 (add-text-properties beg beg1 '(face org-meta-line))
5899 (org-remove-flyspell-overlays-in beg beg1)
5900 (add-text-properties ; For end_src
5901 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5902 (org-remove-flyspell-overlays-in end1 end)
5903 (cond
5904 ((and lang (not (string= lang "")) org-src-fontify-natively)
5905 (org-src-font-lock-fontify-block lang block-start block-end)
5906 ;; remove old background overlays
5907 (mapc (lambda (ov)
5908 (if (eq (overlay-get ov 'face) 'org-block-background)
5909 (delete-overlay ov)))
5910 (overlays-at (/ (+ beg1 block-end) 2)))
5911 ;; add a background overlay
5912 (setq ovl (make-overlay beg1 block-end))
5913 (overlay-put ovl 'face 'org-block-background)
5914 (overlay-put ovl 'evaporate t)) ; make it go away when empty
5915 (quoting
5916 (add-text-properties beg1 (min (point-max) (1+ end1))
5917 '(face org-block))) ; end of source block
5918 ((not org-fontify-quote-and-verse-blocks))
5919 ((string= block-type "quote")
5920 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5921 ((string= block-type "verse")
5922 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5923 (add-text-properties beg beg1 '(face org-block-begin-line))
5924 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5925 '(face org-block-end-line))
5927 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5928 (org-remove-flyspell-overlays-in
5929 (match-beginning 0)
5930 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5931 (add-text-properties
5932 beg (match-end 3)
5933 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5934 '(font-lock-fontified t invisible t)
5935 '(font-lock-fontified t face org-document-info-keyword)))
5936 (add-text-properties
5937 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5938 (if (string-equal dc1 "+title:")
5939 '(font-lock-fontified t face org-document-title)
5940 '(font-lock-fontified t face org-document-info))))
5941 ((or (equal dc1 "+results")
5942 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5943 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5944 "+call:" "+header:" "+headers:" "+name:"))
5945 (and (match-end 4) (equal dc3 "+attr")))
5946 (org-remove-flyspell-overlays-in
5947 (match-beginning 0)
5948 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5949 (add-text-properties
5950 beg (match-end 0)
5951 '(font-lock-fontified t face org-meta-line))
5953 ((member dc3 '(" " ""))
5954 (org-remove-flyspell-overlays-in beg (match-end 0))
5955 (add-text-properties
5956 beg (match-end 0)
5957 '(font-lock-fontified t face font-lock-comment-face)))
5958 (t ;; just any other in-buffer setting, but not indented
5959 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5960 (add-text-properties
5961 beg (match-end 0)
5962 '(font-lock-fontified t face org-meta-line))
5963 t))))))
5965 (defun org-fontify-drawers (limit)
5966 "Fontify drawers."
5967 (when (re-search-forward org-drawer-regexp limit t)
5968 (add-text-properties
5969 (match-beginning 0) (match-end 0)
5970 '(font-lock-fontified t face org-special-keyword))
5971 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5974 (defun org-fontify-macros (limit)
5975 "Fontify macros."
5976 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5977 (add-text-properties
5978 (match-beginning 0) (match-end 0)
5979 '(font-lock-fontified t face org-macro))
5980 (when org-hide-macro-markers
5981 (add-text-properties (match-end 2) (match-beginning 2)
5982 '(invisible t))
5983 (add-text-properties (match-beginning 1) (match-end 1)
5984 '(invisible t)))
5985 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5988 (defun org-activate-angle-links (limit)
5989 "Run through the buffer and add overlays to links."
5990 (if (and (re-search-forward org-angle-link-re limit t)
5991 (not (org-in-src-block-p)))
5992 (progn
5993 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5994 (add-text-properties (match-beginning 0) (match-end 0)
5995 (list 'mouse-face 'highlight
5996 'keymap org-mouse-map))
5997 (org-rear-nonsticky-at (match-end 0))
5998 t)))
6000 (defun org-activate-footnote-links (limit)
6001 "Run through the buffer and add overlays to footnotes."
6002 (let ((fn (org-footnote-next-reference-or-definition limit)))
6003 (when fn
6004 (let* ((beg (nth 1 fn))
6005 (end (nth 2 fn))
6006 (label (car fn))
6007 (referencep (/= (line-beginning-position) beg)))
6008 (when (and referencep (nth 3 fn))
6009 (save-excursion
6010 (goto-char beg)
6011 (search-forward (or label "fn:"))
6012 (org-remove-flyspell-overlays-in beg (match-end 0))))
6013 (add-text-properties beg end
6014 (list 'mouse-face 'highlight
6015 'keymap org-mouse-map
6016 'help-echo
6017 (if referencep "Footnote reference"
6018 "Footnote definition")
6019 'font-lock-fontified t
6020 'font-lock-multiline t
6021 'face 'org-footnote))))))
6023 (defun org-activate-bracket-links (limit)
6024 "Run through the buffer and add overlays to bracketed links."
6025 (if (and (re-search-forward org-bracket-link-regexp limit t)
6026 (not (org-in-src-block-p)))
6027 (let* ((hl (org-match-string-no-properties 1))
6028 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6029 (ip (org-maybe-intangible
6030 (list 'invisible 'org-link
6031 'keymap org-mouse-map 'mouse-face 'highlight
6032 'font-lock-multiline t 'help-echo help
6033 'htmlize-link `(:uri ,hl))))
6034 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6035 'font-lock-multiline t 'help-echo help
6036 'htmlize-link `(:uri ,hl))))
6037 ;; We need to remove the invisible property here. Table narrowing
6038 ;; may have made some of this invisible.
6039 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6040 (remove-text-properties (match-beginning 0) (match-end 0)
6041 '(invisible nil))
6042 (if (match-end 3)
6043 (progn
6044 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6045 (org-rear-nonsticky-at (match-beginning 3))
6046 (add-text-properties (match-beginning 3) (match-end 3) vp)
6047 (org-rear-nonsticky-at (match-end 3))
6048 (add-text-properties (match-end 3) (match-end 0) ip)
6049 (org-rear-nonsticky-at (match-end 0)))
6050 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6051 (org-rear-nonsticky-at (match-beginning 1))
6052 (add-text-properties (match-beginning 1) (match-end 1) vp)
6053 (org-rear-nonsticky-at (match-end 1))
6054 (add-text-properties (match-end 1) (match-end 0) ip)
6055 (org-rear-nonsticky-at (match-end 0)))
6056 t)))
6058 (defun org-activate-dates (limit)
6059 "Run through the buffer and add overlays to dates."
6060 (if (and (re-search-forward org-tsr-regexp-both limit t)
6061 (not (equal (char-before (match-beginning 0)) 91)))
6062 (progn
6063 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6064 (add-text-properties (match-beginning 0) (match-end 0)
6065 (list 'mouse-face 'highlight
6066 'keymap org-mouse-map))
6067 (org-rear-nonsticky-at (match-end 0))
6068 (when org-display-custom-times
6069 (if (match-end 3)
6070 (org-display-custom-time (match-beginning 3) (match-end 3)))
6071 (org-display-custom-time (match-beginning 1) (match-end 1)))
6072 t)))
6074 (defvar org-target-link-regexp nil
6075 "Regular expression matching radio targets in plain text.")
6076 (make-variable-buffer-local 'org-target-link-regexp)
6078 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6079 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6080 border border border))
6081 "Regular expression matching a link target.")
6083 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6084 "Regular expression matching a radio target.")
6086 (defconst org-any-target-regexp
6087 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6088 "Regular expression matching any target.")
6090 (defun org-activate-target-links (limit)
6091 "Run through the buffer and add overlays to target matches."
6092 (when org-target-link-regexp
6093 (let ((case-fold-search t))
6094 (if (re-search-forward org-target-link-regexp limit t)
6095 (progn
6096 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6097 (add-text-properties (match-beginning 1) (match-end 1)
6098 (list 'mouse-face 'highlight
6099 'keymap org-mouse-map
6100 'help-echo "Radio target link"
6101 'org-linked-text t))
6102 (org-rear-nonsticky-at (match-end 1))
6103 t)))))
6105 (defun org-update-radio-target-regexp ()
6106 "Find all radio targets in this file and update the regular expression.
6107 Also refresh fontification if needed."
6108 (interactive)
6109 (let ((old-regexp org-target-link-regexp)
6110 (targets
6111 (org-with-wide-buffer
6112 (goto-char (point-min))
6113 (let (rtn)
6114 (while (re-search-forward org-radio-target-regexp nil t)
6115 ;; Make sure point is really within the object.
6116 (backward-char)
6117 (let ((obj (org-element-context)))
6118 (when (eq (org-element-type obj) 'radio-target)
6119 (add-to-list 'rtn (org-element-property :value obj)))))
6120 rtn))))
6121 (setq org-target-link-regexp
6122 (and targets
6123 (concat "\\(?:^\\|[^[:alnum:]]\\)\\("
6124 (mapconcat
6125 (lambda (x)
6126 (replace-regexp-in-string
6127 " +" "\\s-+" (regexp-quote x) t t))
6128 targets
6129 "\\|")
6130 "\\)\\(?:$\\|[^[:alnum:]]\\)")))
6131 (unless (equal old-regexp org-target-link-regexp)
6132 ;; Clean-up cache.
6133 (let ((regexp (cond
6134 ((not old-regexp) org-target-link-regexp)
6135 ((not org-target-link-regexp) old-regexp)
6136 (t (concat old-regexp "\\|" org-target-link-regexp)))))
6137 (when regexp
6138 (org-with-wide-buffer
6139 (goto-char (point-min))
6140 (while (re-search-forward regexp nil t)
6141 (org-element-cache-refresh (match-beginning 1))))))
6142 ;; Re fontify buffer.
6143 (when (memq 'radio org-highlight-links)
6144 (org-restart-font-lock)))))
6146 (defun org-hide-wide-columns (limit)
6147 (let (s e)
6148 (setq s (text-property-any (point) (or limit (point-max))
6149 'org-cwidth t))
6150 (when s
6151 (setq e (next-single-property-change s 'org-cwidth))
6152 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6153 (goto-char e)
6154 t)))
6156 (defvar org-latex-and-related-regexp nil
6157 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6159 (defun org-compute-latex-and-related-regexp ()
6160 "Compute regular expression for LaTeX, entities and sub/superscript.
6161 Result depends on variable `org-highlight-latex-and-related'."
6162 (org-set-local
6163 'org-latex-and-related-regexp
6164 (let* ((re-sub
6165 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6166 ((eq org-use-sub-superscripts '{})
6167 (list org-match-substring-with-braces-regexp))
6168 (org-use-sub-superscripts (list org-match-substring-regexp))))
6169 (re-latex
6170 (when (memq 'latex org-highlight-latex-and-related)
6171 (let ((matchers (plist-get org-format-latex-options :matchers)))
6172 (delq nil
6173 (mapcar (lambda (x)
6174 (and (member (car x) matchers) (nth 1 x)))
6175 org-latex-regexps)))))
6176 (re-entities
6177 (when (memq 'entities org-highlight-latex-and-related)
6178 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6179 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6181 (defun org-do-latex-and-related (limit)
6182 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6183 LIMIT bounds the search for syntax to highlight. Stop at first
6184 highlighted object, if any. Return t if some highlighting was
6185 done, nil otherwise."
6186 (when (org-string-nw-p org-latex-and-related-regexp)
6187 (catch 'found
6188 (while (re-search-forward org-latex-and-related-regexp limit t)
6189 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6190 'face))
6191 '(org-code org-verbatim underline))
6192 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6193 '(?_ ?^))
6195 0)))
6196 (font-lock-prepend-text-property
6197 (+ offset (match-beginning 0)) (match-end 0)
6198 'face 'org-latex-and-related)
6199 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6200 '(font-lock-multiline t)))
6201 (throw 'found t)))
6202 nil)))
6204 (defun org-restart-font-lock ()
6205 "Restart `font-lock-mode', to force refontification."
6206 (when (and (boundp 'font-lock-mode) font-lock-mode)
6207 (font-lock-mode -1)
6208 (font-lock-mode 1)))
6210 (defun org-activate-tags (limit)
6211 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6212 (progn
6213 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6214 (add-text-properties (match-beginning 1) (match-end 1)
6215 (list 'mouse-face 'highlight
6216 'keymap org-mouse-map))
6217 (org-rear-nonsticky-at (match-end 1))
6218 t)))
6220 (defun org-outline-level ()
6221 "Compute the outline level of the heading at point.
6222 If this is called at a normal headline, the level is the number of stars.
6223 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6224 (save-excursion
6225 (if (not (condition-case nil
6226 (org-back-to-heading t)
6227 (error nil)))
6229 (looking-at org-outline-regexp)
6230 (1- (- (match-end 0) (match-beginning 0))))))
6232 (defvar org-font-lock-keywords nil)
6234 (defsubst org-re-property (property &optional literal)
6235 "Return a regexp matching a PROPERTY line.
6236 Match group 3 will be set to the value if it exists."
6237 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6238 (if literal property (regexp-quote property))
6239 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6241 (defconst org-property-re
6242 (org-re-property ".*?" 'literal)
6243 "Regular expression matching a property line.
6244 There are four matching groups:
6245 1: :PROPKEY: including the leading and trailing colon,
6246 2: PROPKEY without the leading and trailing colon,
6247 3: PROPVAL without leading or trailing spaces,
6248 4: the indentation of the current line,
6249 5: trailing whitespace.")
6251 (defvar org-font-lock-hook nil
6252 "Functions to be called for special font lock stuff.")
6254 (defvar org-font-lock-set-keywords-hook nil
6255 "Functions that can manipulate `org-font-lock-extra-keywords'.
6256 This is called after `org-font-lock-extra-keywords' is defined, but before
6257 it is installed to be used by font lock. This can be useful if something
6258 needs to be inserted at a specific position in the font-lock sequence.")
6260 (defun org-font-lock-hook (limit)
6261 "Run `org-font-lock-hook' within LIMIT."
6262 (run-hook-with-args 'org-font-lock-hook limit))
6264 (defun org-set-font-lock-defaults ()
6265 "Set font lock defaults for the current buffer."
6266 (let* ((em org-fontify-emphasized-text)
6267 (lk org-highlight-links)
6268 (org-font-lock-extra-keywords
6269 (list
6270 ;; Call the hook
6271 '(org-font-lock-hook)
6272 ;; Headlines
6273 `(,(if org-fontify-whole-heading-line
6274 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6275 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6276 (1 (org-get-level-face 1))
6277 (2 (org-get-level-face 2))
6278 (3 (org-get-level-face 3)))
6279 ;; Table lines
6280 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6281 (1 'org-table t))
6282 ;; Table internals
6283 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6284 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6285 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6286 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6287 ;; Drawers
6288 '(org-fontify-drawers)
6289 ;; Properties
6290 (list org-property-re
6291 '(1 'org-special-keyword t)
6292 '(3 'org-property-value t))
6293 ;; Links
6294 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6295 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6296 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6297 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6298 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6299 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6300 (if (memq 'footnote lk) '(org-activate-footnote-links))
6301 ;; Targets.
6302 (list org-any-target-regexp '(0 'org-target t))
6303 ;; Diary sexps.
6304 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6305 ;; Macro
6306 '(org-fontify-macros)
6307 '(org-hide-wide-columns (0 nil append))
6308 ;; TODO keyword
6309 (list (format org-heading-keyword-regexp-format
6310 org-todo-regexp)
6311 '(2 (org-get-todo-face 2) t))
6312 ;; DONE
6313 (if org-fontify-done-headline
6314 (list (format org-heading-keyword-regexp-format
6315 (concat
6316 "\\(?:"
6317 (mapconcat 'regexp-quote org-done-keywords "\\|")
6318 "\\)"))
6319 '(2 'org-headline-done t))
6320 nil)
6321 ;; Priorities
6322 '(org-font-lock-add-priority-faces)
6323 ;; Tags
6324 '(org-font-lock-add-tag-faces)
6325 ;; Tags groups
6326 (if (and org-group-tags org-tag-groups-alist)
6327 (list (concat org-outline-regexp-bol ".+\\(:"
6328 (regexp-opt (mapcar 'car org-tag-groups-alist))
6329 ":\\).*$")
6330 '(1 'org-tag-group prepend)))
6331 ;; Special keywords
6332 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6333 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6334 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6335 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6336 ;; Emphasis
6337 (if em
6338 (if (featurep 'xemacs)
6339 '(org-do-emphasis-faces (0 nil append))
6340 '(org-do-emphasis-faces)))
6341 ;; Checkboxes
6342 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6343 1 'org-checkbox prepend)
6344 (if (cdr (assq 'checkbox org-list-automatic-rules))
6345 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6346 (0 (org-get-checkbox-statistics-face) t)))
6347 ;; Description list items
6348 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6349 1 'org-list-dt prepend)
6350 ;; ARCHIVEd headings
6351 (list (concat
6352 org-outline-regexp-bol
6353 "\\(.*:" org-archive-tag ":.*\\)")
6354 '(1 'org-archived prepend))
6355 ;; Specials
6356 '(org-do-latex-and-related)
6357 '(org-fontify-entities)
6358 '(org-raise-scripts)
6359 ;; Code
6360 '(org-activate-code (1 'org-code t))
6361 ;; COMMENT
6362 (list (format
6363 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6364 org-todo-regexp
6365 org-comment-string)
6366 '(9 'org-special-keyword t))
6367 ;; Blocks and meta lines
6368 '(org-fontify-meta-lines-and-blocks))))
6369 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6370 (run-hooks 'org-font-lock-set-keywords-hook)
6371 ;; Now set the full font-lock-keywords
6372 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6373 (org-set-local 'font-lock-defaults
6374 '(org-font-lock-keywords t nil nil backward-paragraph))
6375 (kill-local-variable 'font-lock-keywords) nil))
6377 (defun org-toggle-pretty-entities ()
6378 "Toggle the composition display of entities as UTF8 characters."
6379 (interactive)
6380 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6381 (org-restart-font-lock)
6382 (if org-pretty-entities
6383 (message "Entities are now displayed as UTF8 characters")
6384 (save-restriction
6385 (widen)
6386 (org-decompose-region (point-min) (point-max))
6387 (message "Entities are now displayed as plain text"))))
6389 (defvar org-custom-properties-overlays nil
6390 "List of overlays used for custom properties.")
6391 (make-variable-buffer-local 'org-custom-properties-overlays)
6393 (defun org-toggle-custom-properties-visibility ()
6394 "Display or hide properties in `org-custom-properties'."
6395 (interactive)
6396 (if org-custom-properties-overlays
6397 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6398 (setq org-custom-properties-overlays nil))
6399 (unless (not org-custom-properties)
6400 (save-excursion
6401 (save-restriction
6402 (widen)
6403 (goto-char (point-min))
6404 (while (re-search-forward org-property-re nil t)
6405 (mapc (lambda(p)
6406 (when (equal p (substring (match-string 1) 1 -1))
6407 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6408 (overlay-put o 'invisible t)
6409 (overlay-put o 'org-custom-property t)
6410 (push o org-custom-properties-overlays))))
6411 org-custom-properties)))))))
6413 (defun org-fontify-entities (limit)
6414 "Find an entity to fontify."
6415 (let (ee)
6416 (when org-pretty-entities
6417 (catch 'match
6418 (while (re-search-forward
6419 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6420 limit t)
6421 (if (and (not (org-in-indented-comment-line))
6422 (setq ee (org-entity-get (match-string 1)))
6423 (= (length (nth 6 ee)) 1))
6424 (let*
6425 ((end (if (equal (match-string 2) "{}")
6426 (match-end 2)
6427 (match-end 1))))
6428 (add-text-properties
6429 (match-beginning 0) end
6430 (list 'font-lock-fontified t))
6431 (compose-region (match-beginning 0) end
6432 (nth 6 ee) nil)
6433 (backward-char 1)
6434 (throw 'match t))))
6435 nil))))
6437 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6438 "Fontify string S like in Org-mode."
6439 (with-temp-buffer
6440 (insert s)
6441 (let ((org-odd-levels-only odd-levels))
6442 (org-mode)
6443 (font-lock-fontify-buffer)
6444 (buffer-string))))
6446 (defvar org-m nil)
6447 (defvar org-l nil)
6448 (defvar org-f nil)
6449 (defun org-get-level-face (n)
6450 "Get the right face for match N in font-lock matching of headlines."
6451 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6452 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6453 (if org-cycle-level-faces
6454 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6455 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6456 (cond
6457 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6458 ((eq n 2) org-f)
6459 (t (if org-level-color-stars-only nil org-f))))
6462 (defun org-get-todo-face (kwd)
6463 "Get the right face for a TODO keyword KWD.
6464 If KWD is a number, get the corresponding match group."
6465 (if (numberp kwd) (setq kwd (match-string kwd)))
6466 (or (org-face-from-face-or-color
6467 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6468 (and (member kwd org-done-keywords) 'org-done)
6469 'org-todo))
6471 (defun org-face-from-face-or-color (context inherit face-or-color)
6472 "Create a face list that inherits INHERIT, but sets the foreground color.
6473 When FACE-OR-COLOR is not a string, just return it."
6474 (if (stringp face-or-color)
6475 (list :inherit inherit
6476 (cdr (assoc context org-faces-easy-properties))
6477 face-or-color)
6478 face-or-color))
6480 (defun org-font-lock-add-tag-faces (limit)
6481 "Add the special tag faces."
6482 (when (and org-tag-faces org-tags-special-faces-re)
6483 (while (re-search-forward org-tags-special-faces-re limit t)
6484 (add-text-properties (match-beginning 1) (match-end 1)
6485 (list 'face (org-get-tag-face 1)
6486 'font-lock-fontified t))
6487 (backward-char 1))))
6489 (defun org-font-lock-add-priority-faces (limit)
6490 "Add the special priority faces."
6491 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6492 (when (save-match-data (org-at-heading-p))
6493 (add-text-properties
6494 (match-beginning 0) (match-end 0)
6495 (list 'face (or (org-face-from-face-or-color
6496 'priority 'org-priority
6497 (cdr (assoc (char-after (match-beginning 1))
6498 org-priority-faces)))
6499 'org-priority)
6500 'font-lock-fontified t)))))
6502 (defun org-get-tag-face (kwd)
6503 "Get the right face for a TODO keyword KWD.
6504 If KWD is a number, get the corresponding match group."
6505 (if (numberp kwd) (setq kwd (match-string kwd)))
6506 (or (org-face-from-face-or-color
6507 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6508 'org-tag))
6510 (defun org-unfontify-region (beg end &optional maybe_loudly)
6511 "Remove fontification and activation overlays from links."
6512 (font-lock-default-unfontify-region beg end)
6513 (let* ((buffer-undo-list t)
6514 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6515 (inhibit-modification-hooks t)
6516 deactivate-mark buffer-file-name buffer-file-truename)
6517 (org-decompose-region beg end)
6518 (remove-text-properties beg end
6519 '(mouse-face t keymap t org-linked-text t
6520 invisible t intangible t
6521 org-emphasis t))
6522 (org-remove-font-lock-display-properties beg end)))
6524 (defconst org-script-display '(((raise -0.3) (height 0.7))
6525 ((raise 0.3) (height 0.7))
6526 ((raise -0.5))
6527 ((raise 0.5)))
6528 "Display properties for showing superscripts and subscripts.")
6530 (defun org-remove-font-lock-display-properties (beg end)
6531 "Remove specific display properties that have been added by font lock.
6532 The will remove the raise properties that are used to show superscripts
6533 and subscripts."
6534 (let (next prop)
6535 (while (< beg end)
6536 (setq next (next-single-property-change beg 'display nil end)
6537 prop (get-text-property beg 'display))
6538 (if (member prop org-script-display)
6539 (put-text-property beg next 'display nil))
6540 (setq beg next))))
6542 (defun org-raise-scripts (limit)
6543 "Add raise properties to sub/superscripts."
6544 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6545 (if (re-search-forward
6546 (if (eq org-use-sub-superscripts t)
6547 org-match-substring-regexp
6548 org-match-substring-with-braces-regexp)
6549 limit t)
6550 (let* ((pos (point)) table-p comment-p
6551 (mpos (match-beginning 3))
6552 (emph-p (get-text-property mpos 'org-emphasis))
6553 (link-p (get-text-property mpos 'mouse-face))
6554 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6555 (goto-char (point-at-bol))
6556 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6557 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6558 (goto-char pos)
6559 ;; Handle a_b^c
6560 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6561 (if (or comment-p emph-p link-p keyw-p)
6563 (put-text-property (match-beginning 3) (match-end 0)
6564 'display
6565 (if (equal (char-after (match-beginning 2)) ?^)
6566 (nth (if table-p 3 1) org-script-display)
6567 (nth (if table-p 2 0) org-script-display)))
6568 (add-text-properties (match-beginning 2) (match-end 2)
6569 (list 'invisible t
6570 'org-dwidth t 'org-dwidth-n 1))
6571 (if (and (eq (char-after (match-beginning 3)) ?{)
6572 (eq (char-before (match-end 3)) ?}))
6573 (progn
6574 (add-text-properties
6575 (match-beginning 3) (1+ (match-beginning 3))
6576 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6577 (add-text-properties
6578 (1- (match-end 3)) (match-end 3)
6579 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6580 t)))))
6582 ;;;; Visibility cycling, including org-goto and indirect buffer
6584 ;;; Cycling
6586 (defvar org-cycle-global-status nil)
6587 (make-variable-buffer-local 'org-cycle-global-status)
6588 (put 'org-cycle-global-status 'org-state t)
6589 (defvar org-cycle-subtree-status nil)
6590 (make-variable-buffer-local 'org-cycle-subtree-status)
6591 (put 'org-cycle-subtree-status 'org-state t)
6593 (defvar org-inlinetask-min-level)
6595 (defun org-unlogged-message (&rest args)
6596 "Display a message, but avoid logging it in the *Messages* buffer."
6597 (let ((message-log-max nil))
6598 (apply 'message args)))
6600 ;;;###autoload
6601 (defun org-cycle (&optional arg)
6602 "TAB-action and visibility cycling for Org-mode.
6604 This is the command invoked in Org-mode by the TAB key. Its main purpose
6605 is outline visibility cycling, but it also invokes other actions
6606 in special contexts.
6608 - When this function is called with a prefix argument, rotate the entire
6609 buffer through 3 states (global cycling)
6610 1. OVERVIEW: Show only top-level headlines.
6611 2. CONTENTS: Show all headlines of all levels, but no body text.
6612 3. SHOW ALL: Show everything.
6613 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6614 determined by the variable `org-startup-folded', and by any VISIBILITY
6615 properties in the buffer.
6616 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6617 including any drawers.
6619 - When inside a table, re-align the table and move to the next field.
6621 - When point is at the beginning of a headline, rotate the subtree started
6622 by this line through 3 different states (local cycling)
6623 1. FOLDED: Only the main headline is shown.
6624 2. CHILDREN: The main headline and the direct children are shown.
6625 From this state, you can move to one of the children
6626 and zoom in further.
6627 3. SUBTREE: Show the entire subtree, including body text.
6628 If there is no subtree, switch directly from CHILDREN to FOLDED.
6630 - When point is at the beginning of an empty headline and the variable
6631 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6632 of the headline by demoting and promoting it to likely levels. This
6633 speeds up creation document structure by pressing TAB once or several
6634 times right after creating a new headline.
6636 - When there is a numeric prefix, go up to a heading with level ARG, do
6637 a `show-subtree' and return to the previous cursor position. If ARG
6638 is negative, go up that many levels.
6640 - When point is not at the beginning of a headline, execute the global
6641 binding for TAB, which is re-indenting the line. See the option
6642 `org-cycle-emulate-tab' for details.
6644 - Special case: if point is at the beginning of the buffer and there is
6645 no headline in line 1, this function will act as if called with prefix arg
6646 (C-u TAB, same as S-TAB) also when called without prefix arg.
6647 But only if also the variable `org-cycle-global-at-bob' is t."
6648 (interactive "P")
6649 (org-load-modules-maybe)
6650 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6651 (and org-cycle-level-after-item/entry-creation
6652 (or (org-cycle-level)
6653 (org-cycle-item-indentation))))
6654 (let* ((limit-level
6655 (or org-cycle-max-level
6656 (and (boundp 'org-inlinetask-min-level)
6657 org-inlinetask-min-level
6658 (1- org-inlinetask-min-level))))
6659 (nstars (and limit-level
6660 (if org-odd-levels-only
6661 (and limit-level (1- (* limit-level 2)))
6662 limit-level)))
6663 (org-outline-regexp
6664 (if (not (derived-mode-p 'org-mode))
6665 outline-regexp
6666 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6667 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6668 (not (looking-at org-outline-regexp))))
6669 (org-cycle-hook
6670 (if bob-special
6671 (delq 'org-optimize-window-after-visibility-change
6672 (copy-sequence org-cycle-hook))
6673 org-cycle-hook))
6674 (pos (point)))
6676 (if (or bob-special (equal arg '(4)))
6677 ;; special case: use global cycling
6678 (setq arg t))
6680 (cond
6682 ((equal arg '(16))
6683 (setq last-command 'dummy)
6684 (org-set-startup-visibility)
6685 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6687 ((equal arg '(64))
6688 (show-all)
6689 (org-unlogged-message "Entire buffer visible, including drawers"))
6691 ;; Try cdlatex TAB completion
6692 ((org-try-cdlatex-tab))
6694 ;; Table: enter it or move to the next field.
6695 ((org-at-table-p 'any)
6696 (if (org-at-table.el-p)
6697 (message "Use C-c ' to edit table.el tables")
6698 (if arg (org-table-edit-field t)
6699 (org-table-justify-field-maybe)
6700 (call-interactively 'org-table-next-field))))
6702 ((run-hook-with-args-until-success
6703 'org-tab-after-check-for-table-hook))
6705 ;; Global cycling: delegate to `org-cycle-internal-global'.
6706 ((eq arg t) (org-cycle-internal-global))
6708 ;; Drawers: delegate to `org-flag-drawer'.
6709 ((save-excursion
6710 (beginning-of-line 1)
6711 (looking-at org-drawer-regexp))
6712 (org-flag-drawer ; toggle block visibility
6713 (not (get-char-property (match-end 0) 'invisible))))
6715 ;; Show-subtree, ARG levels up from here.
6716 ((integerp arg)
6717 (save-excursion
6718 (org-back-to-heading)
6719 (outline-up-heading (if (< arg 0) (- arg)
6720 (- (funcall outline-level) arg)))
6721 (org-show-subtree)))
6723 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6724 ((and (featurep 'org-inlinetask)
6725 (org-inlinetask-at-task-p)
6726 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6727 (org-inlinetask-toggle-visibility))
6729 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6730 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6731 (save-excursion (beginning-of-line 1)
6732 (looking-at org-outline-regexp)))
6733 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6734 (org-cycle-internal-local))
6736 ;; From there: TAB emulation and template completion.
6737 (buffer-read-only (org-back-to-heading))
6739 ((run-hook-with-args-until-success
6740 'org-tab-after-check-for-cycling-hook))
6742 ((org-try-structure-completion))
6744 ((run-hook-with-args-until-success
6745 'org-tab-before-tab-emulation-hook))
6747 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6748 (or (not (bolp))
6749 (not (looking-at org-outline-regexp))))
6750 (call-interactively (global-key-binding "\t")))
6752 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6753 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6754 (or (and (eq org-cycle-emulate-tab 'white)
6755 (= (match-end 0) (point-at-eol)))
6756 (and (eq org-cycle-emulate-tab 'whitestart)
6757 (>= (match-end 0) pos))))
6759 (eq org-cycle-emulate-tab t))
6760 (call-interactively (global-key-binding "\t")))
6762 (t (save-excursion
6763 (org-back-to-heading)
6764 (org-cycle)))))))
6766 (defun org-cycle-internal-global ()
6767 "Do the global cycling action."
6768 ;; Hack to avoid display of messages for .org attachments in Gnus
6769 (let ((ga (string-match "\\*fontification" (buffer-name))))
6770 (cond
6771 ((and (eq last-command this-command)
6772 (eq org-cycle-global-status 'overview))
6773 ;; We just created the overview - now do table of contents
6774 ;; This can be slow in very large buffers, so indicate action
6775 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6776 (unless ga (org-unlogged-message "CONTENTS..."))
6777 (org-content)
6778 (unless ga (org-unlogged-message "CONTENTS...done"))
6779 (setq org-cycle-global-status 'contents)
6780 (run-hook-with-args 'org-cycle-hook 'contents))
6782 ((and (eq last-command this-command)
6783 (eq org-cycle-global-status 'contents))
6784 ;; We just showed the table of contents - now show everything
6785 (run-hook-with-args 'org-pre-cycle-hook 'all)
6786 (show-all)
6787 (unless ga (org-unlogged-message "SHOW ALL"))
6788 (setq org-cycle-global-status 'all)
6789 (run-hook-with-args 'org-cycle-hook 'all))
6792 ;; Default action: go to overview
6793 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6794 (org-overview)
6795 (unless ga (org-unlogged-message "OVERVIEW"))
6796 (setq org-cycle-global-status 'overview)
6797 (run-hook-with-args 'org-cycle-hook 'overview)))))
6799 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6801 (defun org-cycle-internal-local ()
6802 "Do the local cycling action."
6803 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6804 ;; First, determine end of headline (EOH), end of subtree or item
6805 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6806 (save-excursion
6807 (if (org-at-item-p)
6808 (progn
6809 (beginning-of-line)
6810 (setq struct (org-list-struct))
6811 (setq eoh (point-at-eol))
6812 (setq eos (org-list-get-item-end-before-blank (point) struct))
6813 (setq has-children (org-list-has-child-p (point) struct)))
6814 (org-back-to-heading)
6815 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6816 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6817 (setq has-children
6818 (or (save-excursion
6819 (let ((level (funcall outline-level)))
6820 (outline-next-heading)
6821 (and (org-at-heading-p t)
6822 (> (funcall outline-level) level))))
6823 (save-excursion
6824 (org-list-search-forward (org-item-beginning-re) eos t)))))
6825 ;; Determine end invisible part of buffer (EOL)
6826 (beginning-of-line 2)
6827 ;; XEmacs doesn't have `next-single-char-property-change'
6828 (if (featurep 'xemacs)
6829 (while (and (not (eobp)) ;; this is like `next-line'
6830 (get-char-property (1- (point)) 'invisible))
6831 (beginning-of-line 2))
6832 (while (and (not (eobp)) ;; this is like `next-line'
6833 (get-char-property (1- (point)) 'invisible))
6834 (goto-char (next-single-char-property-change (point) 'invisible))
6835 (and (eolp) (beginning-of-line 2))))
6836 (setq eol (point)))
6837 ;; Find out what to do next and set `this-command'
6838 (cond
6839 ((= eos eoh)
6840 ;; Nothing is hidden behind this heading
6841 (unless (org-before-first-heading-p)
6842 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6843 (org-unlogged-message "EMPTY ENTRY")
6844 (setq org-cycle-subtree-status nil)
6845 (save-excursion
6846 (goto-char eos)
6847 (outline-next-heading)
6848 (if (outline-invisible-p) (org-flag-heading nil))))
6849 ((and (or (>= eol eos)
6850 (not (string-match "\\S-" (buffer-substring eol eos))))
6851 (or has-children
6852 (not (setq children-skipped
6853 org-cycle-skip-children-state-if-no-children))))
6854 ;; Entire subtree is hidden in one line: children view
6855 (unless (org-before-first-heading-p)
6856 (run-hook-with-args 'org-pre-cycle-hook 'children))
6857 (if (org-at-item-p)
6858 (org-list-set-item-visibility (point-at-bol) struct 'children)
6859 (org-show-entry)
6860 (org-with-limited-levels (show-children))
6861 ;; FIXME: This slows down the func way too much.
6862 ;; How keep drawers hidden in subtree anyway?
6863 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6864 ;; (org-cycle-hide-drawers 'subtree))
6866 ;; Fold every list in subtree to top-level items.
6867 (when (eq org-cycle-include-plain-lists 'integrate)
6868 (save-excursion
6869 (org-back-to-heading)
6870 (while (org-list-search-forward (org-item-beginning-re) eos t)
6871 (beginning-of-line 1)
6872 (let* ((struct (org-list-struct))
6873 (prevs (org-list-prevs-alist struct))
6874 (end (org-list-get-bottom-point struct)))
6875 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6876 (org-list-get-all-items (point) struct prevs))
6877 (goto-char (if (< end eos) end eos)))))))
6878 (org-unlogged-message "CHILDREN")
6879 (save-excursion
6880 (goto-char eos)
6881 (outline-next-heading)
6882 (if (outline-invisible-p) (org-flag-heading nil)))
6883 (setq org-cycle-subtree-status 'children)
6884 (unless (org-before-first-heading-p)
6885 (run-hook-with-args 'org-cycle-hook 'children)))
6886 ((or children-skipped
6887 (and (eq last-command this-command)
6888 (eq org-cycle-subtree-status 'children)))
6889 ;; We just showed the children, or no children are there,
6890 ;; now show everything.
6891 (unless (org-before-first-heading-p)
6892 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6893 (outline-flag-region eoh eos nil)
6894 (org-unlogged-message
6895 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6896 (setq org-cycle-subtree-status 'subtree)
6897 (unless (org-before-first-heading-p)
6898 (run-hook-with-args 'org-cycle-hook 'subtree)))
6900 ;; Default action: hide the subtree.
6901 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6902 (outline-flag-region eoh eos t)
6903 (org-unlogged-message "FOLDED")
6904 (setq org-cycle-subtree-status 'folded)
6905 (unless (org-before-first-heading-p)
6906 (run-hook-with-args 'org-cycle-hook 'folded))))))
6908 ;;;###autoload
6909 (defun org-global-cycle (&optional arg)
6910 "Cycle the global visibility. For details see `org-cycle'.
6911 With \\[universal-argument] prefix arg, switch to startup visibility.
6912 With a numeric prefix, show all headlines up to that level."
6913 (interactive "P")
6914 (let ((org-cycle-include-plain-lists
6915 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6916 (cond
6917 ((integerp arg)
6918 (show-all)
6919 (hide-sublevels arg)
6920 (setq org-cycle-global-status 'contents))
6921 ((equal arg '(4))
6922 (org-set-startup-visibility)
6923 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6925 (org-cycle '(4))))))
6927 (defun org-set-startup-visibility ()
6928 "Set the visibility required by startup options and properties."
6929 (cond
6930 ((eq org-startup-folded t)
6931 (org-overview))
6932 ((eq org-startup-folded 'content)
6933 (org-content))
6934 ((or (eq org-startup-folded 'showeverything)
6935 (eq org-startup-folded nil))
6936 (show-all)))
6937 (unless (eq org-startup-folded 'showeverything)
6938 (if org-hide-block-startup (org-hide-block-all))
6939 (org-set-visibility-according-to-property 'no-cleanup)
6940 (org-cycle-hide-archived-subtrees 'all)
6941 (org-cycle-hide-drawers 'all)
6942 (org-cycle-show-empty-lines t)))
6944 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6945 "Switch subtree visibilities according to :VISIBILITY: property."
6946 (interactive)
6947 (let (org-show-entry-below state)
6948 (save-excursion
6949 (goto-char (point-min))
6950 (while (re-search-forward
6951 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6952 nil t)
6953 (setq state (match-string 1))
6954 (save-excursion
6955 (org-back-to-heading t)
6956 (hide-subtree)
6957 (org-reveal)
6958 (cond
6959 ((equal state '("fold" "folded"))
6960 (hide-subtree))
6961 ((equal state "children")
6962 (org-show-hidden-entry)
6963 (show-children))
6964 ((equal state "content")
6965 (save-excursion
6966 (save-restriction
6967 (org-narrow-to-subtree)
6968 (org-content))))
6969 ((member state '("all" "showall"))
6970 (show-subtree)))))
6971 (unless no-cleanup
6972 (org-cycle-hide-archived-subtrees 'all)
6973 (org-cycle-hide-drawers 'all)
6974 (org-cycle-show-empty-lines 'all)))))
6976 ;; This function uses outline-regexp instead of the more fundamental
6977 ;; org-outline-regexp so that org-cycle-global works outside of Org
6978 ;; buffers, where outline-regexp is needed.
6979 (defun org-overview ()
6980 "Switch to overview mode, showing only top-level headlines.
6981 This shows all headlines with a level equal or greater than the level
6982 of the first headline in the buffer. This is important, because if the
6983 first headline is not level one, then (hide-sublevels 1) gives confusing
6984 results."
6985 (interactive)
6986 (save-excursion
6987 (let ((level
6988 (save-excursion
6989 (goto-char (point-min))
6990 (if (re-search-forward (concat "^" outline-regexp) nil t)
6991 (progn
6992 (goto-char (match-beginning 0))
6993 (funcall outline-level))))))
6994 (and level (hide-sublevels level)))))
6996 (defun org-content (&optional arg)
6997 "Show all headlines in the buffer, like a table of contents.
6998 With numerical argument N, show content up to level N."
6999 (interactive "P")
7000 (org-overview)
7001 (save-excursion
7002 ;; Visit all headings and show their offspring
7003 (and (integerp arg) (org-overview))
7004 (goto-char (point-max))
7005 (catch 'exit
7006 (while (and (progn (condition-case nil
7007 (outline-previous-visible-heading 1)
7008 (error (goto-char (point-min))))
7010 (looking-at org-outline-regexp))
7011 (if (integerp arg)
7012 (show-children (1- arg))
7013 (show-branches))
7014 (if (bobp) (throw 'exit nil))))))
7016 (defun org-optimize-window-after-visibility-change (state)
7017 "Adjust the window after a change in outline visibility.
7018 This function is the default value of the hook `org-cycle-hook'."
7019 (when (get-buffer-window (current-buffer))
7020 (cond
7021 ((eq state 'content) nil)
7022 ((eq state 'all) nil)
7023 ((eq state 'folded) nil)
7024 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7025 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7027 (defun org-remove-empty-overlays-at (pos)
7028 "Remove outline overlays that do not contain non-white stuff."
7029 (mapc
7030 (lambda (o)
7031 (and (eq 'outline (overlay-get o 'invisible))
7032 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7033 (overlay-end o))))
7034 (delete-overlay o)))
7035 (overlays-at pos)))
7037 (defun org-clean-visibility-after-subtree-move ()
7038 "Fix visibility issues after moving a subtree."
7039 ;; First, find a reasonable region to look at:
7040 ;; Start two siblings above, end three below
7041 (let* ((beg (save-excursion
7042 (and (org-get-last-sibling)
7043 (org-get-last-sibling))
7044 (point)))
7045 (end (save-excursion
7046 (and (org-get-next-sibling)
7047 (org-get-next-sibling)
7048 (org-get-next-sibling))
7049 (if (org-at-heading-p)
7050 (point-at-eol)
7051 (point))))
7052 (level (looking-at "\\*+"))
7053 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7054 (save-excursion
7055 (save-restriction
7056 (narrow-to-region beg end)
7057 (when re
7058 ;; Properly fold already folded siblings
7059 (goto-char (point-min))
7060 (while (re-search-forward re nil t)
7061 (if (and (not (outline-invisible-p))
7062 (save-excursion
7063 (goto-char (point-at-eol)) (outline-invisible-p)))
7064 (hide-entry))))
7065 (org-cycle-show-empty-lines 'overview)
7066 (org-cycle-hide-drawers 'overview)))))
7068 (defun org-cycle-show-empty-lines (state)
7069 "Show empty lines above all visible headlines.
7070 The region to be covered depends on STATE when called through
7071 `org-cycle-hook'. Lisp program can use t for STATE to get the
7072 entire buffer covered. Note that an empty line is only shown if there
7073 are at least `org-cycle-separator-lines' empty lines before the headline."
7074 (when (not (= org-cycle-separator-lines 0))
7075 (save-excursion
7076 (let* ((n (abs org-cycle-separator-lines))
7077 (re (cond
7078 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7079 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7080 (t (let ((ns (number-to-string (- n 2))))
7081 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7082 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7083 beg end b e)
7084 (cond
7085 ((memq state '(overview contents t))
7086 (setq beg (point-min) end (point-max)))
7087 ((memq state '(children folded))
7088 (setq beg (point) end (progn (org-end-of-subtree t t)
7089 (beginning-of-line 2)
7090 (point)))))
7091 (when beg
7092 (goto-char beg)
7093 (while (re-search-forward re end t)
7094 (unless (get-char-property (match-end 1) 'invisible)
7095 (setq e (match-end 1))
7096 (if (< org-cycle-separator-lines 0)
7097 (setq b (save-excursion
7098 (goto-char (match-beginning 0))
7099 (org-back-over-empty-lines)
7100 (if (save-excursion
7101 (goto-char (max (point-min) (1- (point))))
7102 (org-at-heading-p))
7103 (1- (point))
7104 (point))))
7105 (setq b (match-beginning 1)))
7106 (outline-flag-region b e nil)))))))
7107 ;; Never hide empty lines at the end of the file.
7108 (save-excursion
7109 (goto-char (point-max))
7110 (outline-previous-heading)
7111 (outline-end-of-heading)
7112 (if (and (looking-at "[ \t\n]+")
7113 (= (match-end 0) (point-max)))
7114 (outline-flag-region (point) (match-end 0) nil))))
7116 (defun org-show-empty-lines-in-parent ()
7117 "Move to the parent and re-show empty lines before visible headlines."
7118 (save-excursion
7119 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7120 (org-cycle-show-empty-lines context))))
7122 (defun org-files-list ()
7123 "Return `org-agenda-files' list, plus all open org-mode files.
7124 This is useful for operations that need to scan all of a user's
7125 open and agenda-wise Org files."
7126 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7127 (dolist (buf (buffer-list))
7128 (with-current-buffer buf
7129 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7130 (let ((file (expand-file-name (buffer-file-name))))
7131 (unless (member file files)
7132 (push file files))))))
7133 files))
7135 (defsubst org-entry-beginning-position ()
7136 "Return the beginning position of the current entry."
7137 (save-excursion (outline-back-to-heading t) (point)))
7139 (defsubst org-entry-end-position ()
7140 "Return the end position of the current entry."
7141 (save-excursion (outline-next-heading) (point)))
7143 (defun org-cycle-hide-drawers (state &optional exceptions)
7144 "Re-hide all drawers after a visibility state change.
7145 When non-nil, optional argument EXCEPTIONS is a list of strings
7146 specifying which drawers should not be hidden."
7147 (when (and (derived-mode-p 'org-mode)
7148 (not (memq state '(overview folded contents))))
7149 (save-excursion
7150 (let* ((globalp (memq state '(contents all)))
7151 (beg (if globalp (point-min) (point)))
7152 (end (if globalp (point-max)
7153 (if (eq state 'children)
7154 (save-excursion (outline-next-heading) (point))
7155 (org-end-of-subtree t)))))
7156 (goto-char beg)
7157 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7158 (unless (member-ignore-case (match-string 1) exceptions)
7159 (let ((drawer (org-element-at-point)))
7160 (when (memq (org-element-type drawer) '(drawer property-drawer))
7161 (org-flag-drawer t drawer)
7162 ;; Make sure to skip drawer entirely or we might flag
7163 ;; it another time when matching its ending line with
7164 ;; `org-drawer-regexp'.
7165 (goto-char (org-element-property :end drawer))))))))))
7167 (defun org-cycle-hide-inline-tasks (state)
7168 "Re-hide inline tasks when switching to 'contents or 'children
7169 visibility state."
7170 (case state
7171 (contents
7172 (when (org-bound-and-true-p org-inlinetask-min-level)
7173 (hide-sublevels (1- org-inlinetask-min-level))))
7174 (children
7175 (when (featurep 'org-inlinetask)
7176 (save-excursion
7177 (while (and (outline-next-heading)
7178 (org-inlinetask-at-task-p))
7179 (org-inlinetask-toggle-visibility)
7180 (org-inlinetask-goto-end)))))))
7182 (defun org-flag-drawer (flag &optional element)
7183 "When FLAG is non-nil, hide the drawer we are at.
7184 Otherwise make it visible. When optional argument ELEMENT is
7185 a parsed drawer, as returned by `org-element-at-point', hide or
7186 show that drawer instead."
7187 (when (save-excursion
7188 (beginning-of-line)
7189 (org-looking-at-p org-drawer-regexp))
7190 (let ((drawer (or element (org-element-at-point))))
7191 (when (memq (org-element-type drawer) '(drawer property-drawer))
7192 (let ((post (org-element-property :post-affiliated drawer)))
7193 (save-excursion
7194 (outline-flag-region
7195 (progn (goto-char post) (line-end-position))
7196 (progn (goto-char (org-element-property :end drawer))
7197 (skip-chars-backward " \r\t\n")
7198 (line-end-position))
7199 flag))
7200 ;; When the drawer is hidden away, make sure point lies in
7201 ;; a visible part of the buffer.
7202 (when (and flag (> (line-beginning-position) post))
7203 (goto-char post)))))))
7205 (defun org-subtree-end-visible-p ()
7206 "Is the end of the current subtree visible?"
7207 (pos-visible-in-window-p
7208 (save-excursion (org-end-of-subtree t) (point))))
7210 (defun org-first-headline-recenter (&optional N)
7211 "Move cursor to the first headline and recenter the headline.
7212 Optional argument N means put the headline into the Nth line of the window."
7213 (goto-char (point-min))
7214 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7215 (beginning-of-line)
7216 (recenter (prefix-numeric-value N))))
7218 ;;; Saving and restoring visibility
7220 (defun org-outline-overlay-data (&optional use-markers)
7221 "Return a list of the locations of all outline overlays.
7222 These are overlays with the `invisible' property value `outline'.
7223 The return value is a list of cons cells, with start and stop
7224 positions for each overlay.
7225 If USE-MARKERS is set, return the positions as markers."
7226 (let (beg end)
7227 (save-excursion
7228 (save-restriction
7229 (widen)
7230 (delq nil
7231 (mapcar (lambda (o)
7232 (when (eq (overlay-get o 'invisible) 'outline)
7233 (setq beg (overlay-start o)
7234 end (overlay-end o))
7235 (and beg end (> end beg)
7236 (if use-markers
7237 (cons (copy-marker beg)
7238 (copy-marker end t))
7239 (cons beg end)))))
7240 (overlays-in (point-min) (point-max))))))))
7242 (defun org-set-outline-overlay-data (data)
7243 "Create visibility overlays for all positions in DATA.
7244 DATA should have been made by `org-outline-overlay-data'."
7245 (let (o)
7246 (save-excursion
7247 (save-restriction
7248 (widen)
7249 (show-all)
7250 (mapc (lambda (c)
7251 (outline-flag-region (car c) (cdr c) t))
7252 data)))))
7254 ;;; Folding of blocks
7256 (defvar org-hide-block-overlays nil
7257 "Overlays hiding blocks.")
7258 (make-variable-buffer-local 'org-hide-block-overlays)
7260 (defun org-block-map (function &optional start end)
7261 "Call FUNCTION at the head of all source blocks in the current buffer.
7262 Optional arguments START and END can be used to limit the range."
7263 (let ((start (or start (point-min)))
7264 (end (or end (point-max))))
7265 (save-excursion
7266 (goto-char start)
7267 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7268 (save-excursion
7269 (save-match-data
7270 (goto-char (match-beginning 0))
7271 (funcall function)))))))
7273 (defun org-hide-block-toggle-all ()
7274 "Toggle the visibility of all blocks in the current buffer."
7275 (org-block-map #'org-hide-block-toggle))
7277 (defun org-hide-block-all ()
7278 "Fold all blocks in the current buffer."
7279 (interactive)
7280 (org-show-block-all)
7281 (org-block-map #'org-hide-block-toggle-maybe))
7283 (defun org-show-block-all ()
7284 "Unfold all blocks in the current buffer."
7285 (interactive)
7286 (mapc 'delete-overlay org-hide-block-overlays)
7287 (setq org-hide-block-overlays nil))
7289 (defun org-hide-block-toggle-maybe ()
7290 "Toggle visibility of block at point."
7291 (interactive)
7292 (let ((case-fold-search t))
7293 (if (save-excursion
7294 (beginning-of-line 1)
7295 (looking-at org-block-regexp))
7296 (progn (org-hide-block-toggle)
7297 t) ;; to signal that we took action
7298 nil))) ;; to signal that we did not
7300 (defun org-hide-block-toggle (&optional force)
7301 "Toggle the visibility of the current block."
7302 (interactive)
7303 (save-excursion
7304 (beginning-of-line)
7305 (if (re-search-forward org-block-regexp nil t)
7306 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7307 (end (match-end 0)) ;; end of entire body
7309 (if (memq t (mapcar (lambda (overlay)
7310 (eq (overlay-get overlay 'invisible)
7311 'org-hide-block))
7312 (overlays-at start)))
7313 (if (or (not force) (eq force 'off))
7314 (mapc (lambda (ov)
7315 (when (member ov org-hide-block-overlays)
7316 (setq org-hide-block-overlays
7317 (delq ov org-hide-block-overlays)))
7318 (when (eq (overlay-get ov 'invisible)
7319 'org-hide-block)
7320 (delete-overlay ov)))
7321 (overlays-at start)))
7322 (setq ov (make-overlay start end))
7323 (overlay-put ov 'invisible 'org-hide-block)
7324 ;; make the block accessible to isearch
7325 (overlay-put
7326 ov 'isearch-open-invisible
7327 (lambda (ov)
7328 (when (member ov org-hide-block-overlays)
7329 (setq org-hide-block-overlays
7330 (delq ov org-hide-block-overlays)))
7331 (when (eq (overlay-get ov 'invisible)
7332 'org-hide-block)
7333 (delete-overlay ov))))
7334 (push ov org-hide-block-overlays)))
7335 (user-error "Not looking at a source block"))))
7337 ;; org-tab-after-check-for-cycling-hook
7338 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7339 ;; Remove overlays when changing major mode
7340 (add-hook 'org-mode-hook
7341 (lambda () (org-add-hook 'change-major-mode-hook
7342 'org-show-block-all 'append 'local)))
7344 ;;; Org-goto
7346 (defvar org-goto-window-configuration nil)
7347 (defvar org-goto-marker nil)
7348 (defvar org-goto-map)
7349 (defun org-goto-map ()
7350 "Set the keymap `org-goto'."
7351 (setq org-goto-map
7352 (let ((map (make-sparse-keymap)))
7353 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7354 mouse-drag-region universal-argument org-occur))
7355 cmd)
7356 (while (setq cmd (pop cmds))
7357 (substitute-key-definition cmd cmd map global-map)))
7358 (suppress-keymap map)
7359 (org-defkey map "\C-m" 'org-goto-ret)
7360 (org-defkey map [(return)] 'org-goto-ret)
7361 (org-defkey map [(left)] 'org-goto-left)
7362 (org-defkey map [(right)] 'org-goto-right)
7363 (org-defkey map [(control ?g)] 'org-goto-quit)
7364 (org-defkey map "\C-i" 'org-cycle)
7365 (org-defkey map [(tab)] 'org-cycle)
7366 (org-defkey map [(down)] 'outline-next-visible-heading)
7367 (org-defkey map [(up)] 'outline-previous-visible-heading)
7368 (if org-goto-auto-isearch
7369 (if (fboundp 'define-key-after)
7370 (define-key-after map [t] 'org-goto-local-auto-isearch)
7371 nil)
7372 (org-defkey map "q" 'org-goto-quit)
7373 (org-defkey map "n" 'outline-next-visible-heading)
7374 (org-defkey map "p" 'outline-previous-visible-heading)
7375 (org-defkey map "f" 'outline-forward-same-level)
7376 (org-defkey map "b" 'outline-backward-same-level)
7377 (org-defkey map "u" 'outline-up-heading))
7378 (org-defkey map "/" 'org-occur)
7379 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7380 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7381 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7382 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7383 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7384 map)))
7386 (defconst org-goto-help
7387 "Browse buffer copy, to find location or copy text.%s
7388 RET=jump to location C-g=quit and return to previous location
7389 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7391 (defvar org-goto-start-pos) ; dynamically scoped parameter
7393 (defun org-goto (&optional alternative-interface)
7394 "Look up a different location in the current file, keeping current visibility.
7396 When you want look-up or go to a different location in a
7397 document, the fastest way is often to fold the entire buffer and
7398 then dive into the tree. This method has the disadvantage, that
7399 the previous location will be folded, which may not be what you
7400 want.
7402 This command works around this by showing a copy of the current
7403 buffer in an indirect buffer, in overview mode. You can dive
7404 into the tree in that copy, use org-occur and incremental search
7405 to find a location. When pressing RET or `Q', the command
7406 returns to the original buffer in which the visibility is still
7407 unchanged. After RET it will also jump to the location selected
7408 in the indirect buffer and expose the headline hierarchy above.
7410 With a prefix argument, use the alternative interface: e.g. if
7411 `org-goto-interface' is 'outline use 'outline-path-completion."
7412 (interactive "P")
7413 (org-goto-map)
7414 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7415 (org-refile-use-outline-path t)
7416 (org-refile-target-verify-function nil)
7417 (interface
7418 (if (not alternative-interface)
7419 org-goto-interface
7420 (if (eq org-goto-interface 'outline)
7421 'outline-path-completion
7422 'outline)))
7423 (org-goto-start-pos (point))
7424 (selected-point
7425 (if (eq interface 'outline)
7426 (car (org-get-location (current-buffer) org-goto-help))
7427 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7428 (org-refile-check-position pa)
7429 (nth 3 pa)))))
7430 (if selected-point
7431 (progn
7432 (org-mark-ring-push org-goto-start-pos)
7433 (goto-char selected-point)
7434 (if (or (outline-invisible-p) (org-invisible-p2))
7435 (org-show-context 'org-goto)))
7436 (message "Quit"))))
7438 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7439 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7440 (defvar org-goto-local-auto-isearch-map) ; defined below
7442 (defun org-get-location (buf help)
7443 "Let the user select a location in the Org-mode buffer BUF.
7444 This function uses a recursive edit. It returns the selected position
7445 or nil."
7446 (org-no-popups
7447 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7448 (isearch-hide-immediately nil)
7449 (isearch-search-fun-function
7450 (lambda () 'org-goto-local-search-headings))
7451 (org-goto-selected-point org-goto-exit-command))
7452 (save-excursion
7453 (save-window-excursion
7454 (delete-other-windows)
7455 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7456 (org-pop-to-buffer-same-window
7457 (condition-case nil
7458 (make-indirect-buffer (current-buffer) "*org-goto*")
7459 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7460 (with-output-to-temp-buffer "*Org Help*"
7461 (princ (format help (if org-goto-auto-isearch
7462 " Just type for auto-isearch."
7463 " n/p/f/b/u to navigate, q to quit."))))
7464 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7465 (setq buffer-read-only nil)
7466 (let ((org-startup-truncated t)
7467 (org-startup-folded nil)
7468 (org-startup-align-all-tables nil))
7469 (org-mode)
7470 (org-overview))
7471 (setq buffer-read-only t)
7472 (if (and (boundp 'org-goto-start-pos)
7473 (integer-or-marker-p org-goto-start-pos))
7474 (let ((org-show-hierarchy-above t)
7475 (org-show-siblings t)
7476 (org-show-following-heading t))
7477 (goto-char org-goto-start-pos)
7478 (and (outline-invisible-p) (org-show-context)))
7479 (goto-char (point-min)))
7480 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7481 (message "Select location and press RET")
7482 (use-local-map org-goto-map)
7483 (recursive-edit)))
7484 (kill-buffer "*org-goto*")
7485 (cons org-goto-selected-point org-goto-exit-command))))
7487 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7488 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7489 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7490 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7492 (defun org-goto-local-search-headings (string bound noerror)
7493 "Search and make sure that any matches are in headlines."
7494 (catch 'return
7495 (while (if isearch-forward
7496 (search-forward string bound noerror)
7497 (search-backward string bound noerror))
7498 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7499 (and (member :headline context)
7500 (not (member :tags context))))
7501 (throw 'return (point))))))
7503 (defun org-goto-local-auto-isearch ()
7504 "Start isearch."
7505 (interactive)
7506 (goto-char (point-min))
7507 (let ((keys (this-command-keys)))
7508 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7509 (isearch-mode t)
7510 (isearch-process-search-char (string-to-char keys)))))
7512 (defun org-goto-ret (&optional arg)
7513 "Finish `org-goto' by going to the new location."
7514 (interactive "P")
7515 (setq org-goto-selected-point (point)
7516 org-goto-exit-command 'return)
7517 (throw 'exit nil))
7519 (defun org-goto-left ()
7520 "Finish `org-goto' by going to the new location."
7521 (interactive)
7522 (if (org-at-heading-p)
7523 (progn
7524 (beginning-of-line 1)
7525 (setq org-goto-selected-point (point)
7526 org-goto-exit-command 'left)
7527 (throw 'exit nil))
7528 (user-error "Not on a heading")))
7530 (defun org-goto-right ()
7531 "Finish `org-goto' by going to the new location."
7532 (interactive)
7533 (if (org-at-heading-p)
7534 (progn
7535 (setq org-goto-selected-point (point)
7536 org-goto-exit-command 'right)
7537 (throw 'exit nil))
7538 (user-error "Not on a heading")))
7540 (defun org-goto-quit ()
7541 "Finish `org-goto' without cursor motion."
7542 (interactive)
7543 (setq org-goto-selected-point nil)
7544 (setq org-goto-exit-command 'quit)
7545 (throw 'exit nil))
7547 ;;; Indirect buffer display of subtrees
7549 (defvar org-indirect-dedicated-frame nil
7550 "This is the frame being used for indirect tree display.")
7551 (defvar org-last-indirect-buffer nil)
7553 (defun org-tree-to-indirect-buffer (&optional arg)
7554 "Create indirect buffer and narrow it to current subtree.
7555 With a numerical prefix ARG, go up to this level and then take that tree.
7556 If ARG is negative, go up that many levels.
7558 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7559 indirect buffer previously made with this command, to avoid proliferation of
7560 indirect buffers. However, when you call the command with a \
7561 \\[universal-argument] prefix, or
7562 when `org-indirect-buffer-display' is `new-frame', the last buffer
7563 is kept so that you can work with several indirect buffers at the same time.
7564 If `org-indirect-buffer-display' is `dedicated-frame', the \
7565 \\[universal-argument] prefix also
7566 requests that a new frame be made for the new buffer, so that the dedicated
7567 frame is not changed."
7568 (interactive "P")
7569 (let ((cbuf (current-buffer))
7570 (cwin (selected-window))
7571 (pos (point))
7572 beg end level heading ibuf)
7573 (save-excursion
7574 (org-back-to-heading t)
7575 (when (numberp arg)
7576 (setq level (org-outline-level))
7577 (if (< arg 0) (setq arg (+ level arg)))
7578 (while (> (setq level (org-outline-level)) arg)
7579 (org-up-heading-safe)))
7580 (setq beg (point)
7581 heading (org-get-heading))
7582 (org-end-of-subtree t t)
7583 (if (org-at-heading-p) (backward-char 1))
7584 (setq end (point)))
7585 (if (and (buffer-live-p org-last-indirect-buffer)
7586 (not (eq org-indirect-buffer-display 'new-frame))
7587 (not arg))
7588 (kill-buffer org-last-indirect-buffer))
7589 (setq ibuf (org-get-indirect-buffer cbuf heading)
7590 org-last-indirect-buffer ibuf)
7591 (cond
7592 ((or (eq org-indirect-buffer-display 'new-frame)
7593 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7594 (select-frame (make-frame))
7595 (delete-other-windows)
7596 (org-pop-to-buffer-same-window ibuf)
7597 (org-set-frame-title heading))
7598 ((eq org-indirect-buffer-display 'dedicated-frame)
7599 (raise-frame
7600 (select-frame (or (and org-indirect-dedicated-frame
7601 (frame-live-p org-indirect-dedicated-frame)
7602 org-indirect-dedicated-frame)
7603 (setq org-indirect-dedicated-frame (make-frame)))))
7604 (delete-other-windows)
7605 (org-pop-to-buffer-same-window ibuf)
7606 (org-set-frame-title (concat "Indirect: " heading)))
7607 ((eq org-indirect-buffer-display 'current-window)
7608 (org-pop-to-buffer-same-window ibuf))
7609 ((eq org-indirect-buffer-display 'other-window)
7610 (pop-to-buffer ibuf))
7611 (t (error "Invalid value")))
7612 (if (featurep 'xemacs)
7613 (save-excursion (org-mode) (turn-on-font-lock)))
7614 (narrow-to-region beg end)
7615 (show-all)
7616 (goto-char pos)
7617 (run-hook-with-args 'org-cycle-hook 'all)
7618 (and (window-live-p cwin) (select-window cwin))))
7620 (defun org-get-indirect-buffer (&optional buffer heading)
7621 (setq buffer (or buffer (current-buffer)))
7622 (let ((n 1) (base (buffer-name buffer)) bname)
7623 (while (buffer-live-p
7624 (get-buffer
7625 (setq bname
7626 (concat base "-"
7627 (if heading (concat heading "-" (number-to-string n))
7628 (number-to-string n))))))
7629 (setq n (1+ n)))
7630 (condition-case nil
7631 (make-indirect-buffer buffer bname 'clone)
7632 (error (make-indirect-buffer buffer bname)))))
7634 (defun org-set-frame-title (title)
7635 "Set the title of the current frame to the string TITLE."
7636 ;; FIXME: how to name a single frame in XEmacs???
7637 (unless (featurep 'xemacs)
7638 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7640 ;;;; Structure editing
7642 ;;; Inserting headlines
7644 (defun org-previous-line-empty-p (&optional next)
7645 "Is the previous line a blank line?
7646 When NEXT is non-nil, check the next line instead."
7647 (save-excursion
7648 (and (not (bobp))
7649 (or (beginning-of-line (if next 2 0)) t)
7650 (save-match-data
7651 (looking-at "[ \t]*$")))))
7653 (defun org-insert-heading (&optional arg invisible-ok)
7654 "Insert a new heading or item with same depth at point.
7656 If point is in a plain list and ARG is nil, add a new list item.
7658 With one universal prefix argument, insert a heading even when
7659 the point is within a list.
7661 With two universal prefix arguments, insert the heading at the
7662 end of the grandparent subtree. For example, if point is within
7663 a 2nd-level heading, then it will insert a 2nd-level heading at
7664 the end of the 1st-level parent heading.
7666 If point is at the beginning of a headline, insert a sibling
7667 before the current headline. If point is not at the beginning,
7668 split the line and create a new headline with the text in the
7669 current line after point \(see `org-M-RET-may-split-line' on how
7670 to modify this behavior).
7672 If point is at the beginning of a normal line, turn this line
7673 into a heading.
7675 When INVISIBLE-OK is set, stop at invisible headlines when going
7676 back. This is important for non-interactive uses of the
7677 command."
7678 (interactive "P")
7679 (if (org-called-interactively-p 'any) (org-reveal))
7680 (let ((itemp (org-in-item-p))
7681 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7682 (respect-content (or org-insert-heading-respect-content
7683 (equal arg '(4))))
7684 (initial-content "")
7685 (adjust-empty-lines t))
7687 (cond
7689 ((or (= (buffer-size) 0)
7690 (and (or (and (bolp)
7691 (not (save-excursion
7692 (and (ignore-errors (org-back-to-heading invisible-ok))
7693 (org-at-heading-p)))))
7694 (and (bolp) (not (looking-at org-outline-regexp-bol))))
7695 (or arg (not itemp))))
7696 ;; At beginning of buffer or so high up that only a heading
7697 ;; makes sense.
7698 (insert
7699 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7700 (if (org-in-src-block-p) ",* " "* "))
7701 (run-hooks 'org-insert-heading-hook))
7703 ((and itemp (not (equal arg '(4))))
7704 ;; Insert an item
7705 (org-insert-item))
7708 ;; Maybe move at the end of the subtree
7709 (when (equal arg '(16))
7710 (org-up-heading-safe)
7711 (org-end-of-subtree t))
7712 ;; Insert a heading
7713 (save-restriction
7714 (widen)
7715 (let* ((level nil)
7716 (on-heading (org-at-heading-p))
7717 (empty-line-p (if on-heading
7718 (org-previous-line-empty-p)
7719 ;; We will decide later
7720 nil))
7721 ;; Get a level string to fall back on
7722 (fix-level
7723 (if (org-before-first-heading-p) "*"
7724 (save-excursion
7725 (org-back-to-heading t)
7726 (if (org-previous-line-empty-p) (setq empty-line-p t))
7727 (looking-at org-outline-regexp)
7728 (make-string (1- (length (match-string 0))) ?*))))
7729 (stars
7730 (save-excursion
7731 (condition-case nil
7732 (progn
7733 (org-back-to-heading invisible-ok)
7734 (when (and (not on-heading)
7735 (featurep 'org-inlinetask)
7736 (integerp org-inlinetask-min-level)
7737 (>= (length (match-string 0))
7738 org-inlinetask-min-level))
7739 ;; Find a heading level before the inline task
7740 (while (and (setq level (org-up-heading-safe))
7741 (>= level org-inlinetask-min-level)))
7742 (if (org-at-heading-p)
7743 (org-back-to-heading invisible-ok)
7744 (error "This should not happen")))
7745 (unless (and (save-excursion
7746 (save-match-data
7747 (org-backward-heading-same-level
7748 1 invisible-ok))
7749 (= (point) (match-beginning 0)))
7750 (not (org-previous-line-empty-p t)))
7751 (setq empty-line-p (or empty-line-p
7752 (org-previous-line-empty-p))))
7753 (match-string 0))
7754 (error (or fix-level "* ")))))
7755 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7756 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7757 pos hide-previous previous-pos)
7759 ;; If we insert after content, move there and clean up whitespace
7760 (when (and respect-content
7761 (not (org-looking-at-p org-outline-regexp-bol)))
7762 (org-end-of-subtree nil t)
7763 (skip-chars-backward " \r\n")
7764 (and (not (looking-back "^\\*+"))
7765 (looking-at "[ \t]+") (replace-match ""))
7766 (unless (eobp) (forward-char 1))
7767 (when (looking-at "^\\*")
7768 (unless (bobp) (backward-char 1))
7769 (insert "\n")))
7771 ;; If we are splitting, grab the text that should be moved to the new headline
7772 (when may-split
7773 (if (org-on-heading-p)
7774 ;; This is a heading, we split intelligently (keeping tags)
7775 (let ((pos (point)))
7776 (goto-char (point-at-bol))
7777 (unless (looking-at org-complex-heading-regexp)
7778 (error "This should not happen"))
7779 (when (and (match-beginning 4)
7780 (> pos (match-beginning 4))
7781 (< pos (match-end 4)))
7782 (setq initial-content (buffer-substring pos (match-end 4)))
7783 (goto-char pos)
7784 (delete-region (point) (match-end 4))
7785 (if (looking-at "[ \t]*$")
7786 (replace-match "")
7787 (insert (make-string (length initial-content) ?\ )))
7788 (setq initial-content (org-trim initial-content)))
7789 (goto-char pos))
7790 ;; a normal line
7791 (unless (bolp)
7792 (setq initial-content (buffer-substring (point) (point-at-eol)))
7793 (delete-region (point) (point-at-eol))
7794 (setq initial-content (org-trim initial-content)))))
7796 ;; If we are at the beginning of the line, insert before it. Else after
7797 (cond
7798 ((and (bolp) (looking-at "[ \t]*$")))
7799 ((and (bolp) (not (looking-at "[ \t]*$")))
7800 (open-line 1))
7802 (goto-char (point-at-eol))
7803 (insert "\n")))
7805 ;; Insert the new heading
7806 (insert stars)
7807 (just-one-space)
7808 (insert initial-content)
7809 (when adjust-empty-lines
7810 (if (or (not blank)
7811 (and blank (not (org-previous-line-empty-p))))
7812 (org-N-empty-lines-before-current (if blank 1 0))))
7813 (run-hooks 'org-insert-heading-hook)))))))
7815 (defun org-N-empty-lines-before-current (N)
7816 "Make the number of empty lines before current exactly N.
7817 So this will delete or add empty lines."
7818 (save-excursion
7819 (goto-char (point-at-bol))
7820 (if (looking-back "\\s-+" nil 'greedy)
7821 (replace-match ""))
7822 (or (bobp) (insert "\n"))
7823 (while (> N 0)
7824 (insert "\n")
7825 (setq N (1- N)))))
7827 (defun org-get-heading (&optional no-tags no-todo)
7828 "Return the heading of the current entry, without the stars.
7829 When NO-TAGS is non-nil, don't include tags.
7830 When NO-TODO is non-nil, don't include TODO keywords."
7831 (save-excursion
7832 (org-back-to-heading t)
7833 (cond
7834 ((and no-tags no-todo)
7835 (looking-at org-complex-heading-regexp)
7836 (match-string 4))
7837 (no-tags
7838 (looking-at (concat org-outline-regexp
7839 "\\(.*?\\)"
7840 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7841 (match-string 1))
7842 (no-todo
7843 (looking-at org-todo-line-regexp)
7844 (match-string 3))
7845 (t (looking-at org-heading-regexp)
7846 (match-string 2)))))
7848 (defvar orgstruct-mode) ; defined below
7850 (defun org-heading-components ()
7851 "Return the components of the current heading.
7852 This is a list with the following elements:
7853 - the level as an integer
7854 - the reduced level, different if `org-odd-levels-only' is set.
7855 - the TODO keyword, or nil
7856 - the priority character, like ?A, or nil if no priority is given
7857 - the headline text itself, or the tags string if no headline text
7858 - the tags string, or nil."
7859 (save-excursion
7860 (org-back-to-heading t)
7861 (if (let (case-fold-search)
7862 (looking-at
7863 (if orgstruct-mode
7864 org-heading-regexp
7865 org-complex-heading-regexp)))
7866 (if orgstruct-mode
7867 (list (length (match-string 1))
7868 (org-reduced-level (length (match-string 1)))
7871 (match-string 2)
7872 nil)
7873 (list (length (match-string 1))
7874 (org-reduced-level (length (match-string 1)))
7875 (org-match-string-no-properties 2)
7876 (and (match-end 3) (aref (match-string 3) 2))
7877 (org-match-string-no-properties 4)
7878 (org-match-string-no-properties 5))))))
7880 (defun org-get-entry ()
7881 "Get the entry text, after heading, entire subtree."
7882 (save-excursion
7883 (org-back-to-heading t)
7884 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7886 (defun org-insert-heading-after-current ()
7887 "Insert a new heading with same level as current, after current subtree."
7888 (interactive)
7889 (org-back-to-heading)
7890 (org-insert-heading)
7891 (org-move-subtree-down)
7892 (end-of-line 1))
7894 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7895 "Insert heading with `org-insert-heading-respect-content' set to t."
7896 (interactive "P")
7897 (let ((org-insert-heading-respect-content t))
7898 (org-insert-heading '(4) invisible-ok)))
7900 (defun org-insert-todo-heading-respect-content (&optional force-state)
7901 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7902 (interactive "P")
7903 (let ((org-insert-heading-respect-content t))
7904 (org-insert-todo-heading force-state '(4))))
7906 (defun org-insert-todo-heading (arg &optional force-heading)
7907 "Insert a new heading with the same level and TODO state as current heading.
7908 If the heading has no TODO state, or if the state is DONE, use the first
7909 state (TODO by default). Also with one prefix arg, force first state. With
7910 two prefix args, force inserting at the end of the parent subtree."
7911 (interactive "P")
7912 (when (or force-heading (not (org-insert-item 'checkbox)))
7913 (org-insert-heading (or (and (equal arg '(16)) '(16))
7914 force-heading))
7915 (save-excursion
7916 (org-back-to-heading)
7917 (outline-previous-heading)
7918 (looking-at org-todo-line-regexp))
7919 (let*
7920 ((new-mark-x
7921 (if (or (equal arg '(4))
7922 (not (match-beginning 2))
7923 (member (match-string 2) org-done-keywords))
7924 (car org-todo-keywords-1)
7925 (match-string 2)))
7926 (new-mark
7928 (run-hook-with-args-until-success
7929 'org-todo-get-default-hook new-mark-x nil)
7930 new-mark-x)))
7931 (beginning-of-line 1)
7932 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7933 (if org-treat-insert-todo-heading-as-state-change
7934 (org-todo new-mark)
7935 (insert new-mark " "))))
7936 (when org-provide-todo-statistics
7937 (org-update-parent-todo-statistics))))
7939 (defun org-insert-subheading (arg)
7940 "Insert a new subheading and demote it.
7941 Works for outline headings and for plain lists alike."
7942 (interactive "P")
7943 (org-insert-heading arg)
7944 (cond
7945 ((org-at-heading-p) (org-do-demote))
7946 ((org-at-item-p) (org-indent-item))))
7948 (defun org-insert-todo-subheading (arg)
7949 "Insert a new subheading with TODO keyword or checkbox and demote it.
7950 Works for outline headings and for plain lists alike."
7951 (interactive "P")
7952 (org-insert-todo-heading arg)
7953 (cond
7954 ((org-at-heading-p) (org-do-demote))
7955 ((org-at-item-p) (org-indent-item))))
7957 ;;; Promotion and Demotion
7959 (defvar org-after-demote-entry-hook nil
7960 "Hook run after an entry has been demoted.
7961 The cursor will be at the beginning of the entry.
7962 When a subtree is being demoted, the hook will be called for each node.")
7964 (defvar org-after-promote-entry-hook nil
7965 "Hook run after an entry has been promoted.
7966 The cursor will be at the beginning of the entry.
7967 When a subtree is being promoted, the hook will be called for each node.")
7969 (defun org-promote-subtree ()
7970 "Promote the entire subtree.
7971 See also `org-promote'."
7972 (interactive)
7973 (save-excursion
7974 (org-with-limited-levels (org-map-tree 'org-promote)))
7975 (org-fix-position-after-promote))
7977 (defun org-demote-subtree ()
7978 "Demote the entire subtree. See `org-demote'.
7979 See also `org-promote'."
7980 (interactive)
7981 (save-excursion
7982 (org-with-limited-levels (org-map-tree 'org-demote)))
7983 (org-fix-position-after-promote))
7986 (defun org-do-promote ()
7987 "Promote the current heading higher up the tree.
7988 If the region is active in `transient-mark-mode', promote all headings
7989 in the region."
7990 (interactive)
7991 (save-excursion
7992 (if (org-region-active-p)
7993 (org-map-region 'org-promote (region-beginning) (region-end))
7994 (org-promote)))
7995 (org-fix-position-after-promote))
7997 (defun org-do-demote ()
7998 "Demote the current heading lower down the tree.
7999 If the region is active in `transient-mark-mode', demote all headings
8000 in the region."
8001 (interactive)
8002 (save-excursion
8003 (if (org-region-active-p)
8004 (org-map-region 'org-demote (region-beginning) (region-end))
8005 (org-demote)))
8006 (org-fix-position-after-promote))
8008 (defun org-fix-position-after-promote ()
8009 "Make sure that after pro/demotion cursor position is right."
8010 (let ((pos (point)))
8011 (when (save-excursion
8012 (beginning-of-line 1)
8013 (looking-at org-todo-line-regexp)
8014 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8015 (cond ((eobp) (insert " "))
8016 ((eolp) (insert " "))
8017 ((equal (char-after) ?\ ) (forward-char 1))))))
8019 (defun org-current-level ()
8020 "Return the level of the current entry, or nil if before the first headline.
8021 The level is the number of stars at the beginning of the headline."
8022 (save-excursion
8023 (org-with-limited-levels
8024 (if (ignore-errors (org-back-to-heading t))
8025 (funcall outline-level)))))
8027 (defun org-get-previous-line-level ()
8028 "Return the outline depth of the last headline before the current line.
8029 Returns 0 for the first headline in the buffer, and nil if before the
8030 first headline."
8031 (and (org-current-level)
8032 (or (and (/= (line-beginning-position) (point-min))
8033 (save-excursion (beginning-of-line 0) (org-current-level)))
8034 0)))
8036 (defun org-reduced-level (l)
8037 "Compute the effective level of a heading.
8038 This takes into account the setting of `org-odd-levels-only'."
8039 (cond
8040 ((zerop l) 0)
8041 (org-odd-levels-only (1+ (floor (/ l 2))))
8042 (t l)))
8044 (defun org-level-increment ()
8045 "Return the number of stars that will be added or removed at a
8046 time to headlines when structure editing, based on the value of
8047 `org-odd-levels-only'."
8048 (if org-odd-levels-only 2 1))
8050 (defun org-get-valid-level (level &optional change)
8051 "Rectify a level change under the influence of `org-odd-levels-only'
8052 LEVEL is a current level, CHANGE is by how much the level should be
8053 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8054 even level numbers will become the next higher odd number."
8055 (if org-odd-levels-only
8056 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8057 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8058 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8059 (max 1 (+ level (or change 0)))))
8061 (if (boundp 'define-obsolete-function-alias)
8062 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8063 (define-obsolete-function-alias 'org-get-legal-level
8064 'org-get-valid-level)
8065 (define-obsolete-function-alias 'org-get-legal-level
8066 'org-get-valid-level "23.1")))
8068 (defun org-promote ()
8069 "Promote the current heading higher up the tree.
8070 If the region is active in `transient-mark-mode', promote all headings
8071 in the region."
8072 (org-back-to-heading t)
8073 (let* ((level (save-match-data (funcall outline-level)))
8074 (after-change-functions (remove 'flyspell-after-change-function
8075 after-change-functions))
8076 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8077 (diff (abs (- level (length up-head) -1))))
8078 (cond ((and (= level 1) org-called-with-limited-levels
8079 org-allow-promoting-top-level-subtree)
8080 (replace-match "# " nil t))
8081 ((= level 1)
8082 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8083 (t (replace-match up-head nil t)))
8084 ;; Fixup tag positioning
8085 (unless (= level 1)
8086 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8087 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8088 (run-hooks 'org-after-promote-entry-hook)))
8090 (defun org-demote ()
8091 "Demote the current heading lower down the tree.
8092 If the region is active in `transient-mark-mode', demote all headings
8093 in the region."
8094 (org-back-to-heading t)
8095 (let* ((level (save-match-data (funcall outline-level)))
8096 (after-change-functions (remove 'flyspell-after-change-function
8097 after-change-functions))
8098 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8099 (diff (abs (- level (length down-head) -1))))
8100 (replace-match down-head nil t)
8101 ;; Fixup tag positioning
8102 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8103 (if org-adapt-indentation (org-fixup-indentation diff))
8104 (run-hooks 'org-after-demote-entry-hook)))
8106 (defun org-cycle-level ()
8107 "Cycle the level of an empty headline through possible states.
8108 This goes first to child, then to parent, level, then up the hierarchy.
8109 After top level, it switches back to sibling level."
8110 (interactive)
8111 (let ((org-adapt-indentation nil))
8112 (when (org-point-at-end-of-empty-headline)
8113 (setq this-command 'org-cycle-level) ; Only needed for caching
8114 (let ((cur-level (org-current-level))
8115 (prev-level (org-get-previous-line-level)))
8116 (cond
8117 ;; If first headline in file, promote to top-level.
8118 ((= prev-level 0)
8119 (loop repeat (/ (- cur-level 1) (org-level-increment))
8120 do (org-do-promote)))
8121 ;; If same level as prev, demote one.
8122 ((= prev-level cur-level)
8123 (org-do-demote))
8124 ;; If parent is top-level, promote to top level if not already.
8125 ((= prev-level 1)
8126 (loop repeat (/ (- cur-level 1) (org-level-increment))
8127 do (org-do-promote)))
8128 ;; If top-level, return to prev-level.
8129 ((= cur-level 1)
8130 (loop repeat (/ (- prev-level 1) (org-level-increment))
8131 do (org-do-demote)))
8132 ;; If less than prev-level, promote one.
8133 ((< cur-level prev-level)
8134 (org-do-promote))
8135 ;; If deeper than prev-level, promote until higher than
8136 ;; prev-level.
8137 ((> cur-level prev-level)
8138 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8139 do (org-do-promote))))
8140 t))))
8142 (defun org-map-tree (fun)
8143 "Call FUN for every heading underneath the current one."
8144 (org-back-to-heading)
8145 (let ((level (funcall outline-level)))
8146 (save-excursion
8147 (funcall fun)
8148 (while (and (progn
8149 (outline-next-heading)
8150 (> (funcall outline-level) level))
8151 (not (eobp)))
8152 (funcall fun)))))
8154 (defun org-map-region (fun beg end)
8155 "Call FUN for every heading between BEG and END."
8156 (let ((org-ignore-region t))
8157 (save-excursion
8158 (setq end (copy-marker end))
8159 (goto-char beg)
8160 (if (and (re-search-forward org-outline-regexp-bol nil t)
8161 (< (point) end))
8162 (funcall fun))
8163 (while (and (progn
8164 (outline-next-heading)
8165 (< (point) end))
8166 (not (eobp)))
8167 (funcall fun)))))
8169 (defvar org-property-end-re) ; silence byte-compiler
8170 (defun org-fixup-indentation (diff)
8171 "Change the indentation in the current entry by DIFF.
8172 However, if any line in the current entry has no indentation, or if it
8173 would end up with no indentation after the change, nothing at all is done."
8174 (save-excursion
8175 (let ((end (save-excursion (outline-next-heading)
8176 (point-marker)))
8177 (prohibit (if (> diff 0)
8178 "^\\S-"
8179 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8180 col)
8181 (unless (save-excursion (end-of-line 1)
8182 (re-search-forward prohibit end t))
8183 (while (and (< (point) end)
8184 (re-search-forward "^[ \t]+" end t))
8185 (goto-char (match-end 0))
8186 (setq col (current-column))
8187 (if (< diff 0) (replace-match ""))
8188 (org-indent-to-column (+ diff col))))
8189 (move-marker end nil))))
8191 (defun org-convert-to-odd-levels ()
8192 "Convert an org-mode file with all levels allowed to one with odd levels.
8193 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8194 level 5 etc."
8195 (interactive)
8196 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8197 (let ((outline-level 'org-outline-level)
8198 (org-odd-levels-only nil) n)
8199 (save-excursion
8200 (goto-char (point-min))
8201 (while (re-search-forward "^\\*\\*+ " nil t)
8202 (setq n (- (length (match-string 0)) 2))
8203 (while (>= (setq n (1- n)) 0)
8204 (org-demote))
8205 (end-of-line 1))))))
8207 (defun org-convert-to-oddeven-levels ()
8208 "Convert an org-mode file with only odd levels to one with odd/even levels.
8209 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8210 file contains a section with an even level, conversion would
8211 destroy the structure of the file. An error is signaled in this
8212 case."
8213 (interactive)
8214 (goto-char (point-min))
8215 ;; First check if there are no even levels
8216 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8217 (org-show-context t)
8218 (error "Not all levels are odd in this file. Conversion not possible"))
8219 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8220 (let ((outline-regexp org-outline-regexp)
8221 (outline-level 'org-outline-level)
8222 (org-odd-levels-only nil) n)
8223 (save-excursion
8224 (goto-char (point-min))
8225 (while (re-search-forward "^\\*\\*+ " nil t)
8226 (setq n (/ (1- (length (match-string 0))) 2))
8227 (while (>= (setq n (1- n)) 0)
8228 (org-promote))
8229 (end-of-line 1))))))
8231 (defun org-tr-level (n)
8232 "Make N odd if required."
8233 (if org-odd-levels-only (1+ (/ n 2)) n))
8235 ;;; Vertical tree motion, cutting and pasting of subtrees
8237 (defun org-move-subtree-up (&optional arg)
8238 "Move the current subtree up past ARG headlines of the same level."
8239 (interactive "p")
8240 (org-move-subtree-down (- (prefix-numeric-value arg))))
8242 (defun org-move-subtree-down (&optional arg)
8243 "Move the current subtree down past ARG headlines of the same level."
8244 (interactive "p")
8245 (setq arg (prefix-numeric-value arg))
8246 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8247 'org-get-last-sibling))
8248 (ins-point (make-marker))
8249 (cnt (abs arg))
8250 (col (current-column))
8251 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8252 ;; Select the tree
8253 (org-back-to-heading)
8254 (setq beg0 (point))
8255 (save-excursion
8256 (setq ne-beg (org-back-over-empty-lines))
8257 (setq beg (point)))
8258 (save-match-data
8259 (save-excursion (outline-end-of-heading)
8260 (setq folded (outline-invisible-p)))
8261 (outline-end-of-subtree))
8262 (outline-next-heading)
8263 (setq ne-end (org-back-over-empty-lines))
8264 (setq end (point))
8265 (goto-char beg0)
8266 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8267 ;; include less whitespace
8268 (save-excursion
8269 (goto-char beg)
8270 (forward-line (- ne-beg ne-end))
8271 (setq beg (point))))
8272 ;; Find insertion point, with error handling
8273 (while (> cnt 0)
8274 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8275 (progn (goto-char beg0)
8276 (user-error "Cannot move past superior level or buffer limit")))
8277 (setq cnt (1- cnt)))
8278 (if (> arg 0)
8279 ;; Moving forward - still need to move over subtree
8280 (progn (org-end-of-subtree t t)
8281 (save-excursion
8282 (org-back-over-empty-lines)
8283 (or (bolp) (newline)))))
8284 (setq ne-ins (org-back-over-empty-lines))
8285 (move-marker ins-point (point))
8286 (setq txt (buffer-substring beg end))
8287 (org-save-markers-in-region beg end)
8288 (delete-region beg end)
8289 (org-remove-empty-overlays-at beg)
8290 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8291 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8292 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8293 (let ((bbb (point)))
8294 (insert-before-markers txt)
8295 (org-reinstall-markers-in-region bbb)
8296 (move-marker ins-point bbb))
8297 (or (bolp) (insert "\n"))
8298 (setq ins-end (point))
8299 (goto-char ins-point)
8300 (org-skip-whitespace)
8301 (when (and (< arg 0)
8302 (org-first-sibling-p)
8303 (> ne-ins ne-beg))
8304 ;; Move whitespace back to beginning
8305 (save-excursion
8306 (goto-char ins-end)
8307 (let ((kill-whole-line t))
8308 (kill-line (- ne-ins ne-beg)) (point)))
8309 (insert (make-string (- ne-ins ne-beg) ?\n)))
8310 (move-marker ins-point nil)
8311 (if folded
8312 (hide-subtree)
8313 (org-show-entry)
8314 (show-children)
8315 (org-cycle-hide-drawers 'children))
8316 (org-clean-visibility-after-subtree-move)
8317 ;; move back to the initial column we were at
8318 (move-to-column col)))
8320 (defvar org-subtree-clip ""
8321 "Clipboard for cut and paste of subtrees.
8322 This is actually only a copy of the kill, because we use the normal kill
8323 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8325 (defvar org-subtree-clip-folded nil
8326 "Was the last copied subtree folded?
8327 This is used to fold the tree back after pasting.")
8329 (defun org-cut-subtree (&optional n)
8330 "Cut the current subtree into the clipboard.
8331 With prefix arg N, cut this many sequential subtrees.
8332 This is a short-hand for marking the subtree and then cutting it."
8333 (interactive "p")
8334 (org-copy-subtree n 'cut))
8336 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8337 "Copy the current subtree it in the clipboard.
8338 With prefix arg N, copy this many sequential subtrees.
8339 This is a short-hand for marking the subtree and then copying it.
8340 If CUT is non-nil, actually cut the subtree.
8341 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8342 of some markers in the region, even if CUT is non-nil. This is
8343 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8344 (interactive "p")
8345 (let (beg end folded (beg0 (point)))
8346 (if (org-called-interactively-p 'any)
8347 (org-back-to-heading nil) ; take what looks like a subtree
8348 (org-back-to-heading t)) ; take what is really there
8349 (setq beg (point))
8350 (skip-chars-forward " \t\r\n")
8351 (save-match-data
8352 (if nosubtrees
8353 (outline-next-heading)
8354 (save-excursion (outline-end-of-heading)
8355 (setq folded (outline-invisible-p)))
8356 (condition-case nil
8357 (org-forward-heading-same-level (1- n) t)
8358 (error nil))
8359 (org-end-of-subtree t t)))
8360 (setq end (point))
8361 (goto-char beg0)
8362 (when (> end beg)
8363 (setq org-subtree-clip-folded folded)
8364 (when (or cut force-store-markers)
8365 (org-save-markers-in-region beg end))
8366 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8367 (setq org-subtree-clip (current-kill 0))
8368 (message "%s: Subtree(s) with %d characters"
8369 (if cut "Cut" "Copied")
8370 (length org-subtree-clip)))))
8372 (defun org-paste-subtree (&optional level tree for-yank)
8373 "Paste the clipboard as a subtree, with modification of headline level.
8374 The entire subtree is promoted or demoted in order to match a new headline
8375 level.
8377 If the cursor is at the beginning of a headline, the same level as
8378 that headline is used to paste the tree.
8380 If not, the new level is derived from the *visible* headings
8381 before and after the insertion point, and taken to be the inferior headline
8382 level of the two. So if the previous visible heading is level 3 and the
8383 next is level 4 (or vice versa), level 4 will be used for insertion.
8384 This makes sure that the subtree remains an independent subtree and does
8385 not swallow low level entries.
8387 You can also force a different level, either by using a numeric prefix
8388 argument, or by inserting the heading marker by hand. For example, if the
8389 cursor is after \"*****\", then the tree will be shifted to level 5.
8391 If optional TREE is given, use this text instead of the kill ring.
8393 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8394 move back over whitespace before inserting, and move point to the end of
8395 the inserted text when done."
8396 (interactive "P")
8397 (setq tree (or tree (and kill-ring (current-kill 0))))
8398 (unless (org-kill-is-subtree-p tree)
8399 (user-error "%s"
8400 (substitute-command-keys
8401 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8402 (org-with-limited-levels
8403 (let* ((visp (not (outline-invisible-p)))
8404 (txt tree)
8405 (^re_ "\\(\\*+\\)[ \t]*")
8406 (old-level (if (string-match org-outline-regexp-bol txt)
8407 (- (match-end 0) (match-beginning 0) 1)
8408 -1))
8409 (force-level (cond (level (prefix-numeric-value level))
8410 ((and (looking-at "[ \t]*$")
8411 (string-match
8412 "^\\*+$" (buffer-substring
8413 (point-at-bol) (point))))
8414 (- (match-end 1) (match-beginning 1)))
8415 ((and (bolp)
8416 (looking-at org-outline-regexp))
8417 (- (match-end 0) (point) 1))))
8418 (previous-level (save-excursion
8419 (condition-case nil
8420 (progn
8421 (outline-previous-visible-heading 1)
8422 (if (looking-at ^re_)
8423 (- (match-end 0) (match-beginning 0) 1)
8425 (error 1))))
8426 (next-level (save-excursion
8427 (condition-case nil
8428 (progn
8429 (or (looking-at org-outline-regexp)
8430 (outline-next-visible-heading 1))
8431 (if (looking-at ^re_)
8432 (- (match-end 0) (match-beginning 0) 1)
8434 (error 1))))
8435 (new-level (or force-level (max previous-level next-level)))
8436 (shift (if (or (= old-level -1)
8437 (= new-level -1)
8438 (= old-level new-level))
8440 (- new-level old-level)))
8441 (delta (if (> shift 0) -1 1))
8442 (func (if (> shift 0) 'org-demote 'org-promote))
8443 (org-odd-levels-only nil)
8444 beg end newend)
8445 ;; Remove the forced level indicator
8446 (if force-level
8447 (delete-region (point-at-bol) (point)))
8448 ;; Paste
8449 (beginning-of-line (if (bolp) 1 2))
8450 (setq beg (point))
8451 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8452 (insert-before-markers txt)
8453 (unless (string-match "\n\\'" txt) (insert "\n"))
8454 (setq newend (point))
8455 (org-reinstall-markers-in-region beg)
8456 (setq end (point))
8457 (goto-char beg)
8458 (skip-chars-forward " \t\n\r")
8459 (setq beg (point))
8460 (if (and (outline-invisible-p) visp)
8461 (save-excursion (outline-show-heading)))
8462 ;; Shift if necessary
8463 (unless (= shift 0)
8464 (save-restriction
8465 (narrow-to-region beg end)
8466 (while (not (= shift 0))
8467 (org-map-region func (point-min) (point-max))
8468 (setq shift (+ delta shift)))
8469 (goto-char (point-min))
8470 (setq newend (point-max))))
8471 (when (or (org-called-interactively-p 'interactive) for-yank)
8472 (message "Clipboard pasted as level %d subtree" new-level))
8473 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8474 kill-ring
8475 (eq org-subtree-clip (current-kill 0))
8476 org-subtree-clip-folded)
8477 ;; The tree was folded before it was killed/copied
8478 (hide-subtree))
8479 (and for-yank (goto-char newend)))))
8481 (defun org-kill-is-subtree-p (&optional txt)
8482 "Check if the current kill is an outline subtree, or a set of trees.
8483 Returns nil if kill does not start with a headline, or if the first
8484 headline level is not the largest headline level in the tree.
8485 So this will actually accept several entries of equal levels as well,
8486 which is OK for `org-paste-subtree'.
8487 If optional TXT is given, check this string instead of the current kill."
8488 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8489 (re (org-get-limited-outline-regexp))
8490 (^re (concat "^" re))
8491 (start-level (and kill
8492 (string-match
8493 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8494 kill)
8495 (- (match-end 2) (match-beginning 2) 1)))
8496 (start (1+ (or (match-beginning 2) -1))))
8497 (if (not start-level)
8498 (progn
8499 nil) ;; does not even start with a heading
8500 (catch 'exit
8501 (while (setq start (string-match ^re kill (1+ start)))
8502 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8503 (throw 'exit nil)))
8504 t))))
8506 (defvar org-markers-to-move nil
8507 "Markers that should be moved with a cut-and-paste operation.
8508 Those markers are stored together with their positions relative to
8509 the start of the region.")
8511 (defun org-save-markers-in-region (beg end)
8512 "Check markers in region.
8513 If these markers are between BEG and END, record their position relative
8514 to BEG, so that after moving the block of text, we can put the markers back
8515 into place.
8516 This function gets called just before an entry or tree gets cut from the
8517 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8518 called immediately, to move the markers with the entries."
8519 (setq org-markers-to-move nil)
8520 (when (featurep 'org-clock)
8521 (org-clock-save-markers-for-cut-and-paste beg end))
8522 (when (featurep 'org-agenda)
8523 (org-agenda-save-markers-for-cut-and-paste beg end)))
8525 (defun org-check-and-save-marker (marker beg end)
8526 "Check if MARKER is between BEG and END.
8527 If yes, remember the marker and the distance to BEG."
8528 (when (and (marker-buffer marker)
8529 (equal (marker-buffer marker) (current-buffer)))
8530 (if (and (>= marker beg) (< marker end))
8531 (push (cons marker (- marker beg)) org-markers-to-move))))
8533 (defun org-reinstall-markers-in-region (beg)
8534 "Move all remembered markers to their position relative to BEG."
8535 (mapc (lambda (x)
8536 (move-marker (car x) (+ beg (cdr x))))
8537 org-markers-to-move)
8538 (setq org-markers-to-move nil))
8540 (defun org-narrow-to-subtree ()
8541 "Narrow buffer to the current subtree."
8542 (interactive)
8543 (save-excursion
8544 (save-match-data
8545 (org-with-limited-levels
8546 (narrow-to-region
8547 (progn (org-back-to-heading t) (point))
8548 (progn (org-end-of-subtree t t)
8549 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8550 (point)))))))
8552 (defun org-narrow-to-block ()
8553 "Narrow buffer to the current block."
8554 (interactive)
8555 (let* ((case-fold-search t)
8556 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8557 "^[ \t]*#\\+end_.*")))
8558 (if blockp
8559 (narrow-to-region (car blockp) (cdr blockp))
8560 (user-error "Not in a block"))))
8562 (eval-when-compile
8563 (defvar org-property-drawer-re))
8565 (defvar org-property-start-re) ;; defined below
8566 (defun org-clone-subtree-with-time-shift (n &optional shift)
8567 "Clone the task (subtree) at point N times.
8568 The clones will be inserted as siblings.
8570 In interactive use, the user will be prompted for the number of
8571 clones to be produced. If the entry has a timestamp, the user
8572 will also be prompted for a time shift, which may be a repeater
8573 as used in time stamps, for example `+3d'. To disable this,
8574 you can call the function with a universal prefix argument.
8576 When a valid repeater is given and the entry contains any time
8577 stamps, the clones will become a sequence in time, with time
8578 stamps in the subtree shifted for each clone produced. If SHIFT
8579 is nil or the empty string, time stamps will be left alone. The
8580 ID property of the original subtree is removed.
8582 If the original subtree did contain time stamps with a repeater,
8583 the following will happen:
8584 - the repeater will be removed in each clone
8585 - an additional clone will be produced, with the current, unshifted
8586 date(s) in the entry.
8587 - the original entry will be placed *after* all the clones, with
8588 repeater intact.
8589 - the start days in the repeater in the original entry will be shifted
8590 to past the last clone.
8591 In this way you can spell out a number of instances of a repeating task,
8592 and still retain the repeater to cover future instances of the task."
8593 (interactive "nNumber of clones to produce: ")
8594 (let ((shift
8595 (or shift
8596 (if (and (not (equal current-prefix-arg '(4)))
8597 (save-excursion
8598 (re-search-forward org-ts-regexp-both
8599 (save-excursion
8600 (org-end-of-subtree t)
8601 (point)) t)))
8602 (read-from-minibuffer
8603 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8604 ""))) ;; No time shift
8605 (n-no-remove -1)
8606 (drawer-re org-drawer-regexp)
8607 beg end template task idprop
8608 shift-n shift-what doshift nmin nmax)
8609 (if (not (and (integerp n) (> n 0)))
8610 (user-error "Invalid number of replications %s" n))
8611 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8612 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8613 shift)))
8614 (user-error "Invalid shift specification %s" shift))
8615 (when doshift
8616 (setq shift-n (string-to-number (match-string 1 shift))
8617 shift-what (cdr (assoc (match-string 2 shift)
8618 '(("d" . day) ("w" . week)
8619 ("m" . month) ("y" . year))))))
8620 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8621 (setq nmin 1 nmax n)
8622 (org-back-to-heading t)
8623 (setq beg (point))
8624 (setq idprop (org-entry-get nil "ID"))
8625 (org-end-of-subtree t t)
8626 (or (bolp) (insert "\n"))
8627 (setq end (point))
8628 (setq template (buffer-substring beg end))
8629 (when (and doshift
8630 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8631 (delete-region beg end)
8632 (setq end beg)
8633 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8634 (goto-char end)
8635 (loop for n from nmin to nmax do
8636 ;; prepare clone
8637 (with-temp-buffer
8638 (insert template)
8639 (org-mode)
8640 (goto-char (point-min))
8641 (org-show-subtree)
8642 (and idprop (if org-clone-delete-id
8643 (org-entry-delete nil "ID")
8644 (org-id-get-create t)))
8645 (unless (= n 0)
8646 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8647 (kill-whole-line))
8648 (goto-char (point-min))
8649 (while (re-search-forward drawer-re nil t)
8650 (org-remove-empty-drawer-at (point))))
8651 (goto-char (point-min))
8652 (when doshift
8653 (while (re-search-forward org-ts-regexp-both nil t)
8654 (org-timestamp-change (* n shift-n) shift-what))
8655 (unless (= n n-no-remove)
8656 (goto-char (point-min))
8657 (while (re-search-forward org-ts-regexp nil t)
8658 (save-excursion
8659 (goto-char (match-beginning 0))
8660 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8661 (delete-region (match-beginning 1) (match-end 1)))))))
8662 (setq task (buffer-string)))
8663 (insert task))
8664 (goto-char beg)))
8666 ;;; Outline Sorting
8668 (defun org-sort (with-case)
8669 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8670 Optional argument WITH-CASE means sort case-sensitively."
8671 (interactive "P")
8672 (cond
8673 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8674 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8676 (org-call-with-arg 'org-sort-entries with-case))))
8678 (defun org-sort-remove-invisible (s)
8679 "Remove invisible links from string S."
8680 (remove-text-properties 0 (length s) org-rm-props s)
8681 (while (string-match org-bracket-link-regexp s)
8682 (setq s (replace-match (if (match-end 2)
8683 (match-string 3 s)
8684 (match-string 1 s)) t t s)))
8685 (let ((st (format " %s " s)))
8686 (while (string-match org-emph-re st)
8687 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8688 (setq s (substring st 1 -1)))
8691 (defvar org-priority-regexp) ; defined later in the file
8693 (defvar org-after-sorting-entries-or-items-hook nil
8694 "Hook that is run after a bunch of entries or items have been sorted.
8695 When children are sorted, the cursor is in the parent line when this
8696 hook gets called. When a region or a plain list is sorted, the cursor
8697 will be in the first entry of the sorted region/list.")
8699 (defun org-sort-entries
8700 (&optional with-case sorting-type getkey-func compare-func property)
8701 "Sort entries on a certain level of an outline tree.
8702 If there is an active region, the entries in the region are sorted.
8703 Else, if the cursor is before the first entry, sort the top-level items.
8704 Else, the children of the entry at point are sorted.
8706 Sorting can be alphabetically, numerically, by date/time as given by
8707 a time stamp, by a property, by priority order, or by a custom function.
8709 The command prompts for the sorting type unless it has been given to the
8710 function through the SORTING-TYPE argument, which needs to be a character,
8711 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8712 the precise meaning of each character:
8714 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8715 c By creation time, which is assumed to be the first inactive time stamp
8716 at the beginning of a line.
8717 d By deadline date/time.
8718 k By clocking time.
8719 n Numerically, by converting the beginning of the entry/item to a number.
8720 o By order of TODO keywords.
8721 p By priority according to the cookie.
8722 r By the value of a property.
8723 s By scheduled date/time.
8724 t By date/time, either the first active time stamp in the entry, or, if
8725 none exist, by the first inactive one.
8727 Capital letters will reverse the sort order.
8729 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8730 called with point at the beginning of the record. It must return either
8731 a string or a number that should serve as the sorting key for that record.
8733 Comparing entries ignores case by default. However, with an optional argument
8734 WITH-CASE, the sorting considers case as well.
8736 Sorting is done against the visible part of the headlines, it ignores hidden
8737 links.
8739 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8740 (interactive "P")
8741 (let ((case-func (if with-case 'identity 'downcase))
8742 (cmstr
8743 ;; The clock marker is lost when using `sort-subr', let's
8744 ;; store the clocking string.
8745 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8746 (save-excursion
8747 (goto-char org-clock-marker)
8748 (looking-back "^.*") (match-string-no-properties 0))))
8749 start beg end stars re re2
8750 txt what tmp)
8751 ;; Find beginning and end of region to sort
8752 (cond
8753 ((org-region-active-p)
8754 ;; we will sort the region
8755 (setq end (region-end)
8756 what "region")
8757 (goto-char (region-beginning))
8758 (if (not (org-at-heading-p)) (outline-next-heading))
8759 (setq start (point)))
8760 ((or (org-at-heading-p)
8761 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8762 ;; we will sort the children of the current headline
8763 (org-back-to-heading)
8764 (setq start (point)
8765 end (progn (org-end-of-subtree t t)
8766 (or (bolp) (insert "\n"))
8767 (when (>= (org-back-over-empty-lines) 1)
8768 (forward-line 1))
8769 (point))
8770 what "children")
8771 (goto-char start)
8772 (show-subtree)
8773 (outline-next-heading))
8775 ;; we will sort the top-level entries in this file
8776 (goto-char (point-min))
8777 (or (org-at-heading-p) (outline-next-heading))
8778 (setq start (point))
8779 (goto-char (point-max))
8780 (beginning-of-line 1)
8781 (when (looking-at ".*?\\S-")
8782 ;; File ends in a non-white line
8783 (end-of-line 1)
8784 (insert "\n"))
8785 (setq end (point-max))
8786 (setq what "top-level")
8787 (goto-char start)
8788 (show-all)))
8790 (setq beg (point))
8791 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8793 (looking-at "\\(\\*+\\)")
8794 (setq stars (match-string 1)
8795 re (concat "^" (regexp-quote stars) " +")
8796 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8797 txt (buffer-substring beg end))
8798 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8799 (if (and (not (equal stars "*")) (string-match re2 txt))
8800 (user-error "Region to sort contains a level above the first entry"))
8802 (unless sorting-type
8803 (message
8804 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8805 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8806 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8807 what)
8808 (setq sorting-type (read-char-exclusive))
8810 (unless getkey-func
8811 (and (= (downcase sorting-type) ?f)
8812 (setq getkey-func
8813 (org-icompleting-read "Sort using function: "
8814 obarray 'fboundp t nil nil))
8815 (setq getkey-func (intern getkey-func))))
8817 (and (= (downcase sorting-type) ?r)
8818 (not property)
8819 (setq property
8820 (org-icompleting-read "Property: "
8821 (mapcar 'list (org-buffer-property-keys t))
8822 nil t))))
8824 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8825 (message "Sorting entries...")
8827 (save-restriction
8828 (narrow-to-region start end)
8829 (let ((dcst (downcase sorting-type))
8830 (case-fold-search nil)
8831 (now (current-time)))
8832 (sort-subr
8833 (/= dcst sorting-type)
8834 ;; This function moves to the beginning character of the "record" to
8835 ;; be sorted.
8836 (lambda nil
8837 (if (re-search-forward re nil t)
8838 (goto-char (match-beginning 0))
8839 (goto-char (point-max))))
8840 ;; This function moves to the last character of the "record" being
8841 ;; sorted.
8842 (lambda nil
8843 (save-match-data
8844 (condition-case nil
8845 (outline-forward-same-level 1)
8846 (error
8847 (goto-char (point-max))))))
8848 ;; This function returns the value that gets sorted against.
8849 (lambda nil
8850 (cond
8851 ((= dcst ?n)
8852 (if (looking-at org-complex-heading-regexp)
8853 (string-to-number (org-sort-remove-invisible (match-string 4)))
8854 nil))
8855 ((= dcst ?a)
8856 (if (looking-at org-complex-heading-regexp)
8857 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8858 nil))
8859 ((= dcst ?k)
8860 (or (get-text-property (point) :org-clock-minutes) 0))
8861 ((= dcst ?t)
8862 (let ((end (save-excursion (outline-next-heading) (point))))
8863 (if (or (re-search-forward org-ts-regexp end t)
8864 (re-search-forward org-ts-regexp-both end t))
8865 (org-time-string-to-seconds (match-string 0))
8866 (org-float-time now))))
8867 ((= dcst ?c)
8868 (let ((end (save-excursion (outline-next-heading) (point))))
8869 (if (re-search-forward
8870 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8871 end t)
8872 (org-time-string-to-seconds (match-string 0))
8873 (org-float-time now))))
8874 ((= dcst ?s)
8875 (let ((end (save-excursion (outline-next-heading) (point))))
8876 (if (re-search-forward org-scheduled-time-regexp end t)
8877 (org-time-string-to-seconds (match-string 1))
8878 (org-float-time now))))
8879 ((= dcst ?d)
8880 (let ((end (save-excursion (outline-next-heading) (point))))
8881 (if (re-search-forward org-deadline-time-regexp end t)
8882 (org-time-string-to-seconds (match-string 1))
8883 (org-float-time now))))
8884 ((= dcst ?p)
8885 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8886 (string-to-char (match-string 2))
8887 org-default-priority))
8888 ((= dcst ?r)
8889 (or (org-entry-get nil property) ""))
8890 ((= dcst ?o)
8891 (if (looking-at org-complex-heading-regexp)
8892 (- 9999 (length (member (match-string 2)
8893 org-todo-keywords-1)))))
8894 ((= dcst ?f)
8895 (if getkey-func
8896 (progn
8897 (setq tmp (funcall getkey-func))
8898 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8899 tmp)
8900 (error "Invalid key function `%s'" getkey-func)))
8901 (t (error "Invalid sorting type `%c'" sorting-type))))
8903 (cond
8904 ((= dcst ?a) 'string<)
8905 ((= dcst ?f) compare-func)
8906 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8907 (run-hooks 'org-after-sorting-entries-or-items-hook)
8908 ;; Reset the clock marker if needed
8909 (when cmstr
8910 (save-excursion
8911 (goto-char start)
8912 (search-forward cmstr nil t)
8913 (move-marker org-clock-marker (point))))
8914 (message "Sorting entries...done")))
8916 (defun org-do-sort (table what &optional with-case sorting-type)
8917 "Sort TABLE of WHAT according to SORTING-TYPE.
8918 The user will be prompted for the SORTING-TYPE if the call to this
8919 function does not specify it.
8920 WHAT is only for the prompt, to indicate what is being sorted.
8921 The sorting key will be extracted from the car of the elements of
8922 the table.
8923 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8924 (unless sorting-type
8925 (message
8926 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8927 what)
8928 (setq sorting-type (read-char-exclusive)))
8929 (let ((dcst (downcase sorting-type))
8930 extractfun comparefun)
8931 ;; Define the appropriate functions
8932 (cond
8933 ((= dcst ?n)
8934 (setq extractfun 'string-to-number
8935 comparefun (if (= dcst sorting-type) '< '>)))
8936 ((= dcst ?a)
8937 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8938 (lambda(x) (downcase (org-sort-remove-invisible x))))
8939 comparefun (if (= dcst sorting-type)
8940 'string<
8941 (lambda (a b) (and (not (string< a b))
8942 (not (string= a b)))))))
8943 ((= dcst ?t)
8944 (setq extractfun
8945 (lambda (x)
8946 (cond ((or (string-match org-ts-regexp x)
8947 (string-match org-ts-regexp-both x))
8948 (org-float-time
8949 (org-time-string-to-time (match-string 0 x))))
8950 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
8951 (org-hh:mm-string-to-minutes x))
8952 (t 0)))
8953 comparefun (if (= dcst sorting-type) '< '>)))
8954 (t (error "Invalid sorting type `%c'" sorting-type)))
8956 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8957 table)
8958 (lambda (a b) (funcall comparefun (car a) (car b))))))
8961 ;;; The orgstruct minor mode
8963 ;; Define a minor mode which can be used in other modes in order to
8964 ;; integrate the org-mode structure editing commands.
8966 ;; This is really a hack, because the org-mode structure commands use
8967 ;; keys which normally belong to the major mode. Here is how it
8968 ;; works: The minor mode defines all the keys necessary to operate the
8969 ;; structure commands, but wraps the commands into a function which
8970 ;; tests if the cursor is currently at a headline or a plain list
8971 ;; item. If that is the case, the structure command is used,
8972 ;; temporarily setting many Org-mode variables like regular
8973 ;; expressions for filling etc. However, when any of those keys is
8974 ;; used at a different location, function uses `key-binding' to look
8975 ;; up if the key has an associated command in another currently active
8976 ;; keymap (minor modes, major mode, global), and executes that
8977 ;; command. There might be problems if any of the keys is otherwise
8978 ;; used as a prefix key.
8980 (defcustom orgstruct-heading-prefix-regexp ""
8981 "Regexp that matches the custom prefix of Org headlines in
8982 orgstruct(++)-mode."
8983 :group 'org
8984 :version "24.4"
8985 :package-version '(Org . "8.3")
8986 :type 'regexp)
8987 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8989 (defcustom orgstruct-setup-hook nil
8990 "Hook run after orgstruct-mode-map is filled."
8991 :group 'org
8992 :version "24.4"
8993 :package-version '(Org . "8.0")
8994 :type 'hook)
8996 (defvar orgstruct-initialized nil)
8998 (defvar org-local-vars nil
8999 "List of local variables, for use by `orgstruct-mode'.")
9001 ;;;###autoload
9002 (define-minor-mode orgstruct-mode
9003 "Toggle the minor mode `orgstruct-mode'.
9004 This mode is for using Org-mode structure commands in other
9005 modes. The following keys behave as if Org-mode were active, if
9006 the cursor is on a headline, or on a plain list item (both as
9007 defined by Org-mode)."
9008 nil " OrgStruct" (make-sparse-keymap)
9009 (funcall (if orgstruct-mode
9010 'add-to-invisibility-spec
9011 'remove-from-invisibility-spec)
9012 '(outline . t))
9013 (when orgstruct-mode
9014 (org-load-modules-maybe)
9015 (unless orgstruct-initialized
9016 (orgstruct-setup)
9017 (setq orgstruct-initialized t))))
9019 ;;;###autoload
9020 (defun turn-on-orgstruct ()
9021 "Unconditionally turn on `orgstruct-mode'."
9022 (orgstruct-mode 1))
9024 (defvar org-fb-vars nil)
9025 (make-variable-buffer-local 'org-fb-vars)
9026 (defun orgstruct++-mode (&optional arg)
9027 "Toggle `orgstruct-mode', the enhanced version of it.
9028 In addition to setting orgstruct-mode, this also exports all
9029 indentation and autofilling variables from org-mode into the
9030 buffer. It will also recognize item context in multiline items."
9031 (interactive "P")
9032 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9033 (if (< arg 1)
9034 (progn (orgstruct-mode -1)
9035 (mapc (lambda(v)
9036 (org-set-local (car v)
9037 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9038 org-fb-vars))
9039 (orgstruct-mode 1)
9040 (setq org-fb-vars nil)
9041 (unless org-local-vars
9042 (setq org-local-vars (org-get-local-variables)))
9043 (let (var val)
9044 (mapc
9045 (lambda (x)
9046 (when (string-match
9047 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9048 (symbol-name (car x)))
9049 (setq var (car x) val (nth 1 x))
9050 (push (list var `(quote ,(eval var))) org-fb-vars)
9051 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9052 org-local-vars)
9053 (org-set-local 'orgstruct-is-++ t))))
9055 (defvar orgstruct-is-++ nil
9056 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9057 (make-variable-buffer-local 'orgstruct-is-++)
9059 ;;;###autoload
9060 (defun turn-on-orgstruct++ ()
9061 "Unconditionally turn on `orgstruct++-mode'."
9062 (orgstruct++-mode 1))
9064 (defun orgstruct-error ()
9065 "Error when there is no default binding for a structure key."
9066 (interactive)
9067 (funcall (if (fboundp 'user-error)
9068 'user-error
9069 'error)
9070 "This key has no function outside structure elements"))
9072 (defun orgstruct-setup ()
9073 "Setup orgstruct keymap."
9074 (dolist (cell '((org-demote . t)
9075 (org-metaleft . t)
9076 (org-metaright . t)
9077 (org-promote . t)
9078 (org-shiftmetaleft . t)
9079 (org-shiftmetaright . t)
9080 org-backward-element
9081 org-backward-heading-same-level
9082 org-ctrl-c-ret
9083 org-ctrl-c-minus
9084 org-ctrl-c-star
9085 org-cycle
9086 org-forward-heading-same-level
9087 org-insert-heading
9088 org-insert-heading-respect-content
9089 org-kill-note-or-show-branches
9090 org-mark-subtree
9091 org-meta-return
9092 org-metadown
9093 org-metaup
9094 org-narrow-to-subtree
9095 org-promote-subtree
9096 org-reveal
9097 org-shiftdown
9098 org-shiftleft
9099 org-shiftmetadown
9100 org-shiftmetaup
9101 org-shiftright
9102 org-shifttab
9103 org-shifttab
9104 org-shiftup
9105 org-show-subtree
9106 org-sort
9107 org-up-element
9108 outline-demote
9109 outline-next-visible-heading
9110 outline-previous-visible-heading
9111 outline-promote
9112 outline-up-heading
9113 show-children))
9114 (let ((f (or (car-safe cell) cell))
9115 (disable-when-heading-prefix (cdr-safe cell)))
9116 (when (fboundp f)
9117 (let ((new-bindings))
9118 (dolist (binding (nconc (where-is-internal f org-mode-map)
9119 (where-is-internal f outline-mode-map)))
9120 (push binding new-bindings)
9121 ;; TODO use local-function-key-map
9122 (dolist (rep '(("<tab>" . "TAB")
9123 ("<return>" . "RET")
9124 ("<escape>" . "ESC")
9125 ("<delete>" . "DEL")))
9126 (setq binding (read-kbd-macro
9127 (let ((case-fold-search))
9128 (replace-regexp-in-string
9129 (regexp-quote (cdr rep))
9130 (car rep)
9131 (key-description binding)))))
9132 (pushnew binding new-bindings :test 'equal)))
9133 (dolist (binding new-bindings)
9134 (let ((key (lookup-key orgstruct-mode-map binding)))
9135 (when (or (not key) (numberp key))
9136 (condition-case nil
9137 (org-defkey orgstruct-mode-map
9138 binding
9139 (orgstruct-make-binding f binding disable-when-heading-prefix))
9140 (error nil)))))))))
9141 (run-hooks 'orgstruct-setup-hook))
9143 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9144 "Create a function for binding in the structure minor mode.
9145 FUN is the command to call inside a table. KEY is the key that
9146 should be checked in for a command to execute outside of tables.
9147 Non-nil `disable-when-heading-prefix' means to disable the command
9148 if `orgstruct-heading-prefix-regexp' is not empty."
9149 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9150 (let ((nname name)
9151 (i 0))
9152 (while (fboundp (intern nname))
9153 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9154 (setq name (intern nname)))
9155 (eval
9156 (let ((bindings '((org-heading-regexp
9157 (concat "^"
9158 orgstruct-heading-prefix-regexp
9159 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9160 (org-outline-regexp
9161 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9162 (org-outline-regexp-bol
9163 (concat "^" org-outline-regexp))
9164 (outline-regexp org-outline-regexp)
9165 (outline-heading-end-regexp "\n")
9166 (outline-level 'org-outline-level)
9167 (outline-heading-alist))))
9168 `(defun ,name (arg)
9169 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9170 "Outside of structure, run the binding of `"
9171 (key-description key) "'."
9172 (when disable-when-heading-prefix
9173 (concat
9174 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9175 "back to the default binding due to limitations of Org's implementation of\n"
9176 "`" (symbol-name fun) "'.")))
9177 (interactive "p")
9178 (let* ((disable
9179 ,(and disable-when-heading-prefix
9180 '(not (string= orgstruct-heading-prefix-regexp ""))))
9181 (fallback
9182 (or disable
9183 (not
9184 (let* ,bindings
9185 (org-context-p 'headline 'item
9186 ,(when (memq fun
9187 '(org-insert-heading
9188 org-insert-heading-respect-content
9189 org-meta-return))
9190 '(when orgstruct-is-++
9191 'item-body))))))))
9192 (if fallback
9193 (let* ((orgstruct-mode)
9194 (binding
9195 (loop with key = ,key
9196 for rep in
9197 '(nil
9198 ("<\\([^>]*\\)tab>" . "\\1TAB")
9199 ("<\\([^>]*\\)return>" . "\\1RET")
9200 ("<\\([^>]*\\)escape>" . "\\1ESC")
9201 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9203 (when rep
9204 (setq key (read-kbd-macro
9205 (let ((case-fold-search))
9206 (replace-regexp-in-string
9207 (car rep)
9208 (cdr rep)
9209 (key-description key))))))
9210 thereis (key-binding key))))
9211 (if (keymapp binding)
9212 (org-set-transient-map binding)
9213 (let ((func (or binding
9214 (unless disable
9215 'orgstruct-error))))
9216 (when func
9217 (call-interactively func)))))
9218 (org-run-like-in-org-mode
9219 (lambda ()
9220 (interactive)
9221 (let* ,bindings
9222 (call-interactively ',fun)))))))))
9223 name))
9225 (defun org-contextualize-keys (alist contexts)
9226 "Return valid elements in ALIST depending on CONTEXTS.
9228 `org-agenda-custom-commands' or `org-capture-templates' are the
9229 values used for ALIST, and `org-agenda-custom-commands-contexts'
9230 or `org-capture-templates-contexts' are the associated contexts
9231 definitions."
9232 (let ((contexts
9233 ;; normalize contexts
9234 (mapcar
9235 (lambda(c) (cond ((listp (cadr c))
9236 (list (car c) (car c) (cadr c)))
9237 ((string= "" (cadr c))
9238 (list (car c) (car c) (caddr c)))
9239 (t c))) contexts))
9240 (a alist) c r s)
9241 ;; loop over all commands or templates
9242 (while (setq c (pop a))
9243 (let (vrules repl)
9244 (cond
9245 ((not (assoc (car c) contexts))
9246 (push c r))
9247 ((and (assoc (car c) contexts)
9248 (setq vrules (org-contextualize-validate-key
9249 (car c) contexts)))
9250 (mapc (lambda (vr)
9251 (when (not (equal (car vr) (cadr vr)))
9252 (setq repl vr))) vrules)
9253 (if (not repl) (push c r)
9254 (push (cadr repl) s)
9255 (push
9256 (cons (car c)
9257 (cdr (or (assoc (cadr repl) alist)
9258 (error "Undefined key `%s' as contextual replacement for `%s'"
9259 (cadr repl) (car c)))))
9260 r))))))
9261 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9262 (delq
9264 (delete-dups
9265 (mapcar (lambda (x)
9266 (let ((tpl (car x)))
9267 (when (not (delq
9269 (mapcar (lambda(y)
9270 (equal y tpl)) s))) x)))
9271 (reverse r))))))
9273 (defun org-contextualize-validate-key (key contexts)
9274 "Check CONTEXTS for agenda or capture KEY."
9275 (let (r rr res)
9276 (while (setq r (pop contexts))
9277 (mapc
9278 (lambda (rr)
9279 (when
9280 (and (equal key (car r))
9281 (if (functionp rr) (funcall rr)
9282 (or (and (eq (car rr) 'in-file)
9283 (buffer-file-name)
9284 (string-match (cdr rr) (buffer-file-name)))
9285 (and (eq (car rr) 'in-mode)
9286 (string-match (cdr rr) (symbol-name major-mode)))
9287 (and (eq (car rr) 'in-buffer)
9288 (string-match (cdr rr) (buffer-name)))
9289 (when (and (eq (car rr) 'not-in-file)
9290 (buffer-file-name))
9291 (not (string-match (cdr rr) (buffer-file-name))))
9292 (when (eq (car rr) 'not-in-mode)
9293 (not (string-match (cdr rr) (symbol-name major-mode))))
9294 (when (eq (car rr) 'not-in-buffer)
9295 (not (string-match (cdr rr) (buffer-name)))))))
9296 (push r res)))
9297 (car (last r))))
9298 (delete-dups (delq nil res))))
9300 (defun org-context-p (&rest contexts)
9301 "Check if local context is any of CONTEXTS.
9302 Possible values in the list of contexts are `table', `headline', and `item'."
9303 (let ((pos (point)))
9304 (goto-char (point-at-bol))
9305 (prog1 (or (and (memq 'table contexts)
9306 (looking-at "[ \t]*|"))
9307 (and (memq 'headline contexts)
9308 (looking-at org-outline-regexp))
9309 (and (memq 'item contexts)
9310 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9311 (and (memq 'item-body contexts)
9312 (org-in-item-p)))
9313 (goto-char pos))))
9315 (defun org-get-local-variables ()
9316 "Return a list of all local variables in an Org mode buffer."
9317 (let (varlist)
9318 (with-current-buffer (get-buffer-create "*Org tmp*")
9319 (erase-buffer)
9320 (org-mode)
9321 (setq varlist (buffer-local-variables)))
9322 (kill-buffer "*Org tmp*")
9323 (delq nil
9324 (mapcar
9325 (lambda (x)
9326 (setq x
9327 (if (symbolp x)
9328 (list x)
9329 (list (car x) (cdr x))))
9330 (if (and (not (get (car x) 'org-state))
9331 (string-match
9332 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9333 (symbol-name (car x))))
9334 x nil))
9335 varlist))))
9337 (defun org-clone-local-variables (from-buffer &optional regexp)
9338 "Clone local variables from FROM-BUFFER.
9339 Optional argument REGEXP selects variables to clone."
9340 (mapc
9341 (lambda (pair)
9342 (and (symbolp (car pair))
9343 (or (null regexp)
9344 (string-match regexp (symbol-name (car pair))))
9345 (set (make-local-variable (car pair))
9346 (cdr pair))))
9347 (buffer-local-variables from-buffer)))
9349 ;;;###autoload
9350 (defun org-run-like-in-org-mode (cmd)
9351 "Run a command, pretending that the current buffer is in Org-mode.
9352 This will temporarily bind local variables that are typically bound in
9353 Org-mode to the values they have in Org-mode, and then interactively
9354 call CMD."
9355 (org-load-modules-maybe)
9356 (unless org-local-vars
9357 (setq org-local-vars (org-get-local-variables)))
9358 (let (binds)
9359 (dolist (var org-local-vars)
9360 (when (or (not (boundp (car var)))
9361 (eq (symbol-value (car var))
9362 (default-value (car var))))
9363 (push (list (car var) `(quote ,(cadr var))) binds)))
9364 (eval `(let ,binds
9365 (call-interactively (quote ,cmd))))))
9367 ;;;; Archiving
9369 (defun org-get-category (&optional pos force-refresh)
9370 "Get the category applying to position POS."
9371 (save-match-data
9372 (if force-refresh (org-refresh-category-properties))
9373 (let ((pos (or pos (point))))
9374 (or (get-text-property pos 'org-category)
9375 (progn (org-refresh-category-properties)
9376 (get-text-property pos 'org-category))))))
9378 (defun org-refresh-category-properties ()
9379 "Refresh category text properties in the buffer."
9380 (let ((case-fold-search t)
9381 (inhibit-read-only t)
9382 (def-cat (cond
9383 ((null org-category)
9384 (if buffer-file-name
9385 (file-name-sans-extension
9386 (file-name-nondirectory buffer-file-name))
9387 "???"))
9388 ((symbolp org-category) (symbol-name org-category))
9389 (t org-category)))
9390 beg end cat pos optionp)
9391 (org-with-silent-modifications
9392 (save-excursion
9393 (save-restriction
9394 (widen)
9395 (goto-char (point-min))
9396 (put-text-property (point) (point-max) 'org-category def-cat)
9397 (while (re-search-forward
9398 "^[ \t]*\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9399 (setq pos (match-end 0)
9400 optionp (equal (char-after (match-beginning 0)) ?#)
9401 cat (org-trim (match-string 2)))
9402 (if optionp
9403 (setq beg (point-at-bol) end (point-max))
9404 (org-back-to-heading t)
9405 (setq beg (point) end (org-end-of-subtree t t)))
9406 (put-text-property beg end 'org-category cat)
9407 (put-text-property beg end 'org-category-position beg)
9408 (goto-char pos)))))))
9410 (defun org-refresh-properties (dprop tprop)
9411 "Refresh buffer text properties.
9412 DPROP is the drawer property and TPROP is the corresponding text
9413 property to set."
9414 (let ((case-fold-search t)
9415 (inhibit-read-only t) p)
9416 (org-with-silent-modifications
9417 (save-excursion
9418 (save-restriction
9419 (widen)
9420 (goto-char (point-min))
9421 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9422 (setq p (org-match-string-no-properties 1))
9423 (save-excursion
9424 (org-back-to-heading t)
9425 (put-text-property
9426 (point-at-bol) (or (outline-next-heading) (point-max)) tprop p))))))))
9429 ;;;; Link Stuff
9431 ;;; Link abbreviations
9433 (defun org-link-expand-abbrev (link)
9434 "Apply replacements as defined in `org-link-abbrev-alist'."
9435 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9436 (let* ((key (match-string 1 link))
9437 (as (or (assoc key org-link-abbrev-alist-local)
9438 (assoc key org-link-abbrev-alist)))
9439 (tag (and (match-end 2) (match-string 3 link)))
9440 rpl)
9441 (if (not as)
9442 link
9443 (setq rpl (cdr as))
9444 (cond
9445 ((symbolp rpl) (funcall rpl tag))
9446 ((string-match "%(\\([^)]+\\))" rpl)
9447 (replace-match
9448 (save-match-data
9449 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9450 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9451 ((string-match "%h" rpl)
9452 (replace-match (url-hexify-string (or tag "")) t t rpl))
9453 (t (concat rpl tag)))))
9454 link))
9456 ;;; Storing and inserting links
9458 (defvar org-insert-link-history nil
9459 "Minibuffer history for links inserted with `org-insert-link'.")
9461 (defvar org-stored-links nil
9462 "Contains the links stored with `org-store-link'.")
9464 (defvar org-store-link-plist nil
9465 "Plist with info about the most recently link created with `org-store-link'.")
9467 (defvar org-link-protocols nil
9468 "Link protocols added to Org-mode using `org-add-link-type'.")
9470 (defvar org-store-link-functions nil
9471 "List of functions that are called to create and store a link.
9472 Each function will be called in turn until one returns a non-nil
9473 value. Each function should check if it is responsible for creating
9474 this link (for example by looking at the major mode).
9475 If not, it must exit and return nil.
9476 If yes, it should return a non-nil value after a calling
9477 `org-store-link-props' with a list of properties and values.
9478 Special properties are:
9480 :type The link prefix, like \"http\". This must be given.
9481 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9482 This is obligatory as well.
9483 :description Optional default description for the second pair
9484 of brackets in an Org-mode link. The user can still change
9485 this when inserting this link into an Org-mode buffer.
9487 In addition to these, any additional properties can be specified
9488 and then used in capture templates.")
9490 (defun org-add-link-type (type &optional follow export)
9491 "Add TYPE to the list of `org-link-types'.
9492 Re-compute all regular expressions depending on `org-link-types'
9494 FOLLOW and EXPORT are two functions.
9496 FOLLOW should take the link path as the single argument and do whatever
9497 is necessary to follow the link, for example find a file or display
9498 a mail message.
9500 EXPORT should format the link path for export to one of the export formats.
9501 It should be a function accepting three arguments:
9503 path the path of the link, the text after the prefix (like \"http:\")
9504 desc the description of the link, if any, or a description added by
9505 org-export-normalize-links if there is none
9506 format the export format, a symbol like `html' or `latex' or `ascii'..
9508 The function may use the FORMAT information to return different values
9509 depending on the format. The return value will be put literally into
9510 the exported file. If the return value is nil, this means Org should
9511 do what it normally does with links which do not have EXPORT defined.
9513 Org-mode has a built-in default for exporting links. If you are happy with
9514 this default, there is no need to define an export function for the link
9515 type. For a simple example of an export function, see `org-bbdb.el'."
9516 (add-to-list 'org-link-types type t)
9517 (org-make-link-regexps)
9518 (if (assoc type org-link-protocols)
9519 (setcdr (assoc type org-link-protocols) (list follow export))
9520 (push (list type follow export) org-link-protocols)))
9522 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9523 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9525 ;;;###autoload
9526 (defun org-store-link (arg)
9527 "\\<org-mode-map>Store an org-link to the current location.
9528 This link is added to `org-stored-links' and can later be inserted
9529 into an org-buffer with \\[org-insert-link].
9531 For some link types, a prefix arg is interpreted.
9532 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9533 For file links, arg negates `org-context-in-file-links'.
9535 A double prefix arg force skipping storing functions that are not
9536 part of Org's core.
9538 A triple prefix arg force storing a link for each line in the
9539 active region."
9540 (interactive "P")
9541 (org-load-modules-maybe)
9542 (if (and (equal arg '(64)) (org-region-active-p))
9543 (save-excursion
9544 (let ((end (region-end)))
9545 (goto-char (region-beginning))
9546 (set-mark (point))
9547 (while (< (point-at-eol) end)
9548 (move-end-of-line 1) (activate-mark)
9549 (let (current-prefix-arg)
9550 (call-interactively 'org-store-link))
9551 (move-beginning-of-line 2)
9552 (set-mark (point)))))
9553 (org-with-limited-levels
9554 (setq org-store-link-plist nil)
9555 (let (link cpltxt desc description search
9556 txt custom-id agenda-link sfuns sfunsn)
9557 (cond
9559 ;; Store a link using an external link type
9560 ((and (not (equal arg '(16)))
9561 (setq sfuns
9562 (delq
9563 nil (mapcar (lambda (f)
9564 (let (fs) (if (funcall f) (push f fs))))
9565 org-store-link-functions))
9566 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9567 (or (and (cdr sfuns)
9568 (funcall (intern
9569 (completing-read
9570 "Which function for creating the link? "
9571 sfunsn nil t (car sfunsn)))))
9572 (funcall (caar sfuns)))
9573 (setq link (plist-get org-store-link-plist :link)
9574 desc (or (plist-get org-store-link-plist
9575 :description) link))))
9577 ;; Store a link from a source code buffer
9578 ((org-src-edit-buffer-p)
9579 (let (label gc)
9580 (while (or (not label)
9581 (save-excursion
9582 (save-restriction
9583 (widen)
9584 (goto-char (point-min))
9585 (re-search-forward
9586 (regexp-quote (format org-coderef-label-format label))
9587 nil t))))
9588 (when label (message "Label exists already") (sit-for 2))
9589 (setq label (read-string "Code line label: " label)))
9590 (end-of-line 1)
9591 (setq link (format org-coderef-label-format label))
9592 (setq gc (- 79 (length link)))
9593 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9594 (insert link)
9595 (setq link (concat "(" label ")") desc nil)))
9597 ;; We are in the agenda, link to referenced location
9598 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9599 (let ((m (or (get-text-property (point) 'org-hd-marker)
9600 (get-text-property (point) 'org-marker))))
9601 (when m
9602 (org-with-point-at m
9603 (setq agenda-link
9604 (if (org-called-interactively-p 'any)
9605 (call-interactively 'org-store-link)
9606 (org-store-link nil)))))))
9608 ((eq major-mode 'calendar-mode)
9609 (let ((cd (calendar-cursor-to-date)))
9610 (setq link
9611 (format-time-string
9612 (car org-time-stamp-formats)
9613 (apply 'encode-time
9614 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9615 nil nil nil))))
9616 (org-store-link-props :type "calendar" :date cd)))
9618 ((eq major-mode 'help-mode)
9619 (setq link (concat "help:" (save-excursion
9620 (goto-char (point-min))
9621 (looking-at "^[^ ]+")
9622 (match-string 0))))
9623 (org-store-link-props :type "help"))
9625 ((eq major-mode 'w3-mode)
9626 (setq cpltxt (if (and (buffer-name)
9627 (not (string-match "Untitled" (buffer-name))))
9628 (buffer-name)
9629 (url-view-url t))
9630 link (url-view-url t))
9631 (org-store-link-props :type "w3" :url (url-view-url t)))
9633 ((eq major-mode 'image-mode)
9634 (setq cpltxt (concat "file:"
9635 (abbreviate-file-name buffer-file-name))
9636 link cpltxt)
9637 (org-store-link-props :type "image" :file buffer-file-name))
9639 ;; In dired, store a link to the file of the current line
9640 ((derived-mode-p 'dired-mode)
9641 (let ((file (dired-get-filename nil t)))
9642 (setq file (if file
9643 (abbreviate-file-name
9644 (expand-file-name (dired-get-filename nil t)))
9645 ;; otherwise, no file so use current directory.
9646 default-directory))
9647 (setq cpltxt (concat "file:" file)
9648 link cpltxt)))
9650 ((setq search (run-hook-with-args-until-success
9651 'org-create-file-search-functions))
9652 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9653 "::" search))
9654 (setq cpltxt (or description link)))
9656 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9657 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9658 (cond
9659 ;; Store a link using the target at point
9660 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9661 (setq cpltxt
9662 (concat "file:"
9663 (abbreviate-file-name
9664 (buffer-file-name (buffer-base-buffer)))
9665 "::" (match-string 1))
9666 link cpltxt))
9667 ((and (featurep 'org-id)
9668 (or (eq org-id-link-to-org-use-id t)
9669 (and (org-called-interactively-p 'any)
9670 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9671 (and (eq org-id-link-to-org-use-id
9672 'create-if-interactive-and-no-custom-id)
9673 (not custom-id))))
9674 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9675 ;; Store a link using the ID at point
9676 (setq link (condition-case nil
9677 (prog1 (org-id-store-link)
9678 (setq desc (or (plist-get org-store-link-plist
9679 :description)
9680 "")))
9681 (error
9682 ;; Probably before first headline, link only to file
9683 (concat "file:"
9684 (abbreviate-file-name
9685 (buffer-file-name (buffer-base-buffer))))))))
9687 ;; Just link to current headline
9688 (setq cpltxt (concat "file:"
9689 (abbreviate-file-name
9690 (buffer-file-name (buffer-base-buffer)))))
9691 ;; Add a context search string
9692 (when (org-xor org-context-in-file-links arg)
9693 (let* ((ee (org-element-at-point))
9694 (et (org-element-type ee))
9695 (ev (plist-get (cadr ee) :value))
9696 (ek (plist-get (cadr ee) :key))
9697 (eok (and (stringp ek) (string-match "name" ek))))
9698 (setq txt (cond
9699 ((org-at-heading-p) nil)
9700 ((and (eq et 'keyword) eok) ev)
9701 ((org-region-active-p)
9702 (buffer-substring (region-beginning) (region-end)))))
9703 (when (or (null txt) (string-match "\\S-" txt))
9704 (setq cpltxt
9705 (concat cpltxt "::"
9706 (condition-case nil
9707 (org-make-org-heading-search-string txt)
9708 (error "")))
9709 desc (or (and (eq et 'keyword) eok ev)
9710 (nth 4 (ignore-errors (org-heading-components)))
9711 "NONE")))))
9712 (if (string-match "::\\'" cpltxt)
9713 (setq cpltxt (substring cpltxt 0 -2)))
9714 (setq link cpltxt))))
9716 ((buffer-file-name (buffer-base-buffer))
9717 ;; Just link to this file here.
9718 (setq cpltxt (concat "file:"
9719 (abbreviate-file-name
9720 (buffer-file-name (buffer-base-buffer)))))
9721 ;; Add a context string.
9722 (when (org-xor org-context-in-file-links arg)
9723 (setq txt (if (org-region-active-p)
9724 (buffer-substring (region-beginning) (region-end))
9725 (buffer-substring (point-at-bol) (point-at-eol))))
9726 ;; Only use search option if there is some text.
9727 (when (string-match "\\S-" txt)
9728 (setq cpltxt
9729 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9730 desc "NONE")))
9731 (setq link cpltxt))
9733 ((org-called-interactively-p 'interactive)
9734 (user-error "No method for storing a link from this buffer"))
9736 (t (setq link nil)))
9738 ;; We're done setting link and desc, clean up
9739 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9740 (setq link (or link cpltxt)
9741 desc (or desc cpltxt))
9742 (cond ((equal desc "NONE") (setq desc nil))
9743 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9744 (let ((d0 (match-string 3 desc))
9745 (p0 (match-string 5 desc)))
9746 (setq desc
9747 (replace-regexp-in-string
9748 org-bracket-link-regexp
9749 (concat (or p0 d0)
9750 (if (equal (length (match-string 0 desc))
9751 (length desc)) "*" "")) desc)))))
9753 ;; Return the link
9754 (if (not (and (or (org-called-interactively-p 'any)
9755 executing-kbd-macro) link))
9756 (or agenda-link (and link (org-make-link-string link desc)))
9757 (push (list link desc) org-stored-links)
9758 (message "Stored: %s" (or desc link))
9759 (when custom-id
9760 (setq link (concat "file:" (abbreviate-file-name
9761 (buffer-file-name)) "::#" custom-id))
9762 (push (list link desc) org-stored-links))
9763 (car org-stored-links))))))
9765 (defun org-store-link-props (&rest plist)
9766 "Store link properties, extract names and addresses."
9767 (let (x adr)
9768 (when (setq x (plist-get plist :from))
9769 (setq adr (mail-extract-address-components x))
9770 (setq plist (plist-put plist :fromname (car adr)))
9771 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9772 (when (setq x (plist-get plist :to))
9773 (setq adr (mail-extract-address-components x))
9774 (setq plist (plist-put plist :toname (car adr)))
9775 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9776 (let ((from (plist-get plist :from))
9777 (to (plist-get plist :to)))
9778 (when (and from to org-from-is-user-regexp)
9779 (setq plist
9780 (plist-put plist :fromto
9781 (if (string-match org-from-is-user-regexp from)
9782 (concat "to %t")
9783 (concat "from %f"))))))
9784 (setq org-store-link-plist plist))
9786 (defun org-add-link-props (&rest plist)
9787 "Add these properties to the link property list."
9788 (let (key value)
9789 (while plist
9790 (setq key (pop plist) value (pop plist))
9791 (setq org-store-link-plist
9792 (plist-put org-store-link-plist key value)))))
9794 (defun org-email-link-description (&optional fmt)
9795 "Return the description part of an email link.
9796 This takes information from `org-store-link-plist' and formats it
9797 according to FMT (default from `org-email-link-description-format')."
9798 (setq fmt (or fmt org-email-link-description-format))
9799 (let* ((p org-store-link-plist)
9800 (to (plist-get p :toaddress))
9801 (from (plist-get p :fromaddress))
9802 (table
9803 (list
9804 (cons "%c" (plist-get p :fromto))
9805 (cons "%F" (plist-get p :from))
9806 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9807 (cons "%T" (plist-get p :to))
9808 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9809 (cons "%s" (plist-get p :subject))
9810 (cons "%d" (plist-get p :date))
9811 (cons "%m" (plist-get p :message-id)))))
9812 (when (string-match "%c" fmt)
9813 ;; Check if the user wrote this message
9814 (if (and org-from-is-user-regexp from to
9815 (save-match-data (string-match org-from-is-user-regexp from)))
9816 (setq fmt (replace-match "to %t" t t fmt))
9817 (setq fmt (replace-match "from %f" t t fmt))))
9818 (org-replace-escapes fmt table)))
9820 (defun org-make-org-heading-search-string (&optional string)
9821 "Make search string for the current headline or STRING."
9822 (let ((s (or string
9823 (and (derived-mode-p 'org-mode)
9824 (save-excursion
9825 (org-back-to-heading t)
9826 (org-element-property :raw-value (org-element-at-point))))))
9827 (lines org-context-in-file-links))
9828 (or string (setq s (concat "*" s))) ; Add * for headlines
9829 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9830 (when (and string (integerp lines) (> lines 0))
9831 (let ((slines (org-split-string s "\n")))
9832 (when (< lines (length slines))
9833 (setq s (mapconcat
9834 'identity
9835 (reverse (nthcdr (- (length slines) lines)
9836 (reverse slines))) "\n")))))
9837 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9839 (defun org-make-link-string (link &optional description)
9840 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9841 (unless (string-match "\\S-" link)
9842 (error "Empty link"))
9843 (when (and description
9844 (stringp description)
9845 (not (string-match "\\S-" description)))
9846 (setq description nil))
9847 (when (stringp description)
9848 ;; Remove brackets from the description, they are fatal.
9849 (while (string-match "\\[" description)
9850 (setq description (replace-match "{" t t description)))
9851 (while (string-match "\\]" description)
9852 (setq description (replace-match "}" t t description))))
9853 (when (equal link description)
9854 ;; No description needed, it is identical
9855 (setq description nil))
9856 (when (and (not description)
9857 (not (string-match (org-image-file-name-regexp) link))
9858 (not (equal link (org-link-escape link))))
9859 (setq description (org-extract-attributes link)))
9860 (setq link
9861 (cond ((string-match (org-image-file-name-regexp) link) link)
9862 ((string-match org-link-types-re link)
9863 (concat (match-string 1 link)
9864 (org-link-escape (substring link (match-end 1)))))
9865 (t (org-link-escape link))))
9866 (concat "[[" link "]"
9867 (if description (concat "[" description "]") "")
9868 "]"))
9870 (defconst org-link-escape-chars
9871 ;;%20 %2B %3B %3D %5B %5D
9872 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9873 "List of characters that should be escaped in a link when stored to Org.
9874 This is the list that is used for internal purposes.")
9876 (defconst org-link-escape-chars-browser
9877 ;;%20 %22
9878 '(?\ ?\")
9879 "List of characters to be escaped before handing over to the browser.
9880 If you consider using this constant then you probably want to use
9881 the function `org-link-escape-browser' instead. See there why
9882 this constant is a candidate to be removed once Org drops support
9883 for Emacs 24.1 and 24.2.")
9885 (defun org-link-escape (text &optional table merge)
9886 "Return percent escaped representation of TEXT.
9887 TEXT is a string with the text to escape.
9888 Optional argument TABLE is a list with characters that should be
9889 escaped. When nil, `org-link-escape-chars' is used.
9890 If optional argument MERGE is set, merge TABLE into
9891 `org-link-escape-chars'."
9892 (cond
9893 ((and table merge)
9894 (mapc (lambda (defchr)
9895 (unless (member defchr table)
9896 (setq table (cons defchr table)))) org-link-escape-chars))
9897 ((null table)
9898 (setq table org-link-escape-chars)))
9899 (mapconcat
9900 (lambda (char)
9901 (if (or (member char table)
9902 (and (or (< char 32) (= char ?\%) (> char 126))
9903 org-url-hexify-p))
9904 (mapconcat (lambda (sequence-element)
9905 (format "%%%.2X" sequence-element))
9906 (or (encode-coding-char char 'utf-8)
9907 (error "Unable to percent escape character: %s"
9908 (char-to-string char))) "")
9909 (char-to-string char))) text ""))
9911 (defun org-link-escape-browser (text)
9912 "Escape some characters before handing over to the browser.
9913 This function is a candidate to be removed together with the
9914 constant `org-link-escape-chars-browser' once Org drops support
9915 for Emacs 24.1 and 24.2. All calls to this function will have to
9916 be replaced with `url-encode-url' which is available since Emacs
9917 24.3.1."
9918 ;; Example with the Org link
9919 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
9920 ;; to open the browser with +subject:"Release 8.2" filled into the
9921 ;; query field: In this case the variable TEXT contains the
9922 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
9923 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
9924 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
9925 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
9926 (if (fboundp 'url-encode-url)
9927 (url-encode-url text)
9928 (if (org-string-match-p
9929 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9930 text)
9931 (org-link-escape text org-link-escape-chars-browser)
9932 text)))
9934 (defun org-link-unescape (str)
9935 "Unhex hexified Unicode strings as returned from the JavaScript function
9936 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9937 (unless (and (null str) (string= "" str))
9938 (let ((pos 0) (case-fold-search t) unhexed)
9939 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9940 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9941 (setq str (replace-match unhexed t t str))
9942 (setq pos (+ pos (length unhexed))))))
9943 str)
9945 (defun org-link-unescape-compound (hex)
9946 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9947 Note: this function also decodes single byte encodings like
9948 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9949 (save-match-data
9950 (let* ((bytes (cdr (split-string hex "%")))
9951 (ret "")
9952 (eat 0)
9953 (sum 0))
9954 (while bytes
9955 (let* ((val (string-to-number (pop bytes) 16))
9956 (shift-xor
9957 (if (= 0 eat)
9958 (cond
9959 ((>= val 252) (cons 6 252))
9960 ((>= val 248) (cons 5 248))
9961 ((>= val 240) (cons 4 240))
9962 ((>= val 224) (cons 3 224))
9963 ((>= val 192) (cons 2 192))
9964 (t (cons 0 0)))
9965 (cons 6 128))))
9966 (if (>= val 192) (setq eat (car shift-xor)))
9967 (setq val (logxor val (cdr shift-xor)))
9968 (setq sum (+ (lsh sum (car shift-xor)) val))
9969 (if (> eat 0) (setq eat (- eat 1)))
9970 (cond
9971 ((= 0 eat) ;multi byte
9972 (setq ret (concat ret (org-char-to-string sum)))
9973 (setq sum 0))
9974 ((not bytes) ; single byte(s)
9975 (setq ret (org-link-unescape-single-byte-sequence hex))))
9976 )) ;; end (while bytes
9977 ret )))
9979 (defun org-link-unescape-single-byte-sequence (hex)
9980 "Unhexify hex-encoded single byte character sequences."
9981 (mapconcat (lambda (byte)
9982 (char-to-string (string-to-number byte 16)))
9983 (cdr (split-string hex "%")) ""))
9985 (defun org-xor (a b)
9986 "Exclusive or."
9987 (if a (not b) b))
9989 (defun org-fixup-message-id-for-http (s)
9990 "Replace special characters in a message id, so it can be used in an http query."
9991 (when (string-match "%" s)
9992 (setq s (mapconcat (lambda (c)
9993 (if (eq c ?%)
9994 "%25"
9995 (char-to-string c)))
9996 s "")))
9997 (while (string-match "<" s)
9998 (setq s (replace-match "%3C" t t s)))
9999 (while (string-match ">" s)
10000 (setq s (replace-match "%3E" t t s)))
10001 (while (string-match "@" s)
10002 (setq s (replace-match "%40" t t s)))
10005 (defun org-link-prettify (link)
10006 "Return a human-readable representation of LINK.
10007 The car of LINK must be a raw link.
10008 The cdr of LINK must be either a link description or nil."
10009 (let ((desc (or (cadr link) "<no description>")))
10010 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10011 "<" (car link) ">")))
10013 ;;;###autoload
10014 (defun org-insert-link-global ()
10015 "Insert a link like Org-mode does.
10016 This command can be called in any mode to insert a link in Org-mode syntax."
10017 (interactive)
10018 (org-load-modules-maybe)
10019 (org-run-like-in-org-mode 'org-insert-link))
10021 (defun org-insert-all-links (arg &optional pre post)
10022 "Insert all links in `org-stored-links'.
10023 When a universal prefix, do not delete the links from `org-stored-links'.
10024 When `ARG' is a number, insert the last N link(s).
10025 `PRE' and `POST' are optional arguments to define a string to
10026 prepend or to append."
10027 (interactive "P")
10028 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10029 (links (copy-seq org-stored-links))
10030 (pr (or pre "- "))
10031 (po (or post "\n"))
10032 (cnt 1) l)
10033 (if (null org-stored-links)
10034 (message "No link to insert")
10035 (while (and (or (listp arg) (>= arg cnt))
10036 (setq l (if (listp arg)
10037 (pop links)
10038 (pop org-stored-links))))
10039 (setq cnt (1+ cnt))
10040 (insert pr)
10041 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10042 (insert po)))))
10044 (defun org-insert-last-stored-link (arg)
10045 "Insert the last link stored in `org-stored-links'."
10046 (interactive "p")
10047 (org-insert-all-links arg "" "\n"))
10049 (defun org-link-fontify-links-to-this-file ()
10050 "Fontify links to the current file in `org-stored-links'."
10051 (let ((f (buffer-file-name)) a b)
10052 (setq a (mapcar (lambda(l)
10053 (let ((ll (car l)))
10054 (when (and (string-match "^file:\\(.+\\)::" ll)
10055 (equal f (expand-file-name (match-string 1 ll))))
10056 ll)))
10057 org-stored-links))
10058 (when (featurep 'org-id)
10059 (setq b (mapcar (lambda(l)
10060 (let ((ll (car l)))
10061 (when (and (string-match "^id:\\(.+\\)$" ll)
10062 (equal f (expand-file-name
10063 (or (org-id-find-id-file
10064 (match-string 1 ll)) ""))))
10065 ll)))
10066 org-stored-links)))
10067 (mapcar (lambda(l)
10068 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10069 (delq nil (append a b)))))
10071 (defvar org-link-links-in-this-file nil)
10072 (defun org-insert-link (&optional complete-file link-location default-description)
10073 "Insert a link. At the prompt, enter the link.
10075 Completion can be used to insert any of the link protocol prefixes like
10076 http or ftp in use.
10078 The history can be used to select a link previously stored with
10079 `org-store-link'. When the empty string is entered (i.e. if you just
10080 press RET at the prompt), the link defaults to the most recently
10081 stored link. As SPC triggers completion in the minibuffer, you need to
10082 use M-SPC or C-q SPC to force the insertion of a space character.
10084 You will also be prompted for a description, and if one is given, it will
10085 be displayed in the buffer instead of the link.
10087 If there is already a link at point, this command will allow you to edit link
10088 and description parts.
10090 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10091 be selected using completion. The path to the file will be relative to the
10092 current directory if the file is in the current directory or a subdirectory.
10093 Otherwise, the link will be the absolute path as completed in the minibuffer
10094 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10095 option `org-link-file-path-type'.
10097 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10098 the current directory or below.
10100 With three \\[universal-argument] prefixes, negate the meaning of
10101 `org-keep-stored-link-after-insertion'.
10103 If `org-make-link-description-function' is non-nil, this function will be
10104 called with the link target, and the result will be the default
10105 link description.
10107 If the LINK-LOCATION parameter is non-nil, this value will be
10108 used as the link location instead of reading one interactively.
10110 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10111 be used as the default description."
10112 (interactive "P")
10113 (let* ((wcf (current-window-configuration))
10114 (origbuf (current-buffer))
10115 (region (if (org-region-active-p)
10116 (buffer-substring (region-beginning) (region-end))))
10117 (remove (and region (list (region-beginning) (region-end))))
10118 (desc region)
10119 tmphist ; byte-compile incorrectly complains about this
10120 (link link-location)
10121 (abbrevs org-link-abbrev-alist-local)
10122 entry file all-prefixes auto-desc)
10123 (cond
10124 (link-location) ; specified by arg, just use it.
10125 ((org-in-regexp org-bracket-link-regexp 1)
10126 ;; We do have a link at point, and we are going to edit it.
10127 (setq remove (list (match-beginning 0) (match-end 0)))
10128 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10129 (setq link (read-string "Link: "
10130 (org-link-unescape
10131 (org-match-string-no-properties 1)))))
10132 ((or (org-in-regexp org-angle-link-re)
10133 (org-in-regexp org-plain-link-re))
10134 ;; Convert to bracket link
10135 (setq remove (list (match-beginning 0) (match-end 0))
10136 link (read-string "Link: "
10137 (org-remove-angle-brackets (match-string 0)))))
10138 ((member complete-file '((4) (16)))
10139 ;; Completing read for file names.
10140 (setq link (org-file-complete-link complete-file)))
10142 ;; Read link, with completion for stored links.
10143 (org-link-fontify-links-to-this-file)
10144 (org-switch-to-buffer-other-window "*Org Links*")
10145 (with-current-buffer "*Org Links*"
10146 (erase-buffer)
10147 (insert "Insert a link.
10148 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10149 (when org-stored-links
10150 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10151 (insert (mapconcat 'org-link-prettify
10152 (reverse org-stored-links) "\n")))
10153 (goto-char (point-min)))
10154 (let ((cw (selected-window)))
10155 (select-window (get-buffer-window "*Org Links*" 'visible))
10156 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10157 (unless (pos-visible-in-window-p (point-max))
10158 (org-fit-window-to-buffer))
10159 (and (window-live-p cw) (select-window cw)))
10160 ;; Fake a link history, containing the stored links.
10161 (setq tmphist (append (mapcar 'car org-stored-links)
10162 org-insert-link-history))
10163 (setq all-prefixes (append (mapcar 'car abbrevs)
10164 (mapcar 'car org-link-abbrev-alist)
10165 org-link-types))
10166 (unwind-protect
10167 (progn
10168 (setq link
10169 (org-completing-read
10170 "Link: "
10171 (append
10172 (mapcar (lambda (x) (concat x ":"))
10173 all-prefixes)
10174 (mapcar 'car org-stored-links))
10175 nil nil nil
10176 'tmphist
10177 (caar org-stored-links)))
10178 (if (not (string-match "\\S-" link))
10179 (user-error "No link selected"))
10180 (mapc (lambda(l)
10181 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10182 org-stored-links)
10183 (if (or (member link all-prefixes)
10184 (and (equal ":" (substring link -1))
10185 (member (substring link 0 -1) all-prefixes)
10186 (setq link (substring link 0 -1))))
10187 (setq link (with-current-buffer origbuf
10188 (org-link-try-special-completion link)))))
10189 (set-window-configuration wcf)
10190 (kill-buffer "*Org Links*"))
10191 (setq entry (assoc link org-stored-links))
10192 (or entry (push link org-insert-link-history))
10193 (setq desc (or desc (nth 1 entry)))))
10195 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10196 (not org-keep-stored-link-after-insertion))
10197 (setq org-stored-links (delq (assoc link org-stored-links)
10198 org-stored-links)))
10200 (if (and (string-match org-plain-link-re link)
10201 (not (string-match org-ts-regexp link)))
10202 ;; URL-like link, normalize the use of angular brackets.
10203 (setq link (org-remove-angle-brackets link)))
10205 ;; Check if we are linking to the current file with a search
10206 ;; option If yes, simplify the link by using only the search
10207 ;; option.
10208 (when (and buffer-file-name
10209 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10210 (let* ((path (match-string 1 link))
10211 (case-fold-search nil)
10212 (search (match-string 2 link)))
10213 (save-match-data
10214 (if (equal (file-truename buffer-file-name) (file-truename path))
10215 ;; We are linking to this same file, with a search option
10216 (setq link search)))))
10218 ;; Check if we can/should use a relative path. If yes, simplify the link
10219 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10220 (let* ((type (match-string 1 link))
10221 (path (match-string 2 link))
10222 (origpath path)
10223 (case-fold-search nil))
10224 (cond
10225 ((or (eq org-link-file-path-type 'absolute)
10226 (equal complete-file '(16)))
10227 (setq path (abbreviate-file-name (expand-file-name path))))
10228 ((eq org-link-file-path-type 'noabbrev)
10229 (setq path (expand-file-name path)))
10230 ((eq org-link-file-path-type 'relative)
10231 (setq path (file-relative-name path)))
10233 (save-match-data
10234 (if (string-match (concat "^" (regexp-quote
10235 (expand-file-name
10236 (file-name-as-directory
10237 default-directory))))
10238 (expand-file-name path))
10239 ;; We are linking a file with relative path name.
10240 (setq path (substring (expand-file-name path)
10241 (match-end 0)))
10242 (setq path (abbreviate-file-name (expand-file-name path)))))))
10243 (setq link (concat type path))
10244 (if (equal desc origpath)
10245 (setq desc path))))
10247 (if org-make-link-description-function
10248 (setq desc
10249 (or (condition-case nil
10250 (funcall org-make-link-description-function link desc)
10251 (error (progn (message "Can't get link description from `%s'"
10252 (symbol-name org-make-link-description-function))
10253 (sit-for 2) nil)))
10254 (read-string "Description: " default-description)))
10255 (if default-description (setq desc default-description)
10256 (setq desc (or (and auto-desc desc)
10257 (read-string "Description: " desc)))))
10259 (unless (string-match "\\S-" desc) (setq desc nil))
10260 (if remove (apply 'delete-region remove))
10261 (insert (org-make-link-string link desc))))
10263 (defun org-link-try-special-completion (type)
10264 "If there is completion support for link type TYPE, offer it."
10265 (let ((fun (intern (concat "org-" type "-complete-link"))))
10266 (if (functionp fun)
10267 (funcall fun)
10268 (read-string "Link (no completion support): " (concat type ":")))))
10270 (defun org-file-complete-link (&optional arg)
10271 "Create a file link using completion."
10272 (let (file link)
10273 (setq file (org-iread-file-name "File: "))
10274 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10275 (pwd1 (file-name-as-directory (abbreviate-file-name
10276 (expand-file-name ".")))))
10277 (cond
10278 ((equal arg '(16))
10279 (setq link (concat
10280 "file:"
10281 (abbreviate-file-name (expand-file-name file)))))
10282 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10283 (setq link (concat "file:" (match-string 1 file))))
10284 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10285 (expand-file-name file))
10286 (setq link (concat
10287 "file:" (match-string 1 (expand-file-name file)))))
10288 (t (setq link (concat "file:" file)))))
10289 link))
10291 (defun org-iread-file-name (&rest args)
10292 "Read-file-name using `ido-mode' speedup if available.
10293 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10294 See `read-file-name' for a description of parameters."
10295 (org-without-partial-completion
10296 (if (and org-completion-use-ido
10297 (fboundp 'ido-read-file-name)
10298 (boundp 'ido-mode) ido-mode
10299 (listp (second args)))
10300 (let ((ido-enter-matching-directory nil))
10301 (apply 'ido-read-file-name args))
10302 (apply 'read-file-name args))))
10304 (defun org-completing-read (&rest args)
10305 "Completing-read with SPACE being a normal character."
10306 (let ((enable-recursive-minibuffers t)
10307 (minibuffer-local-completion-map
10308 (copy-keymap minibuffer-local-completion-map)))
10309 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10310 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10311 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10312 (apply 'org-icompleting-read args)))
10314 (defun org-completing-read-no-i (&rest args)
10315 (let (org-completion-use-ido org-completion-use-iswitchb)
10316 (apply 'org-completing-read args)))
10318 (defun org-iswitchb-completing-read (prompt choices &rest args)
10319 "Use iswitch as a completing-read replacement to choose from choices.
10320 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10321 from."
10322 (let* ((iswitchb-use-virtual-buffers nil)
10323 (iswitchb-make-buflist-hook
10324 (lambda ()
10325 (setq iswitchb-temp-buflist choices))))
10326 (iswitchb-read-buffer prompt)))
10328 (defun org-icompleting-read (&rest args)
10329 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10330 (org-without-partial-completion
10331 (if (and org-completion-use-ido
10332 (fboundp 'ido-completing-read)
10333 (boundp 'ido-mode) ido-mode
10334 (listp (second args)))
10335 (let ((ido-enter-matching-directory nil))
10336 (apply 'ido-completing-read (concat (car args))
10337 (if (consp (car (nth 1 args)))
10338 (mapcar 'car (nth 1 args))
10339 (nth 1 args))
10340 (cddr args)))
10341 (if (and org-completion-use-iswitchb
10342 (boundp 'iswitchb-mode) iswitchb-mode
10343 (listp (second args)))
10344 (apply 'org-iswitchb-completing-read (concat (car args))
10345 (if (consp (car (nth 1 args)))
10346 (mapcar 'car (nth 1 args))
10347 (nth 1 args))
10348 (cddr args))
10349 (apply 'completing-read args)))))
10351 (defun org-extract-attributes (s)
10352 "Extract the attributes cookie from a string and set as text property."
10353 (let (a attr (start 0) key value)
10354 (save-match-data
10355 (when (string-match "{{\\([^}]+\\)}}$" s)
10356 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10357 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10358 (setq key (match-string 1 a) value (match-string 2 a)
10359 start (match-end 0)
10360 attr (plist-put attr (intern key) value))))
10361 (org-add-props s nil 'org-attr attr))
10364 ;;; Opening/following a link
10366 (defvar org-link-search-failed nil)
10368 (defvar org-open-link-functions nil
10369 "Hook for functions finding a plain text link.
10370 These functions must take a single argument, the link content.
10371 They will be called for links that look like [[link text][description]]
10372 when LINK TEXT does not have a protocol like \"http:\" and does not look
10373 like a filename (e.g. \"./blue.png\").
10375 These functions will be called *before* Org attempts to resolve the
10376 link by doing text searches in the current buffer - so if you want a
10377 link \"[[target]]\" to still find \"<<target>>\", your function should
10378 handle this as a special case.
10380 When the function does handle the link, it must return a non-nil value.
10381 If it decides that it is not responsible for this link, it must return
10382 nil to indicate that that Org-mode can continue with other options
10383 like exact and fuzzy text search.")
10385 (defun org-next-link (&optional search-backward)
10386 "Move forward to the next link.
10387 If the link is in hidden text, expose it."
10388 (interactive "P")
10389 (when (and org-link-search-failed (eq this-command last-command))
10390 (goto-char (point-min))
10391 (message "Link search wrapped back to beginning of buffer"))
10392 (setq org-link-search-failed nil)
10393 (let* ((pos (point))
10394 (ct (org-context))
10395 (a (assoc :link ct))
10396 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10397 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10398 ((looking-at org-any-link-re)
10399 ;; Don't stay stuck at link without an org-link face
10400 (forward-char (if search-backward -1 1))))
10401 (if (funcall srch-fun org-any-link-re nil t)
10402 (progn
10403 (goto-char (match-beginning 0))
10404 (if (outline-invisible-p) (org-show-context)))
10405 (goto-char pos)
10406 (setq org-link-search-failed t)
10407 (message "No further link found"))))
10409 (defun org-previous-link ()
10410 "Move backward to the previous link.
10411 If the link is in hidden text, expose it."
10412 (interactive)
10413 (funcall 'org-next-link t))
10415 (defun org-translate-link (s)
10416 "Translate a link string if a translation function has been defined."
10417 (if (and org-link-translation-function
10418 (fboundp org-link-translation-function)
10419 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10420 (progn
10421 (setq s (funcall org-link-translation-function
10422 (match-string 1 s) (match-string 2 s)))
10423 (concat (car s) ":" (cdr s)))
10426 (defun org-translate-link-from-planner (type path)
10427 "Translate a link from Emacs Planner syntax so that Org can follow it.
10428 This is still an experimental function, your mileage may vary."
10429 (cond
10430 ((member type '("http" "https" "news" "ftp"))
10431 ;; standard Internet links are the same.
10432 nil)
10433 ((and (equal type "irc") (string-match "^//" path))
10434 ;; Planner has two / at the beginning of an irc link, we have 1.
10435 ;; We should have zero, actually....
10436 (setq path (substring path 1)))
10437 ((and (equal type "lisp") (string-match "^/" path))
10438 ;; Planner has a slash, we do not.
10439 (setq type "elisp" path (substring path 1)))
10440 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10441 ;; A typical message link. Planner has the id after the final slash,
10442 ;; we separate it with a hash mark
10443 (setq path (concat (match-string 1 path) "#"
10444 (org-remove-angle-brackets (match-string 2 path))))))
10445 (cons type path))
10447 (defun org-find-file-at-mouse (ev)
10448 "Open file link or URL at mouse."
10449 (interactive "e")
10450 (mouse-set-point ev)
10451 (org-open-at-point 'in-emacs))
10453 (defun org-open-at-mouse (ev)
10454 "Open file link or URL at mouse.
10455 See the docstring of `org-open-file' for details."
10456 (interactive "e")
10457 (mouse-set-point ev)
10458 (if (eq major-mode 'org-agenda-mode)
10459 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10460 (org-open-at-point))
10462 (defvar org-window-config-before-follow-link nil
10463 "The window configuration before following a link.
10464 This is saved in case the need arises to restore it.")
10466 (defvar org-open-link-marker (make-marker)
10467 "Marker pointing to the location where `org-open-at-point' was called.")
10469 ;;;###autoload
10470 (defun org-open-at-point-global ()
10471 "Follow a link like Org-mode does.
10472 This command can be called in any mode to follow a link that has
10473 Org-mode syntax."
10474 (interactive)
10475 (org-run-like-in-org-mode 'org-open-at-point))
10477 ;;;###autoload
10478 (defun org-open-link-from-string (s &optional arg reference-buffer)
10479 "Open a link in the string S, as if it was in Org-mode."
10480 (interactive "sLink: \nP")
10481 (let ((reference-buffer (or reference-buffer (current-buffer))))
10482 (with-temp-buffer
10483 (let ((org-inhibit-startup (not reference-buffer)))
10484 (org-mode)
10485 (insert s)
10486 (goto-char (point-min))
10487 (when reference-buffer
10488 (setq org-link-abbrev-alist-local
10489 (with-current-buffer reference-buffer
10490 org-link-abbrev-alist-local)))
10491 (org-open-at-point arg reference-buffer)))))
10493 (defvar org-open-at-point-functions nil
10494 "Hook that is run when following a link at point.
10496 Functions in this hook must return t if they identify and follow
10497 a link at point. If they don't find anything interesting at point,
10498 they must return nil.")
10500 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10501 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10502 (defun org-open-at-point (&optional arg reference-buffer)
10503 "Open link, timestamp, footnote or tags at point.
10505 When point is on a link, follow it. Normally, files will be
10506 opened by an appropriate application. If the optional prefix
10507 argument ARG is non-nil, Emacs will visit the file. With
10508 a double prefix argument, try to open outside of Emacs, in the
10509 application the system uses for this file type.
10511 When point is on a timestamp, open the agenda at the day
10512 specified.
10514 When point is a footnote definition, move to the first reference
10515 found. If it is on a reference, move to the associated
10516 definition.
10518 When point is on a headline, display a list of every link in the
10519 entry, so it is possible to pick one, or all, of them. If point
10520 is on a tag, call `org-tags-view' instead.
10522 When optional argument REFERENCE-BUFFER is non-nil, it should
10523 specify a buffer from where the link search should happen. This
10524 is used internally by `org-open-link-from-string'."
10525 (interactive "P")
10526 ;; On a code block, open block's results.
10527 (unless (call-interactively #'org-babel-open-src-block-result)
10528 (org-load-modules-maybe)
10529 (move-marker org-open-link-marker (point))
10530 (setq org-window-config-before-follow-link (current-window-configuration))
10531 (org-remove-occur-highlights nil nil t)
10532 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10533 (let* ((context (org-element-context)) type)
10534 ;; On an unsupported type, check if point is contained within
10535 ;; a support one.
10536 (while (and (not (memq (setq type (org-element-type context))
10537 '(headline inlinetask link footnote-definition
10538 footnote-reference timestamp)))
10539 (setq context (org-element-property :parent context))))
10540 (cond
10541 ;; Unsupported context: return an error.
10542 ((not context) (user-error "No link found"))
10543 ;; On a headline or an inlinetask, but not on a timestamp,
10544 ;; a link, a footnote reference or on tags.
10545 ((and (memq type '(headline inlinetask))
10546 ;; Not on tags.
10547 (progn (save-excursion (beginning-of-line)
10548 (looking-at org-complex-heading-regexp))
10549 (or (not (match-beginning 5))
10550 (< (point) (match-beginning 5)))))
10551 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10552 (links (car data))
10553 (links-end (cdr data)))
10554 (if links
10555 (dolist (link (if (stringp links) (list links) links))
10556 (search-forward link nil links-end)
10557 (goto-char (match-beginning 0))
10558 (org-open-at-point))
10559 (require 'org-attach)
10560 (org-attach-reveal 'if-exists))))
10561 ;; Do nothing on white spaces after an object, unless point
10562 ;; is right after it.
10563 ((> (point)
10564 (save-excursion
10565 (goto-char (org-element-property :end context))
10566 (skip-chars-backward " \t")
10567 (point)))
10568 (user-error "No link found"))
10569 ((eq type 'timestamp) (org-follow-timestamp-link))
10570 ;; On tags within a headline or an inlinetask.
10571 ((and (memq type '(headline inlinetask))
10572 (progn (save-excursion (beginning-of-line)
10573 (looking-at org-complex-heading-regexp))
10574 (and (match-beginning 5)
10575 (>= (point) (match-beginning 5)))))
10576 (org-tags-view arg (substring (match-string 5) 0 -1)))
10577 ((eq type 'link)
10578 (let ((type (org-element-property :type context))
10579 (path (org-link-unescape (org-element-property :path context))))
10580 ;; Switch back to REFERENCE-BUFFER needed when called in
10581 ;; a temporary buffer through `org-open-link-from-string'.
10582 (with-current-buffer (or reference-buffer (current-buffer))
10583 (cond
10584 ((equal type "file")
10585 (if (string-match "[*?{]" (file-name-nondirectory path))
10586 (dired path)
10587 ;; Look into `org-link-protocols' in order to find
10588 ;; a DEDICATED-FUNCTION to open file. The function
10589 ;; will be applied on raw link instead of parsed
10590 ;; link due to the limitation in `org-add-link-type'
10591 ;; ("open" function called with a single argument).
10592 ;; If no such function is found, fallback to
10593 ;; `org-open-file'.
10595 ;; Note : "file+emacs" and "file+sys" types are
10596 ;; hard-coded in order to escape the previous
10597 ;; limitation.
10598 (let* ((option (org-element-property :search-option context))
10599 (app (org-element-property :application context))
10600 (dedicated-function
10601 (nth 1 (assoc app org-link-protocols))))
10602 (if dedicated-function
10603 (funcall dedicated-function
10604 (concat path
10605 (and option (concat "::" option))))
10606 (apply #'org-open-file
10607 path
10608 (cond (arg)
10609 ((equal app "emacs") 'emacs)
10610 ((equal app "sys") 'system))
10611 (cond ((not option) nil)
10612 ((org-string-match-p "\\`[0-9]+\\'" option)
10613 (list (string-to-number option)))
10614 (t (list nil
10615 (org-link-unescape option)))))))))
10616 ((assoc type org-link-protocols)
10617 (funcall (nth 1 (assoc type org-link-protocols)) path))
10618 ((equal type "help")
10619 (let ((f-or-v (intern path)))
10620 (cond ((fboundp f-or-v) (describe-function f-or-v))
10621 ((boundp f-or-v) (describe-variable f-or-v))
10622 (t (error "Not a known function or variable")))))
10623 ((member type '("http" "https" "ftp" "mailto" "news"))
10624 (browse-url (org-link-escape-browser (concat type ":" path))))
10625 ((equal type "doi")
10626 (browse-url
10627 (org-link-escape-browser (concat org-doi-server-url path))))
10628 ((equal type "message") (browse-url (concat type ":" path)))
10629 ((equal type "shell")
10630 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10631 (cmd path))
10632 (if (or (and (org-string-nw-p
10633 org-confirm-shell-link-not-regexp)
10634 (string-match
10635 org-confirm-shell-link-not-regexp cmd))
10636 (not org-confirm-shell-link-function)
10637 (funcall org-confirm-shell-link-function
10638 (format "Execute \"%s\" in shell? "
10639 (org-add-props cmd nil
10640 'face 'org-warning))))
10641 (progn
10642 (message "Executing %s" cmd)
10643 (shell-command cmd buf)
10644 (when (featurep 'midnight)
10645 (setq clean-buffer-list-kill-buffer-names
10646 (cons buf
10647 clean-buffer-list-kill-buffer-names))))
10648 (user-error "Abort"))))
10649 ((equal type "elisp")
10650 (let ((cmd path))
10651 (if (or (and (org-string-nw-p
10652 org-confirm-elisp-link-not-regexp)
10653 (org-string-match-p
10654 org-confirm-elisp-link-not-regexp cmd))
10655 (not org-confirm-elisp-link-function)
10656 (funcall org-confirm-elisp-link-function
10657 (format "Execute \"%s\" as elisp? "
10658 (org-add-props cmd nil
10659 'face 'org-warning))))
10660 (message "%s => %s" cmd
10661 (if (eq (string-to-char cmd) ?\()
10662 (eval (read cmd))
10663 (call-interactively (read cmd))))
10664 (user-error "Abort"))))
10665 ((equal type "id")
10666 (require 'ord-id)
10667 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10668 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10669 (unless (run-hook-with-args-until-success
10670 'org-open-link-functions path)
10671 (if (not arg) (org-mark-ring-push)
10672 (switch-to-buffer-other-window
10673 (org-get-buffer-for-internal-link (current-buffer))))
10674 (let ((cmd `(org-link-search
10675 ,(if (member type '("custom-id" "coderef"))
10676 (org-element-property :raw-link context)
10677 path)
10678 ,(cond ((equal arg '(4)) 'occur)
10679 ((equal arg '(16)) 'org-occur))
10680 ,(org-element-property :begin context))))
10681 (condition-case nil
10682 (let ((org-link-search-inhibit-query t))
10683 (eval cmd))
10684 (error (progn (widen) (eval cmd)))))))
10685 (t (browse-url-at-point))))))
10686 ;; On a footnote reference or at a footnote definition's label.
10687 ((or (eq type 'footnote-reference)
10688 (and (eq type 'footnote-definition)
10689 (save-excursion
10690 ;; Do not validate action when point is on the
10691 ;; spaces right after the footnote label, in
10692 ;; order to be on par with behaviour on links.
10693 (skip-chars-forward " \t")
10694 (let ((begin
10695 (org-element-property :contents-begin context)))
10696 (if begin (< (point) begin)
10697 (= (org-element-property :post-affiliated context)
10698 (line-beginning-position)))))))
10699 (org-footnote-action))
10700 (t (user-error "No link found")))))
10701 (move-marker org-open-link-marker nil)
10702 (run-hook-with-args 'org-follow-link-hook)))
10704 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10705 "Offer links in the current entry and return the selected link.
10706 If there is only one link, return it.
10707 If NTH is an integer, return the NTH link found.
10708 If ZERO is a string, check also this string for a link, and if
10709 there is one, return it."
10710 (with-current-buffer buffer
10711 (save-excursion
10712 (save-restriction
10713 (widen)
10714 (goto-char marker)
10715 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10716 "\\(" org-angle-link-re "\\)\\|"
10717 "\\(" org-plain-link-re "\\)"))
10718 (cnt ?0)
10719 (in-emacs (if (integerp nth) nil nth))
10720 have-zero end links link c)
10721 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10722 (push (match-string 0 zero) links)
10723 (setq cnt (1- cnt) have-zero t))
10724 (save-excursion
10725 (org-back-to-heading t)
10726 (setq end (save-excursion (outline-next-heading) (point)))
10727 (while (re-search-forward re end t)
10728 (push (match-string 0) links))
10729 (setq links (org-uniquify (reverse links))))
10730 (cond
10731 ((null links)
10732 (message "No links"))
10733 ((equal (length links) 1)
10734 (setq link (car links)))
10735 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10736 (setq link (nth (if have-zero nth (1- nth)) links)))
10737 (t ; we have to select a link
10738 (save-excursion
10739 (save-window-excursion
10740 (delete-other-windows)
10741 (with-output-to-temp-buffer "*Select Link*"
10742 (mapc (lambda (l)
10743 (if (not (string-match org-bracket-link-regexp l))
10744 (princ (format "[%c] %s\n" (incf cnt)
10745 (org-remove-angle-brackets l)))
10746 (if (match-end 3)
10747 (princ (format "[%c] %s (%s)\n" (incf cnt)
10748 (match-string 3 l) (match-string 1 l)))
10749 (princ (format "[%c] %s\n" (incf cnt)
10750 (match-string 1 l))))))
10751 links))
10752 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10753 (message "Select link to open, RET to open all:")
10754 (setq c (read-char-exclusive))
10755 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10756 (when (equal c ?q) (user-error "Abort"))
10757 (if (equal c ?\C-m)
10758 (setq link links)
10759 (setq nth (- c ?0))
10760 (if have-zero (setq nth (1+ nth)))
10761 (unless (and (integerp nth) (>= (length links) nth))
10762 (user-error "Invalid link selection"))
10763 (setq link (nth (1- nth) links)))))
10764 (cons link end))))))
10766 ;; TODO: These functions are deprecated since `org-open-at-point'
10767 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10768 (defun org-open-file-with-system (path)
10769 "Open file at PATH using the system way of opening it."
10770 (org-open-file path 'system))
10771 (defun org-open-file-with-emacs (path)
10772 "Open file at PATH in Emacs."
10773 (org-open-file path 'emacs))
10776 ;;; File search
10778 (defvar org-create-file-search-functions nil
10779 "List of functions to construct the right search string for a file link.
10780 These functions are called in turn with point at the location to
10781 which the link should point.
10783 A function in the hook should first test if it would like to
10784 handle this file type, for example by checking the `major-mode'
10785 or the file extension. If it decides not to handle this file, it
10786 should just return nil to give other functions a chance. If it
10787 does handle the file, it must return the search string to be used
10788 when following the link. The search string will be part of the
10789 file link, given after a double colon, and `org-open-at-point'
10790 will automatically search for it. If special measures must be
10791 taken to make the search successful, another function should be
10792 added to the companion hook `org-execute-file-search-functions',
10793 which see.
10795 A function in this hook may also use `setq' to set the variable
10796 `description' to provide a suggestion for the descriptive text to
10797 be used for this link when it gets inserted into an Org-mode
10798 buffer with \\[org-insert-link].")
10800 (defvar org-execute-file-search-functions nil
10801 "List of functions to execute a file search triggered by a link.
10803 Functions added to this hook must accept a single argument, the
10804 search string that was part of the file link, the part after the
10805 double colon. The function must first check if it would like to
10806 handle this search, for example by checking the `major-mode' or
10807 the file extension. If it decides not to handle this search, it
10808 should just return nil to give other functions a chance. If it
10809 does handle the search, it must return a non-nil value to keep
10810 other functions from trying.
10812 Each function can access the current prefix argument through the
10813 variable `current-prefix-arg'. Note that a single prefix is used
10814 to force opening a link in Emacs, so it may be good to only use a
10815 numeric or double prefix to guide the search function.
10817 In case this is needed, a function in this hook can also restore
10818 the window configuration before `org-open-at-point' was called using:
10820 (set-window-configuration org-window-config-before-follow-link)")
10822 (defun org-link-search (s &optional type avoid-pos stealth)
10823 "Search for a link search option.
10824 If S is surrounded by forward slashes, it is interpreted as a
10825 regular expression. In org-mode files, this will create an `org-occur'
10826 sparse tree. In ordinary files, `occur' will be used to list matches.
10827 If the current buffer is in `dired-mode', grep will be used to search
10828 in all files. If AVOID-POS is given, ignore matches near that position.
10830 When optional argument STEALTH is non-nil, do not modify
10831 visibility around point, thus ignoring
10832 `org-show-hierarchy-above', `org-show-following-heading' and
10833 `org-show-siblings' variables."
10834 (let ((case-fold-search t)
10835 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10836 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10837 (append '(("") (" ") ("\t") ("\n"))
10838 org-emphasis-alist)
10839 "\\|") "\\)"))
10840 (pos (point))
10841 (pre nil) (post nil)
10842 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10843 (cond
10844 ;; First check if there are any special search functions
10845 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10846 ;; Now try the builtin stuff
10847 ((and (equal (string-to-char s0) ?#)
10848 (> (length s0) 1)
10849 (save-excursion
10850 (goto-char (point-min))
10851 (and
10852 (re-search-forward
10853 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10854 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10855 (setq type 'dedicated
10856 pos (match-beginning 0))))
10857 ;; There is an exact target for this
10858 (goto-char pos)
10859 (org-back-to-heading t)))
10860 ((save-excursion
10861 (goto-char (point-min))
10862 (and
10863 (re-search-forward
10864 (concat "<<" (regexp-quote s0) ">>") nil t)
10865 (setq type 'dedicated
10866 pos (match-beginning 0))))
10867 ;; There is an exact target for this
10868 (goto-char pos))
10869 ((save-excursion
10870 (goto-char (point-min))
10871 (and
10872 (re-search-forward
10873 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10874 (setq type 'dedicated pos (match-beginning 0))))
10875 ;; Found an element with a matching #+name affiliated keyword.
10876 (goto-char pos))
10877 ((and (string-match "^(\\(.*\\))$" s0)
10878 (save-excursion
10879 (goto-char (point-min))
10880 (and
10881 (re-search-forward
10882 (concat "[^[]" (regexp-quote
10883 (format org-coderef-label-format
10884 (match-string 1 s0))))
10885 nil t)
10886 (setq type 'dedicated
10887 pos (1+ (match-beginning 0))))))
10888 ;; There is a coderef target for this
10889 (goto-char pos))
10890 ((string-match "^/\\(.*\\)/$" s)
10891 ;; A regular expression
10892 (cond
10893 ((derived-mode-p 'org-mode)
10894 (org-occur (match-string 1 s)))
10895 (t (org-do-occur (match-string 1 s)))))
10896 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10897 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10898 (goto-char (point-min))
10899 (cond
10900 ((let (case-fold-search)
10901 (re-search-forward (format org-complex-heading-regexp-format
10902 (regexp-quote s))
10903 nil t))
10904 ;; OK, found a match
10905 (setq type 'dedicated)
10906 (goto-char (match-beginning 0)))
10907 ((and (not org-link-search-inhibit-query)
10908 (eq org-link-search-must-match-exact-headline 'query-to-create)
10909 (y-or-n-p "No match - create this as a new heading? "))
10910 (goto-char (point-max))
10911 (or (bolp) (newline))
10912 (insert "* " s "\n")
10913 (beginning-of-line 0))
10915 (goto-char pos)
10916 (error "No match"))))
10918 ;; A normal search string
10919 (when (equal (string-to-char s) ?*)
10920 ;; Anchor on headlines, post may include tags.
10921 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10922 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10923 s (substring s 1)))
10924 (remove-text-properties
10925 0 (length s)
10926 '(face nil mouse-face nil keymap nil fontified nil) s)
10927 ;; Make a series of regular expressions to find a match
10928 (setq words (org-split-string s "[ \n\r\t]+")
10930 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10931 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10932 "\\)" markers)
10933 re2a_ (concat "\\(" (mapconcat 'downcase words
10934 "[ \t\r\n]+") "\\)[ \t\r\n]")
10935 re2a (concat "[ \t\r\n]" re2a_)
10936 re4_ (concat "\\(" (mapconcat 'downcase words
10937 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10938 re4 (concat "[^a-zA-Z_]" re4_)
10940 re1 (concat pre re2 post)
10941 re3 (concat pre (if pre re4_ re4) post)
10942 re5 (concat pre ".*" re4)
10943 re2 (concat pre re2)
10944 re2a (concat pre (if pre re2a_ re2a))
10945 re4 (concat pre (if pre re4_ re4))
10946 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10947 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10948 re5 "\\)"))
10949 (cond
10950 ((eq type 'org-occur) (org-occur reall))
10951 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10952 (t (goto-char (point-min))
10953 (setq type 'fuzzy)
10954 (if (or (and (org-search-not-self 1 re0 nil t)
10955 (setq type 'dedicated))
10956 (org-search-not-self 1 re1 nil t)
10957 (org-search-not-self 1 re2 nil t)
10958 (org-search-not-self 1 re2a nil t)
10959 (org-search-not-self 1 re3 nil t)
10960 (org-search-not-self 1 re4 nil t)
10961 (org-search-not-self 1 re5 nil t))
10962 (goto-char (match-beginning 1))
10963 (goto-char pos)
10964 (error "No match"))))))
10965 (and (derived-mode-p 'org-mode)
10966 (not stealth)
10967 (org-show-context 'link-search))
10968 type))
10970 (defun org-search-not-self (group &rest args)
10971 "Execute `re-search-forward', but only accept matches that do not
10972 enclose the position of `org-open-link-marker'."
10973 (let ((m org-open-link-marker))
10974 (catch 'exit
10975 (while (apply 're-search-forward args)
10976 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10977 (goto-char (match-end group))
10978 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10979 (> (match-beginning 0) (marker-position m))
10980 (< (match-end 0) (marker-position m)))
10981 (save-match-data
10982 (or (not (org-in-regexp
10983 org-bracket-link-analytic-regexp 1))
10984 (not (match-end 4)) ; no description
10985 (and (<= (match-beginning 4) (point))
10986 (>= (match-end 4) (point))))))
10987 (throw 'exit (point))))))))
10989 (defun org-get-buffer-for-internal-link (buffer)
10990 "Return a buffer to be used for displaying the link target of internal links."
10991 (cond
10992 ((not org-display-internal-link-with-indirect-buffer)
10993 buffer)
10994 ((string-match "(Clone)$" (buffer-name buffer))
10995 (message "Buffer is already a clone, not making another one")
10996 ;; we also do not modify visibility in this case
10997 buffer)
10998 (t ; make a new indirect buffer for displaying the link
10999 (let* ((bn (buffer-name buffer))
11000 (ibn (concat bn "(Clone)"))
11001 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11002 (with-current-buffer ib (org-overview))
11003 ib))))
11005 (defun org-do-occur (regexp &optional cleanup)
11006 "Call the Emacs command `occur'.
11007 If CLEANUP is non-nil, remove the printout of the regular expression
11008 in the *Occur* buffer. This is useful if the regex is long and not useful
11009 to read."
11010 (occur regexp)
11011 (when cleanup
11012 (let ((cwin (selected-window)) win beg end)
11013 (when (setq win (get-buffer-window "*Occur*"))
11014 (select-window win))
11015 (goto-char (point-min))
11016 (when (re-search-forward "match[a-z]+" nil t)
11017 (setq beg (match-end 0))
11018 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11019 (setq end (1- (match-beginning 0)))))
11020 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11021 (goto-char (point-min))
11022 (select-window cwin))))
11024 ;;; The mark ring for links jumps
11026 (defvar org-mark-ring nil
11027 "Mark ring for positions before jumps in Org-mode.")
11028 (defvar org-mark-ring-last-goto nil
11029 "Last position in the mark ring used to go back.")
11030 ;; Fill and close the ring
11031 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11032 (loop for i from 1 to org-mark-ring-length do
11033 (push (make-marker) org-mark-ring))
11034 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11035 org-mark-ring)
11037 (defun org-mark-ring-push (&optional pos buffer)
11038 "Put the current position or POS into the mark ring and rotate it."
11039 (interactive)
11040 (setq pos (or pos (point)))
11041 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11042 (move-marker (car org-mark-ring)
11043 (or pos (point))
11044 (or buffer (current-buffer)))
11045 (message "%s"
11046 (substitute-command-keys
11047 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11049 (defun org-mark-ring-goto (&optional n)
11050 "Jump to the previous position in the mark ring.
11051 With prefix arg N, jump back that many stored positions. When
11052 called several times in succession, walk through the entire ring.
11053 Org-mode commands jumping to a different position in the current file,
11054 or to another Org-mode file, automatically push the old position
11055 onto the ring."
11056 (interactive "p")
11057 (let (p m)
11058 (if (eq last-command this-command)
11059 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11060 (setq p org-mark-ring))
11061 (setq org-mark-ring-last-goto p)
11062 (setq m (car p))
11063 (org-pop-to-buffer-same-window (marker-buffer m))
11064 (goto-char m)
11065 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11067 (defun org-remove-angle-brackets (s)
11068 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11069 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11071 (defun org-add-angle-brackets (s)
11072 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11073 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11075 (defun org-remove-double-quotes (s)
11076 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11077 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11080 ;;; Following specific links
11082 (defun org-follow-timestamp-link ()
11083 "Open an agenda view for the time-stamp date/range at point."
11084 (cond
11085 ((org-at-date-range-p t)
11086 (let ((org-agenda-start-on-weekday)
11087 (t1 (match-string 1))
11088 (t2 (match-string 2)) tt1 tt2)
11089 (setq tt1 (time-to-days (org-time-string-to-time t1))
11090 tt2 (time-to-days (org-time-string-to-time t2)))
11091 (let ((org-agenda-buffer-tmp-name
11092 (format "*Org Agenda(a:%s)"
11093 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11094 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11095 ((org-at-timestamp-p t)
11096 (let ((org-agenda-buffer-tmp-name
11097 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11098 (org-agenda-list nil (time-to-days (org-time-string-to-time
11099 (substring (match-string 1) 0 10)))
11100 1)))
11101 (t (error "This should not happen"))))
11104 ;;; Following file links
11105 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11106 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11107 (declare-function mailcap-mime-info
11108 "mailcap" (string &optional request no-decode))
11109 (defvar org-wait nil)
11110 (defun org-open-file (path &optional in-emacs line search)
11111 "Open the file at PATH.
11112 First, this expands any special file name abbreviations. Then the
11113 configuration variable `org-file-apps' is checked if it contains an
11114 entry for this file type, and if yes, the corresponding command is launched.
11116 If no application is found, Emacs simply visits the file.
11118 With optional prefix argument IN-EMACS, Emacs will visit the file.
11119 With a double \\[universal-argument] \\[universal-argument] \
11120 prefix arg, Org tries to avoid opening in Emacs
11121 and to use an external application to visit the file.
11123 Optional LINE specifies a line to go to, optional SEARCH a string
11124 to search for. If LINE or SEARCH is given, the file will be
11125 opened in Emacs, unless an entry from org-file-apps that makes
11126 use of groups in a regexp matches.
11128 If you want to change the way frames are used when following a
11129 link, please customize `org-link-frame-setup'.
11131 If the file does not exist, an error is thrown."
11132 (let* ((file (if (equal path "")
11133 buffer-file-name
11134 (substitute-in-file-name (expand-file-name path))))
11135 (file-apps (append org-file-apps (org-default-apps)))
11136 (apps (org-remove-if
11137 'org-file-apps-entry-match-against-dlink-p file-apps))
11138 (apps-dlink (org-remove-if-not
11139 'org-file-apps-entry-match-against-dlink-p file-apps))
11140 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11141 (dirp (if remp nil (file-directory-p file)))
11142 (file (if (and dirp org-open-directory-means-index-dot-org)
11143 (concat (file-name-as-directory file) "index.org")
11144 file))
11145 (a-m-a-p (assq 'auto-mode apps))
11146 (dfile (downcase file))
11147 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11148 (link (cond ((and (eq line nil)
11149 (eq search nil))
11150 file)
11151 (line
11152 (concat file "::" (number-to-string line)))
11153 (search
11154 (concat file "::" search))))
11155 (dlink (downcase link))
11156 (old-buffer (current-buffer))
11157 (old-pos (point))
11158 (old-mode major-mode)
11159 ext cmd link-match-data)
11160 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11161 (setq ext (match-string 1 dfile))
11162 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11163 (setq ext (match-string 1 dfile))))
11164 (cond
11165 ((member in-emacs '((16) system))
11166 (setq cmd (cdr (assoc 'system apps))))
11167 (in-emacs (setq cmd 'emacs))
11169 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11170 (and dirp (cdr (assoc 'directory apps)))
11171 ; first, try matching against apps-dlink
11172 ; if we get a match here, store the match data for later
11173 (let ((match (assoc-default dlink apps-dlink
11174 'string-match)))
11175 (if match
11176 (progn (setq link-match-data (match-data))
11177 match)
11178 (progn (setq in-emacs (or in-emacs line search))
11179 nil))) ; if we have no match in apps-dlink,
11180 ; always open the file in emacs if line or search
11181 ; is given (for backwards compatibility)
11182 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11183 'string-match)
11184 (cdr (assoc ext apps))
11185 (cdr (assoc t apps))))))
11186 (when (eq cmd 'system)
11187 (setq cmd (cdr (assoc 'system apps))))
11188 (when (eq cmd 'default)
11189 (setq cmd (cdr (assoc t apps))))
11190 (when (eq cmd 'mailcap)
11191 (require 'mailcap)
11192 (mailcap-parse-mailcaps)
11193 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11194 (command (mailcap-mime-info mime-type)))
11195 (if (stringp command)
11196 (setq cmd command)
11197 (setq cmd 'emacs))))
11198 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11199 (not (file-exists-p file))
11200 (not org-open-non-existing-files))
11201 (user-error "No such file: %s" file))
11202 (cond
11203 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11204 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11205 (while (string-match "['\"]%s['\"]" cmd)
11206 (setq cmd (replace-match "%s" t t cmd)))
11207 (while (string-match "%s" cmd)
11208 (setq cmd (replace-match
11209 (save-match-data
11210 (shell-quote-argument
11211 (convert-standard-filename file)))
11212 t t cmd)))
11214 ;; Replace "%1", "%2" etc. in command with group matches from regex
11215 (save-match-data
11216 (let ((match-index 1)
11217 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11218 (set-match-data link-match-data)
11219 (while (<= match-index number-of-groups)
11220 (let ((regex (concat "%" (number-to-string match-index)))
11221 (replace-with (match-string match-index dlink)))
11222 (while (string-match regex cmd)
11223 (setq cmd (replace-match replace-with t t cmd))))
11224 (setq match-index (+ match-index 1)))))
11226 (save-window-excursion
11227 (message "Running %s...done" cmd)
11228 (start-process-shell-command cmd nil cmd)
11229 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11230 ((or (stringp cmd)
11231 (eq cmd 'emacs))
11232 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11233 (widen)
11234 (if line (progn (org-goto-line line)
11235 (if (derived-mode-p 'org-mode)
11236 (org-reveal)))
11237 (if search (org-link-search search))))
11238 ((consp cmd)
11239 (let ((file (convert-standard-filename file)))
11240 (save-match-data
11241 (set-match-data link-match-data)
11242 (eval cmd))))
11243 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11244 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11245 (or (not (equal old-buffer (current-buffer)))
11246 (not (equal old-pos (point))))
11247 (org-mark-ring-push old-pos old-buffer))))
11249 (defun org-file-apps-entry-match-against-dlink-p (entry)
11250 "This function returns non-nil if `entry' uses a regular
11251 expression which should be matched against the whole link by
11252 org-open-file.
11254 It assumes that is the case when the entry uses a regular
11255 expression which has at least one grouping construct and the
11256 action is either a lisp form or a command string containing
11257 '%1', i.e. using at least one subexpression match as a
11258 parameter."
11259 (let ((selector (car entry))
11260 (action (cdr entry)))
11261 (if (stringp selector)
11262 (and (> (regexp-opt-depth selector) 0)
11263 (or (and (stringp action)
11264 (string-match "%[0-9]" action))
11265 (consp action)))
11266 nil)))
11268 (defun org-default-apps ()
11269 "Return the default applications for this operating system."
11270 (cond
11271 ((eq system-type 'darwin)
11272 org-file-apps-defaults-macosx)
11273 ((eq system-type 'windows-nt)
11274 org-file-apps-defaults-windowsnt)
11275 (t org-file-apps-defaults-gnu)))
11277 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11278 "Convert extensions to regular expressions in the cars of LIST.
11279 Also, weed out any non-string entries, because the return value is used
11280 only for regexp matching.
11281 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11282 point to the symbol `emacs', indicating that the file should
11283 be opened in Emacs."
11284 (append
11285 (delq nil
11286 (mapcar (lambda (x)
11287 (if (not (stringp (car x)))
11289 (if (string-match "\\W" (car x))
11291 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11292 list))
11293 (if add-auto-mode
11294 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11296 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11297 (defun org-file-remote-p (file)
11298 "Test whether FILE specifies a location on a remote system.
11299 Return non-nil if the location is indeed remote.
11301 For example, the filename \"/user@host:/foo\" specifies a location
11302 on the system \"/user@host:\"."
11303 (cond ((fboundp 'file-remote-p)
11304 (file-remote-p file))
11305 ((fboundp 'tramp-handle-file-remote-p)
11306 (tramp-handle-file-remote-p file))
11307 ((and (boundp 'ange-ftp-name-format)
11308 (string-match (car ange-ftp-name-format) file))
11309 t)))
11312 ;;;; Refiling
11314 (defun org-get-org-file ()
11315 "Read a filename, with default directory `org-directory'."
11316 (let ((default (or org-default-notes-file remember-data-file)))
11317 (read-file-name (format "File name [%s]: " default)
11318 (file-name-as-directory org-directory)
11319 default)))
11321 (defun org-notes-order-reversed-p ()
11322 "Check if the current file should receive notes in reversed order."
11323 (cond
11324 ((not org-reverse-note-order) nil)
11325 ((eq t org-reverse-note-order) t)
11326 ((not (listp org-reverse-note-order)) nil)
11327 (t (catch 'exit
11328 (let ((all org-reverse-note-order)
11329 entry)
11330 (while (setq entry (pop all))
11331 (if (string-match (car entry) buffer-file-name)
11332 (throw 'exit (cdr entry))))
11333 nil)))))
11335 (defvar org-refile-target-table nil
11336 "The list of refile targets, created by `org-refile'.")
11338 (defvar org-agenda-new-buffers nil
11339 "Buffers created to visit agenda files.")
11341 (defvar org-refile-cache nil
11342 "Cache for refile targets.")
11344 (defvar org-refile-markers nil
11345 "All the markers used for caching refile locations.")
11347 (defun org-refile-marker (pos)
11348 "Get a new refile marker, but only if caching is in use."
11349 (if (not org-refile-use-cache)
11351 (let ((m (make-marker)))
11352 (move-marker m pos)
11353 (push m org-refile-markers)
11354 m)))
11356 (defun org-refile-cache-clear ()
11357 "Clear the refile cache and disable all the markers."
11358 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11359 (setq org-refile-markers nil)
11360 (setq org-refile-cache nil)
11361 (message "Refile cache has been cleared"))
11363 (defun org-refile-cache-check-set (set)
11364 "Check if all the markers in the cache still have live buffers."
11365 (let (marker)
11366 (catch 'exit
11367 (while (and set (setq marker (nth 3 (pop set))))
11368 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11369 (when (and marker (null (marker-buffer marker)))
11370 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11371 (sit-for 3)
11372 (throw 'exit nil)))
11373 t)))
11375 (defun org-refile-cache-put (set &rest identifiers)
11376 "Push the refile targets SET into the cache, under IDENTIFIERS."
11377 (let* ((key (sha1 (prin1-to-string identifiers)))
11378 (entry (assoc key org-refile-cache)))
11379 (if entry
11380 (setcdr entry set)
11381 (push (cons key set) org-refile-cache))))
11383 (defun org-refile-cache-get (&rest identifiers)
11384 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11385 (cond
11386 ((not org-refile-cache) nil)
11387 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11389 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11390 org-refile-cache))))
11391 (and set (org-refile-cache-check-set set) set)))))
11393 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11394 "Produce a table with refile targets."
11395 (let ((case-fold-search nil)
11396 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11397 (entries (or org-refile-targets '((nil . (:level . 1)))))
11398 targets tgs txt re files f desc descre fast-path-p level pos0)
11399 (message "Getting targets...")
11400 (with-current-buffer (or default-buffer (current-buffer))
11401 (while (setq entry (pop entries))
11402 (setq files (car entry) desc (cdr entry))
11403 (setq fast-path-p nil)
11404 (cond
11405 ((null files) (setq files (list (current-buffer))))
11406 ((eq files 'org-agenda-files)
11407 (setq files (org-agenda-files 'unrestricted)))
11408 ((and (symbolp files) (fboundp files))
11409 (setq files (funcall files)))
11410 ((and (symbolp files) (boundp files))
11411 (setq files (symbol-value files))))
11412 (if (stringp files) (setq files (list files)))
11413 (cond
11414 ((eq (car desc) :tag)
11415 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11416 ((eq (car desc) :todo)
11417 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11418 ((eq (car desc) :regexp)
11419 (setq descre (cdr desc)))
11420 ((eq (car desc) :level)
11421 (setq descre (concat "^\\*\\{" (number-to-string
11422 (if org-odd-levels-only
11423 (1- (* 2 (cdr desc)))
11424 (cdr desc)))
11425 "\\}[ \t]")))
11426 ((eq (car desc) :maxlevel)
11427 (setq fast-path-p t)
11428 (setq descre (concat "^\\*\\{1," (number-to-string
11429 (if org-odd-levels-only
11430 (1- (* 2 (cdr desc)))
11431 (cdr desc)))
11432 "\\}[ \t]")))
11433 (t (error "Bad refiling target description %s" desc)))
11434 (while (setq f (pop files))
11435 (with-current-buffer
11436 (if (bufferp f) f (org-get-agenda-file-buffer f))
11438 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11439 (progn
11440 (if (bufferp f) (setq f (buffer-file-name
11441 (buffer-base-buffer f))))
11442 (setq f (and f (expand-file-name f)))
11443 (if (eq org-refile-use-outline-path 'file)
11444 (push (list (file-name-nondirectory f) f nil nil) tgs))
11445 (save-excursion
11446 (save-restriction
11447 (widen)
11448 (goto-char (point-min))
11449 (while (re-search-forward descre nil t)
11450 (goto-char (setq pos0 (point-at-bol)))
11451 (catch 'next
11452 (when org-refile-target-verify-function
11453 (save-match-data
11454 (or (funcall org-refile-target-verify-function)
11455 (throw 'next t))))
11456 (when (and (looking-at org-complex-heading-regexp)
11457 (not (member (match-string 4) excluded-entries))
11458 (match-string 4))
11459 (setq level (org-reduced-level
11460 (- (match-end 1) (match-beginning 1)))
11461 txt (org-link-display-format (match-string 4))
11462 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11463 re (format org-complex-heading-regexp-format
11464 (regexp-quote (match-string 4))))
11465 (when org-refile-use-outline-path
11466 (setq txt (mapconcat
11467 'org-protect-slash
11468 (append
11469 (if (eq org-refile-use-outline-path
11470 'file)
11471 (list (file-name-nondirectory
11472 (buffer-file-name
11473 (buffer-base-buffer))))
11474 (if (eq org-refile-use-outline-path
11475 'full-file-path)
11476 (list (buffer-file-name
11477 (buffer-base-buffer)))))
11478 (org-get-outline-path fast-path-p
11479 level txt)
11480 (list txt))
11481 "/")))
11482 (push (list txt f re (org-refile-marker (point)))
11483 tgs)))
11484 (when (= (point) pos0)
11485 ;; verification function has not moved point
11486 (goto-char (point-at-eol))))))))
11487 (when org-refile-use-cache
11488 (org-refile-cache-put tgs (buffer-file-name) descre))
11489 (setq targets (append tgs targets))))))
11490 (message "Getting targets...done")
11491 (nreverse targets)))
11493 (defun org-protect-slash (s)
11494 (while (string-match "/" s)
11495 (setq s (replace-match "\\" t t s)))
11498 (defvar org-olpa (make-vector 20 nil))
11500 (defun org-get-outline-path (&optional fastp level heading)
11501 "Return the outline path to the current entry, as a list.
11503 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11504 routine which makes outline path derivations for an entire file,
11505 avoiding backtracing. Refile target collection makes use of that."
11506 (if fastp
11507 (progn
11508 (if (> level 19)
11509 (error "Outline path failure, more than 19 levels"))
11510 (loop for i from level upto 19 do
11511 (aset org-olpa i nil))
11512 (prog1
11513 (delq nil (append org-olpa nil))
11514 (aset org-olpa level heading)))
11515 (let (rtn case-fold-search)
11516 (save-excursion
11517 (save-restriction
11518 (widen)
11519 (while (org-up-heading-safe)
11520 (when (looking-at org-complex-heading-regexp)
11521 (push (org-trim
11522 (replace-regexp-in-string
11523 ;; Remove statistical/checkboxes cookies
11524 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11525 (org-match-string-no-properties 4)))
11526 rtn)))
11527 rtn)))))
11529 (defun org-format-outline-path (path &optional width prefix separator)
11530 "Format the outline path PATH for display.
11531 WIDTH is the maximum number of characters that is available.
11532 PREFIX is a prefix to be included in the returned string,
11533 such as the file name.
11534 SEPARATOR is inserted between the different parts of the path,
11535 the default is \"/\"."
11536 (setq width (or width 79))
11537 (if prefix (setq width (- width (length prefix))))
11538 (if (not path)
11539 (or prefix "")
11540 (let* ((nsteps (length path))
11541 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11542 (maxwidth (if (<= total-width width)
11543 10000 ;; everything fits
11544 ;; we need to shorten the level headings
11545 (/ (- width nsteps) nsteps)))
11546 (org-odd-levels-only nil)
11547 (n 0)
11548 (total (1+ (length prefix))))
11549 (setq maxwidth (max maxwidth 10))
11550 (concat prefix
11551 (if prefix (or separator "/"))
11552 (mapconcat
11553 (lambda (h)
11554 (setq n (1+ n))
11555 (if (and (= n nsteps) (< maxwidth 10000))
11556 (setq maxwidth (- total-width total)))
11557 (if (< (length h) maxwidth)
11558 (progn (setq total (+ total (length h) 1)) h)
11559 (setq h (substring h 0 (- maxwidth 2))
11560 total (+ total maxwidth 1))
11561 (if (string-match "[ \t]+\\'" h)
11562 (setq h (substring h 0 (match-beginning 0))))
11563 (setq h (concat h "..")))
11564 (org-add-props h nil 'face
11565 (nth (% (1- n) org-n-level-faces)
11566 org-level-faces))
11568 path (or separator "/"))))))
11570 (defun org-display-outline-path (&optional file current separator just-return-string)
11571 "Display the current outline path in the echo area.
11573 If FILE is non-nil, prepend the output with the file name.
11574 If CURRENT is non-nil, append the current heading to the output.
11575 SEPARATOR is passed through to `org-format-outline-path'. It separates
11576 the different parts of the path and defaults to \"/\".
11577 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11578 (interactive "P")
11579 (let* (case-fold-search
11580 (bfn (buffer-file-name (buffer-base-buffer)))
11581 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11582 res)
11583 (if current (setq path (append path
11584 (save-excursion
11585 (org-back-to-heading t)
11586 (if (looking-at org-complex-heading-regexp)
11587 (list (match-string 4)))))))
11588 (setq res
11589 (org-format-outline-path
11590 path
11591 (1- (frame-width))
11592 (and file bfn (concat (file-name-nondirectory bfn) separator))
11593 separator))
11594 (if just-return-string
11595 (org-no-properties res)
11596 (org-unlogged-message "%s" res))))
11598 (defvar org-refile-history nil
11599 "History for refiling operations.")
11601 (defvar org-after-refile-insert-hook nil
11602 "Hook run after `org-refile' has inserted its stuff at the new location.
11603 Note that this is still *before* the stuff will be removed from
11604 the *old* location.")
11606 (defvar org-capture-last-stored-marker)
11607 (defvar org-refile-keep nil
11608 "Non-nil means `org-refile' will copy instead of refile.")
11610 (defun org-copy ()
11611 "Like `org-refile', but copy."
11612 (interactive)
11613 (let ((org-refile-keep t))
11614 (funcall 'org-refile nil nil nil "Copy")))
11616 (defun org-refile (&optional arg default-buffer rfloc msg)
11617 "Move the entry or entries at point to another heading.
11618 The list of target headings is compiled using the information in
11619 `org-refile-targets', which see.
11621 At the target location, the entry is filed as a subitem of the
11622 target heading. Depending on `org-reverse-note-order', the new
11623 subitem will either be the first or the last subitem.
11625 If there is an active region, all entries in that region will be
11626 refiled. However, the region must fulfill the requirement that
11627 the first heading sets the top-level of the moved text.
11629 With prefix arg ARG, the command will only visit the target
11630 location and not actually move anything.
11632 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11633 refiling operation has put the subtree.
11635 With a numeric prefix argument of `2', refile to the running clock.
11637 With a numeric prefix argument of `3', emulate `org-refile-keep'
11638 being set to `t' and copy to the target location, don't move it.
11639 Beware that keeping refiled entries may result in duplicated ID
11640 properties.
11642 RFLOC can be a refile location obtained in a different way.
11644 MSG is a string to replace \"Refile\" in the default prompt with
11645 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11647 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11649 If you are using target caching (see `org-refile-use-cache'), you
11650 have to clear the target cache in order to find new targets.
11651 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11652 prefix argument (`C-u C-u C-u C-c C-w')."
11653 (interactive "P")
11654 (if (member arg '(0 (64)))
11655 (org-refile-cache-clear)
11656 (let* ((actionmsg (cond (msg msg)
11657 ((equal arg 3) "Refile (and keep)")
11658 (t "Refile")))
11659 (cbuf (current-buffer))
11660 (regionp (org-region-active-p))
11661 (region-start (and regionp (region-beginning)))
11662 (region-end (and regionp (region-end)))
11663 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11664 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11665 pos it nbuf file re level reversed)
11666 (setq last-command nil)
11667 (when regionp
11668 (goto-char region-start)
11669 (or (bolp) (goto-char (point-at-bol)))
11670 (setq region-start (point))
11671 (unless (or (org-kill-is-subtree-p
11672 (buffer-substring region-start region-end))
11673 (prog1 org-refile-active-region-within-subtree
11674 (let ((s (point-at-eol)))
11675 (org-toggle-heading)
11676 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11677 (user-error "The region is not a (sequence of) subtree(s)")))
11678 (if (equal arg '(16))
11679 (org-refile-goto-last-stored)
11680 (when (or
11681 (and (equal arg 2)
11682 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11683 (prog1
11684 (setq it (list (or org-clock-heading "running clock")
11685 (buffer-file-name
11686 (marker-buffer org-clock-hd-marker))
11688 (marker-position org-clock-hd-marker)))
11689 (setq arg nil)))
11690 (setq it (or rfloc
11691 (let (heading-text)
11692 (save-excursion
11693 (unless (and arg (listp arg))
11694 (org-back-to-heading t)
11695 (setq heading-text
11696 (replace-regexp-in-string
11697 org-bracket-link-regexp
11698 "\\3"
11699 (nth 4 (org-heading-components)))))
11700 (org-refile-get-location
11701 (cond ((and arg (listp arg)) "Goto")
11702 (regionp (concat actionmsg " region to"))
11703 (t (concat actionmsg " subtree \""
11704 heading-text "\" to")))
11705 default-buffer
11706 (and (not (equal '(4) arg))
11707 org-refile-allow-creating-parent-nodes)
11708 arg))))))
11709 (setq file (nth 1 it)
11710 re (nth 2 it)
11711 pos (nth 3 it))
11712 (if (and (not arg)
11714 (equal (buffer-file-name) file)
11715 (if regionp
11716 (and (>= pos region-start)
11717 (<= pos region-end))
11718 (and (>= pos (point))
11719 (< pos (save-excursion
11720 (org-end-of-subtree t t))))))
11721 (error "Cannot refile to position inside the tree or region"))
11722 (setq nbuf (or (find-buffer-visiting file)
11723 (find-file-noselect file)))
11724 (if (and arg (not (equal arg 3)))
11725 (progn
11726 (org-pop-to-buffer-same-window nbuf)
11727 (goto-char pos)
11728 (org-show-context 'org-goto))
11729 (if regionp
11730 (progn
11731 (org-kill-new (buffer-substring region-start region-end))
11732 (org-save-markers-in-region region-start region-end))
11733 (org-copy-subtree 1 nil t))
11734 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11735 (find-file-noselect file)))
11736 (setq reversed (org-notes-order-reversed-p))
11737 (save-excursion
11738 (save-restriction
11739 (widen)
11740 (if pos
11741 (progn
11742 (goto-char pos)
11743 (looking-at org-outline-regexp)
11744 (setq level (org-get-valid-level (funcall outline-level) 1))
11745 (goto-char
11746 (if reversed
11747 (or (outline-next-heading) (point-max))
11748 (or (save-excursion (org-get-next-sibling))
11749 (org-end-of-subtree t t)
11750 (point-max)))))
11751 (setq level 1)
11752 (if (not reversed)
11753 (goto-char (point-max))
11754 (goto-char (point-min))
11755 (or (outline-next-heading) (goto-char (point-max)))))
11756 (if (not (bolp)) (newline))
11757 (org-paste-subtree level)
11758 (when org-log-refile
11759 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11760 (unless (eq org-log-refile 'note)
11761 (save-excursion (org-add-log-note))))
11762 (and org-auto-align-tags
11763 (let ((org-loop-over-headlines-in-active-region nil))
11764 (org-set-tags nil t)))
11765 (let ((bookmark-name (plist-get org-bookmark-names-plist
11766 :last-refile)))
11767 (when bookmark-name
11768 (with-demoted-errors
11769 (bookmark-set bookmark-name))))
11770 ;; If we are refiling for capture, make sure that the
11771 ;; last-capture pointers point here
11772 (when (org-bound-and-true-p org-refile-for-capture)
11773 (let ((bookmark-name (plist-get org-bookmark-names-plist
11774 :last-capture-marker)))
11775 (when bookmark-name
11776 (with-demoted-errors
11777 (bookmark-set bookmark-name))))
11778 (move-marker org-capture-last-stored-marker (point)))
11779 (if (fboundp 'deactivate-mark) (deactivate-mark))
11780 (run-hooks 'org-after-refile-insert-hook))))
11781 (unless org-refile-keep
11782 (if regionp
11783 (delete-region (point) (+ (point) (- region-end region-start)))
11784 (delete-region
11785 (and (org-back-to-heading t) (point))
11786 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11787 (when (featurep 'org-inlinetask)
11788 (org-inlinetask-remove-END-maybe))
11789 (setq org-markers-to-move nil)
11790 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11792 (defun org-refile-goto-last-stored ()
11793 "Go to the location where the last refile was stored."
11794 (interactive)
11795 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11796 (message "This is the location of the last refile"))
11798 (defun org-refile--get-location (refloc tbl)
11799 "When user refile to REFLOC, find the associated target in TBL.
11800 Also check `org-refile-target-table'."
11801 (car (delq
11803 (mapcar
11804 (lambda (r) (or (assoc r tbl)
11805 (assoc r org-refile-target-table)))
11806 (list (replace-regexp-in-string "/$" "" refloc)
11807 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11809 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11810 no-exclude)
11811 "Prompt the user for a refile location, using PROMPT.
11812 PROMPT should not be suffixed with a colon and a space, because
11813 this function appends the default value from
11814 `org-refile-history' automatically, if that is not empty.
11815 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11816 this is used for the GOTO interface."
11817 (let ((org-refile-targets org-refile-targets)
11818 (org-refile-use-outline-path org-refile-use-outline-path)
11819 excluded-entries)
11820 (when (and (derived-mode-p 'org-mode)
11821 (not org-refile-use-cache)
11822 (not no-exclude))
11823 (org-map-tree
11824 (lambda()
11825 (setq excluded-entries
11826 (append excluded-entries (list (org-get-heading t t)))))))
11827 (setq org-refile-target-table
11828 (org-refile-get-targets default-buffer excluded-entries)))
11829 (unless org-refile-target-table
11830 (user-error "No refile targets"))
11831 (let* ((cbuf (current-buffer))
11832 (partial-completion-mode nil)
11833 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11834 (cfunc (if (and org-refile-use-outline-path
11835 org-outline-path-complete-in-steps)
11836 'org-olpath-completing-read
11837 'org-icompleting-read))
11838 (extra (if org-refile-use-outline-path "/" ""))
11839 (cbnex (concat (buffer-name) extra))
11840 (filename (and cfn (expand-file-name cfn)))
11841 (tbl (mapcar
11842 (lambda (x)
11843 (if (and (not (member org-refile-use-outline-path
11844 '(file full-file-path)))
11845 (not (equal filename (nth 1 x))))
11846 (cons (concat (car x) extra " ("
11847 (file-name-nondirectory (nth 1 x)) ")")
11848 (cdr x))
11849 (cons (concat (car x) extra) (cdr x))))
11850 org-refile-target-table))
11851 (completion-ignore-case t)
11852 cdef
11853 (prompt (concat prompt
11854 (or (and (car org-refile-history)
11855 (concat " (default " (car org-refile-history) ")"))
11856 (and (assoc cbnex tbl) (setq cdef cbnex)
11857 (concat " (default " cbnex ")"))) ": "))
11858 pa answ parent-target child parent old-hist)
11859 (setq old-hist org-refile-history)
11860 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11861 nil 'org-refile-history (or cdef (car org-refile-history))))
11862 (if (setq pa (org-refile--get-location answ tbl))
11863 (progn
11864 (org-refile-check-position pa)
11865 (when (or (not org-refile-history)
11866 (not (eq old-hist org-refile-history))
11867 (not (equal (car pa) (car org-refile-history))))
11868 (setq org-refile-history
11869 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11870 org-refile-history
11871 (cdr org-refile-history))))
11872 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11873 (pop org-refile-history)))
11875 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11876 (progn
11877 (setq parent (match-string 1 answ)
11878 child (match-string 2 answ))
11879 (setq parent-target (org-refile--get-location parent tbl))
11880 (when (and parent-target
11881 (or (eq new-nodes t)
11882 (and (eq new-nodes 'confirm)
11883 (y-or-n-p (format "Create new node \"%s\"? "
11884 child)))))
11885 (org-refile-new-child parent-target child)))
11886 (user-error "Invalid target location")))))
11888 (declare-function org-string-nw-p "org-macs" (s))
11889 (defun org-refile-check-position (refile-pointer)
11890 "Check if the refile pointer matches the headline to which it points."
11891 (let* ((file (nth 1 refile-pointer))
11892 (re (nth 2 refile-pointer))
11893 (pos (nth 3 refile-pointer))
11894 buffer)
11895 (if (and (not (markerp pos)) (not file))
11896 (if file
11897 (user-error "Please save the buffer to a file before refiling")
11898 (user-error "Please indicate a target file in the refile path"))
11899 (when (org-string-nw-p re)
11900 (setq buffer (if (markerp pos)
11901 (marker-buffer pos)
11902 (or (find-buffer-visiting file)
11903 (find-file-noselect file))))
11904 (with-current-buffer buffer
11905 (save-excursion
11906 (save-restriction
11907 (widen)
11908 (goto-char pos)
11909 (beginning-of-line 1)
11910 (unless (org-looking-at-p re)
11911 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11913 (defun org-refile-new-child (parent-target child)
11914 "Use refile target PARENT-TARGET to add new CHILD below it."
11915 (unless parent-target
11916 (error "Cannot find parent for new node"))
11917 (let ((file (nth 1 parent-target))
11918 (pos (nth 3 parent-target))
11919 level)
11920 (with-current-buffer (or (find-buffer-visiting file)
11921 (find-file-noselect file))
11922 (save-excursion
11923 (save-restriction
11924 (widen)
11925 (if pos
11926 (goto-char pos)
11927 (goto-char (point-max))
11928 (if (not (bolp)) (newline)))
11929 (when (looking-at org-outline-regexp)
11930 (setq level (funcall outline-level))
11931 (org-end-of-subtree t t))
11932 (org-back-over-empty-lines)
11933 (insert "\n" (make-string
11934 (if pos (org-get-valid-level level 1) 1) ?*)
11935 " " child "\n")
11936 (beginning-of-line 0)
11937 (list (concat (car parent-target) "/" child) file "" (point)))))))
11939 (defun org-olpath-completing-read (prompt collection &rest args)
11940 "Read an outline path like a file name."
11941 (let ((thetable collection)
11942 (org-completion-use-ido nil) ; does not work with ido.
11943 (org-completion-use-iswitchb nil)) ; or iswitchb
11944 (apply
11945 'org-icompleting-read prompt
11946 (lambda (string predicate &optional flag)
11947 (let (rtn r f (l (length string)))
11948 (cond
11949 ((eq flag nil)
11950 ;; try completion
11951 (try-completion string thetable))
11952 ((eq flag t)
11953 ;; all-completions
11954 (setq rtn (all-completions string thetable predicate))
11955 (mapcar
11956 (lambda (x)
11957 (setq r (substring x l))
11958 (if (string-match " ([^)]*)$" x)
11959 (setq f (match-string 0 x))
11960 (setq f ""))
11961 (if (string-match "/" r)
11962 (concat string (substring r 0 (match-end 0)) f)
11964 rtn))
11965 ((eq flag 'lambda)
11966 ;; exact match?
11967 (assoc string thetable)))))
11968 args)))
11970 ;;;; Dynamic blocks
11972 (defun org-find-dblock (name)
11973 "Find the first dynamic block with name NAME in the buffer.
11974 If not found, stay at current position and return nil."
11975 (let ((case-fold-search t) pos)
11976 (save-excursion
11977 (goto-char (point-min))
11978 (setq pos (and (re-search-forward
11979 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11980 (match-beginning 0))))
11981 (if pos (goto-char pos))
11982 pos))
11984 (defun org-create-dblock (plist)
11985 "Create a dynamic block section, with parameters taken from PLIST.
11986 PLIST must contain a :name entry which is used as the name of the block."
11987 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11988 (end-of-line 1)
11989 (newline))
11990 (let ((col (current-column))
11991 (name (plist-get plist :name)))
11992 (insert "#+BEGIN: " name)
11993 (while plist
11994 (if (eq (car plist) :name)
11995 (setq plist (cddr plist))
11996 (insert " " (prin1-to-string (pop plist)))))
11997 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11998 (beginning-of-line -2)))
12000 (defun org-prepare-dblock ()
12001 "Prepare dynamic block for refresh.
12002 This empties the block, puts the cursor at the insert position and returns
12003 the property list including an extra property :name with the block name."
12004 (unless (looking-at org-dblock-start-re)
12005 (user-error "Not at a dynamic block"))
12006 (let* ((begdel (1+ (match-end 0)))
12007 (name (org-no-properties (match-string 1)))
12008 (params (append (list :name name)
12009 (read (concat "(" (match-string 3) ")")))))
12010 (save-excursion
12011 (beginning-of-line 1)
12012 (skip-chars-forward " \t")
12013 (setq params (plist-put params :indentation-column (current-column))))
12014 (unless (re-search-forward org-dblock-end-re nil t)
12015 (error "Dynamic block not terminated"))
12016 (setq params
12017 (append params
12018 (list :content (buffer-substring
12019 begdel (match-beginning 0)))))
12020 (delete-region begdel (match-beginning 0))
12021 (goto-char begdel)
12022 (open-line 1)
12023 params))
12025 (defun org-map-dblocks (&optional command)
12026 "Apply COMMAND to all dynamic blocks in the current buffer.
12027 If COMMAND is not given, use `org-update-dblock'."
12028 (let ((cmd (or command 'org-update-dblock)))
12029 (save-excursion
12030 (goto-char (point-min))
12031 (while (re-search-forward org-dblock-start-re nil t)
12032 (goto-char (match-beginning 0))
12033 (save-excursion
12034 (condition-case nil
12035 (funcall cmd)
12036 (error (message "Error during update of dynamic block"))))
12037 (unless (re-search-forward org-dblock-end-re nil t)
12038 (error "Dynamic block not terminated"))))))
12040 (defun org-dblock-update (&optional arg)
12041 "User command for updating dynamic blocks.
12042 Update the dynamic block at point. With prefix ARG, update all dynamic
12043 blocks in the buffer."
12044 (interactive "P")
12045 (if arg
12046 (org-update-all-dblocks)
12047 (or (looking-at org-dblock-start-re)
12048 (org-beginning-of-dblock))
12049 (org-update-dblock)))
12051 (defun org-update-dblock ()
12052 "Update the dynamic block at point.
12053 This means to empty the block, parse for parameters and then call
12054 the correct writing function."
12055 (interactive)
12056 (save-excursion
12057 (let* ((win (selected-window))
12058 (pos (point))
12059 (line (org-current-line))
12060 (params (org-prepare-dblock))
12061 (name (plist-get params :name))
12062 (indent (plist-get params :indentation-column))
12063 (cmd (intern (concat "org-dblock-write:" name))))
12064 (message "Updating dynamic block `%s' at line %d..." name line)
12065 (funcall cmd params)
12066 (message "Updating dynamic block `%s' at line %d...done" name line)
12067 (goto-char pos)
12068 (when (and indent (> indent 0))
12069 (setq indent (make-string indent ?\ ))
12070 (save-excursion
12071 (select-window win)
12072 (org-beginning-of-dblock)
12073 (forward-line 1)
12074 (while (not (looking-at org-dblock-end-re))
12075 (insert indent)
12076 (beginning-of-line 2))
12077 (when (looking-at org-dblock-end-re)
12078 (and (looking-at "[ \t]+")
12079 (replace-match ""))
12080 (insert indent)))))))
12082 (defun org-beginning-of-dblock ()
12083 "Find the beginning of the dynamic block at point.
12084 Error if there is no such block at point."
12085 (let ((pos (point))
12086 beg)
12087 (end-of-line 1)
12088 (if (and (re-search-backward org-dblock-start-re nil t)
12089 (setq beg (match-beginning 0))
12090 (re-search-forward org-dblock-end-re nil t)
12091 (> (match-end 0) pos))
12092 (goto-char beg)
12093 (goto-char pos)
12094 (error "Not in a dynamic block"))))
12096 (defun org-update-all-dblocks ()
12097 "Update all dynamic blocks in the buffer.
12098 This function can be used in a hook."
12099 (interactive)
12100 (when (derived-mode-p 'org-mode)
12101 (org-map-dblocks 'org-update-dblock)))
12104 ;;;; Completion
12106 (declare-function org-export-backend-name "org-export" (cl-x))
12107 (declare-function org-export-backend-options "org-export" (cl-x))
12108 (defun org-get-export-keywords ()
12109 "Return a list of all currently understood export keywords.
12110 Export keywords include options, block names, attributes and
12111 keywords relative to each registered export back-end."
12112 (let (keywords)
12113 (dolist (backend
12114 (org-bound-and-true-p org-export--registered-backends)
12115 (delq nil keywords))
12116 ;; Back-end name (for keywords, like #+LATEX:)
12117 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12118 (dolist (option-entry (org-export-backend-options backend))
12119 ;; Back-end options.
12120 (push (nth 1 option-entry) keywords)))))
12122 (defconst org-options-keywords
12123 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12124 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12125 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12126 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12127 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12129 (defcustom org-structure-template-alist
12130 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12131 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12132 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12133 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12134 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12135 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12136 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12137 "<literal style=\"latex\">\n?\n</literal>")
12138 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12139 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12140 "<literal style=\"html\">\n?\n</literal>")
12141 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12142 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12143 ("A" "#+ASCII: " "")
12144 ("i" "#+INDEX: ?" "#+INDEX: ?")
12145 ("I" "#+INCLUDE: %file ?"
12146 "<include file=%file markup=\"?\">"))
12147 "Structure completion elements.
12148 This is a list of abbreviation keys and values. The value gets inserted
12149 if you type `<' followed by the key and then press the completion key,
12150 usually `M-TAB'. %file will be replaced by a file name after prompting
12151 for the file using completion. The cursor will be placed at the position
12152 of the `?` in the template.
12153 There are two templates for each key, the first uses the original Org syntax,
12154 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12155 the default when the /org-mtags.el/ module has been loaded. See also the
12156 variable `org-mtags-prefer-muse-templates'."
12157 :group 'org-completion
12158 :type '(repeat
12159 (list
12160 (string :tag "Key")
12161 (string :tag "Template")
12162 (string :tag "Muse Template"))))
12164 (defun org-try-structure-completion ()
12165 "Try to complete a structure template before point.
12166 This looks for strings like \"<e\" on an otherwise empty line and
12167 expands them."
12168 (let ((l (buffer-substring (point-at-bol) (point)))
12170 (when (and (looking-at "[ \t]*$")
12171 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12172 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12173 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12174 (match-beginning 1)) a)
12175 t)))
12177 (defun org-complete-expand-structure-template (start cell)
12178 "Expand a structure template."
12179 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12180 (rpl (nth (if musep 2 1) cell))
12181 (ind ""))
12182 (delete-region start (point))
12183 (when (string-match "\\`[ \t]*#\\+" rpl)
12184 (cond
12185 ((bolp))
12186 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12187 (setq ind (buffer-substring (point-at-bol) (point))))
12188 (t (newline))))
12189 (setq start (point))
12190 (if (string-match "%file" rpl)
12191 (setq rpl (replace-match
12192 (concat
12193 "\""
12194 (save-match-data
12195 (abbreviate-file-name (read-file-name "Include file: ")))
12196 "\"")
12197 t t rpl)))
12198 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12199 (concat "\n" ind)))
12200 (insert rpl)
12201 (if (re-search-backward "\\?" start t) (delete-char 1))))
12203 ;;;; TODO, DEADLINE, Comments
12205 (defun org-toggle-comment ()
12206 "Change the COMMENT state of an entry."
12207 (interactive)
12208 (save-excursion
12209 (org-back-to-heading)
12210 (looking-at org-complex-heading-regexp)
12211 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12212 (skip-chars-forward " \t")
12213 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12214 (if (org-in-commented-heading-p t)
12215 (delete-region (point)
12216 (progn (search-forward " " (line-end-position) 'move)
12217 (skip-chars-forward " \t")
12218 (point)))
12219 (insert org-comment-string)
12220 (unless (eolp) (insert " ")))))
12222 (defvar org-last-todo-state-is-todo nil
12223 "This is non-nil when the last TODO state change led to a TODO state.
12224 If the last change removed the TODO tag or switched to DONE, then
12225 this is nil.")
12227 (defvar org-setting-tags nil) ; dynamically skipped
12229 (defvar org-todo-setup-filter-hook nil
12230 "Hook for functions that pre-filter todo specs.
12231 Each function takes a todo spec and returns either nil or the spec
12232 transformed into canonical form." )
12234 (defvar org-todo-get-default-hook nil
12235 "Hook for functions that get a default item for todo.
12236 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12237 nil or a string to be used for the todo mark." )
12239 (defvar org-agenda-headline-snapshot-before-repeat)
12241 (defun org-current-effective-time ()
12242 "Return current time adjusted for `org-extend-today-until' variable."
12243 (let* ((ct (org-current-time))
12244 (dct (decode-time ct))
12245 (ct1
12246 (cond
12247 (org-use-last-clock-out-time-as-effective-time
12248 (or (org-clock-get-last-clock-out-time) ct))
12249 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12250 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12251 (t ct))))
12252 ct1))
12254 (defun org-todo-yesterday (&optional arg)
12255 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12256 (interactive "P")
12257 (if (eq major-mode 'org-agenda-mode)
12258 (apply 'org-agenda-todo-yesterday arg)
12259 (let* ((hour (third (decode-time
12260 (org-current-time))))
12261 (org-extend-today-until (1+ hour)))
12262 (org-todo arg))))
12264 (defvar org-block-entry-blocking ""
12265 "First entry preventing the TODO state change.")
12267 (defun org-cancel-repeater ()
12268 "Cancel a repeater by setting its numeric value to zero."
12269 (interactive)
12270 (save-excursion
12271 (org-back-to-heading t)
12272 (let ((bound1 (point))
12273 (bound0 (save-excursion (outline-next-heading) (point))))
12274 (when (re-search-forward
12275 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12276 org-deadline-time-regexp "\\)\\|\\("
12277 org-ts-regexp "\\)")
12278 bound0 t)
12279 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12280 (replace-match "0" t nil nil 1))))))
12282 (defun org-todo (&optional arg)
12283 "Change the TODO state of an item.
12284 The state of an item is given by a keyword at the start of the heading,
12285 like
12286 *** TODO Write paper
12287 *** DONE Call mom
12289 The different keywords are specified in the variable `org-todo-keywords'.
12290 By default the available states are \"TODO\" and \"DONE\".
12291 So for this example: when the item starts with TODO, it is changed to DONE.
12292 When it starts with DONE, the DONE is removed. And when neither TODO nor
12293 DONE are present, add TODO at the beginning of the heading.
12295 With \\[universal-argument] prefix arg, use completion to determine the new \
12296 state.
12297 With numeric prefix arg, switch to that state.
12298 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12299 keywords (nextset).
12300 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12301 With a numeric prefix arg of 0, inhibit note taking for the change.
12302 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12304 When called through ELisp, arg is also interpreted in the following way:
12305 'none -> empty state
12306 \"\"(empty string) -> switch to empty state
12307 'done -> switch to DONE
12308 'nextset -> switch to the next set of keywords
12309 'previousset -> switch to the previous set of keywords
12310 \"WAITING\" -> switch to the specified keyword, but only if it
12311 really is a member of `org-todo-keywords'."
12312 (interactive "P")
12313 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12314 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12315 'region-start-level 'region))
12316 org-loop-over-headlines-in-active-region)
12317 (org-map-entries
12318 `(org-todo ,arg)
12319 org-loop-over-headlines-in-active-region
12320 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12321 (if (equal arg '(16)) (setq arg 'nextset))
12322 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12323 (let ((org-blocker-hook org-blocker-hook)
12324 commentp
12325 case-fold-search)
12326 (when (equal arg '(64))
12327 (setq arg nil org-blocker-hook nil))
12328 (when (and org-blocker-hook
12329 (or org-inhibit-blocking
12330 (org-entry-get nil "NOBLOCKING")))
12331 (setq org-blocker-hook nil))
12332 (save-excursion
12333 (catch 'exit
12334 (org-back-to-heading t)
12335 (when (org-in-commented-heading-p t)
12336 (org-toggle-comment)
12337 (setq commentp t))
12338 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12339 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12340 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12341 (let* ((match-data (match-data))
12342 (startpos (point-at-bol))
12343 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12344 (org-log-done org-log-done)
12345 (org-log-repeat org-log-repeat)
12346 (org-todo-log-states org-todo-log-states)
12347 (org-inhibit-logging
12348 (if (equal arg 0)
12349 (progn (setq arg nil) 'note) org-inhibit-logging))
12350 (this (match-string 1))
12351 (hl-pos (match-beginning 0))
12352 (head (org-get-todo-sequence-head this))
12353 (ass (assoc head org-todo-kwd-alist))
12354 (interpret (nth 1 ass))
12355 (done-word (nth 3 ass))
12356 (final-done-word (nth 4 ass))
12357 (org-last-state (or this ""))
12358 (completion-ignore-case t)
12359 (member (member this org-todo-keywords-1))
12360 (tail (cdr member))
12361 (org-state (cond
12362 ((and org-todo-key-trigger
12363 (or (and (equal arg '(4))
12364 (eq org-use-fast-todo-selection 'prefix))
12365 (and (not arg) org-use-fast-todo-selection
12366 (not (eq org-use-fast-todo-selection
12367 'prefix)))))
12368 ;; Use fast selection
12369 (org-fast-todo-selection))
12370 ((and (equal arg '(4))
12371 (or (not org-use-fast-todo-selection)
12372 (not org-todo-key-trigger)))
12373 ;; Read a state with completion
12374 (org-icompleting-read
12375 "State: " (mapcar 'list org-todo-keywords-1)
12376 nil t))
12377 ((eq arg 'right)
12378 (if this
12379 (if tail (car tail) nil)
12380 (car org-todo-keywords-1)))
12381 ((eq arg 'left)
12382 (if (equal member org-todo-keywords-1)
12384 (if this
12385 (nth (- (length org-todo-keywords-1)
12386 (length tail) 2)
12387 org-todo-keywords-1)
12388 (org-last org-todo-keywords-1))))
12389 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12390 (setq arg nil))) ; hack to fall back to cycling
12391 (arg
12392 ;; user or caller requests a specific state
12393 (cond
12394 ((equal arg "") nil)
12395 ((eq arg 'none) nil)
12396 ((eq arg 'done) (or done-word (car org-done-keywords)))
12397 ((eq arg 'nextset)
12398 (or (car (cdr (member head org-todo-heads)))
12399 (car org-todo-heads)))
12400 ((eq arg 'previousset)
12401 (let ((org-todo-heads (reverse org-todo-heads)))
12402 (or (car (cdr (member head org-todo-heads)))
12403 (car org-todo-heads))))
12404 ((car (member arg org-todo-keywords-1)))
12405 ((stringp arg)
12406 (user-error "State `%s' not valid in this file" arg))
12407 ((nth (1- (prefix-numeric-value arg))
12408 org-todo-keywords-1))))
12409 ((null member) (or head (car org-todo-keywords-1)))
12410 ((equal this final-done-word) nil) ;; -> make empty
12411 ((null tail) nil) ;; -> first entry
12412 ((memq interpret '(type priority))
12413 (if (eq this-command last-command)
12414 (car tail)
12415 (if (> (length tail) 0)
12416 (or done-word (car org-done-keywords))
12417 nil)))
12419 (car tail))))
12420 (org-state (or
12421 (run-hook-with-args-until-success
12422 'org-todo-get-default-hook org-state org-last-state)
12423 org-state))
12424 (next (if org-state (concat " " org-state " ") " "))
12425 (change-plist (list :type 'todo-state-change :from this :to org-state
12426 :position startpos))
12427 dolog now-done-p)
12428 (when org-blocker-hook
12429 (setq org-last-todo-state-is-todo
12430 (not (member this org-done-keywords)))
12431 (unless (save-excursion
12432 (save-match-data
12433 (org-with-wide-buffer
12434 (run-hook-with-args-until-failure
12435 'org-blocker-hook change-plist))))
12436 (if (org-called-interactively-p 'interactive)
12437 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12438 this org-state org-block-entry-blocking)
12439 ;; fail silently
12440 (message "TODO state change from %s to %s blocked (by \"%s\")"
12441 this org-state org-block-entry-blocking)
12442 (throw 'exit nil))))
12443 (store-match-data match-data)
12444 (replace-match next t t)
12445 (unless (pos-visible-in-window-p hl-pos)
12446 (message "TODO state changed to %s" (org-trim next)))
12447 (unless head
12448 (setq head (org-get-todo-sequence-head org-state)
12449 ass (assoc head org-todo-kwd-alist)
12450 interpret (nth 1 ass)
12451 done-word (nth 3 ass)
12452 final-done-word (nth 4 ass)))
12453 (when (memq arg '(nextset previousset))
12454 (message "Keyword-Set %d/%d: %s"
12455 (- (length org-todo-sets) -1
12456 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12457 (length org-todo-sets)
12458 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12459 (setq org-last-todo-state-is-todo
12460 (not (member org-state org-done-keywords)))
12461 (setq now-done-p (and (member org-state org-done-keywords)
12462 (not (member this org-done-keywords))))
12463 (and logging (org-local-logging logging))
12464 (when (and (or org-todo-log-states org-log-done)
12465 (not (eq org-inhibit-logging t))
12466 (not (memq arg '(nextset previousset))))
12467 ;; we need to look at recording a time and note
12468 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12469 (nth 2 (assoc this org-todo-log-states))))
12470 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12471 (setq dolog 'time))
12472 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12473 (and org-state
12474 (member org-state org-not-done-keywords)
12475 (not (member this org-not-done-keywords))))
12476 ;; This is now a todo state and was not one before
12477 ;; If there was a CLOSED time stamp, get rid of it.
12478 (org-add-planning-info nil nil 'closed))
12479 (when (and now-done-p org-log-done)
12480 ;; It is now done, and it was not done before
12481 (org-add-planning-info 'closed (org-current-effective-time))
12482 (if (and (not dolog) (eq 'note org-log-done))
12483 (org-add-log-setup 'done org-state this 'findpos 'note)))
12484 (when (and org-state dolog)
12485 ;; This is a non-nil state, and we need to log it
12486 (org-add-log-setup 'state org-state this 'findpos dolog)))
12487 ;; Fixup tag positioning
12488 (org-todo-trigger-tag-changes org-state)
12489 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12490 (when org-provide-todo-statistics
12491 (org-update-parent-todo-statistics))
12492 (run-hooks 'org-after-todo-state-change-hook)
12493 (if (and arg (not (member org-state org-done-keywords)))
12494 (setq head (org-get-todo-sequence-head org-state)))
12495 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12496 ;; Do we need to trigger a repeat?
12497 (when now-done-p
12498 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12499 ;; This is for the agenda, take a snapshot of the headline.
12500 (save-match-data
12501 (setq org-agenda-headline-snapshot-before-repeat
12502 (org-get-heading))))
12503 (org-auto-repeat-maybe org-state))
12504 ;; Fixup cursor location if close to the keyword
12505 (if (and (outline-on-heading-p)
12506 (not (bolp))
12507 (save-excursion (beginning-of-line 1)
12508 (looking-at org-todo-line-regexp))
12509 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12510 (progn
12511 (goto-char (or (match-end 2) (match-end 1)))
12512 (and (looking-at " ") (just-one-space))))
12513 (when org-trigger-hook
12514 (save-excursion
12515 (run-hook-with-args 'org-trigger-hook change-plist)))
12516 (when commentp (org-toggle-comment))))))))
12518 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12519 "Block turning an entry into a TODO, using the hierarchy.
12520 This checks whether the current task should be blocked from state
12521 changes. Such blocking occurs when:
12523 1. The task has children which are not all in a completed state.
12525 2. A task has a parent with the property :ORDERED:, and there
12526 are siblings prior to the current task with incomplete
12527 status.
12529 3. The parent of the task is blocked because it has siblings that should
12530 be done first, or is child of a block grandparent TODO entry."
12532 (if (not org-enforce-todo-dependencies)
12533 t ; if locally turned off don't block
12534 (catch 'dont-block
12535 ;; If this is not a todo state change, or if this entry is already DONE,
12536 ;; do not block
12537 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12538 (member (plist-get change-plist :from)
12539 (cons 'done org-done-keywords))
12540 (member (plist-get change-plist :to)
12541 (cons 'todo org-not-done-keywords))
12542 (not (plist-get change-plist :to)))
12543 (throw 'dont-block t))
12544 ;; If this task has children, and any are undone, it's blocked
12545 (save-excursion
12546 (org-back-to-heading t)
12547 (let ((this-level (funcall outline-level)))
12548 (outline-next-heading)
12549 (let ((child-level (funcall outline-level)))
12550 (while (and (not (eobp))
12551 (> child-level this-level))
12552 ;; this todo has children, check whether they are all
12553 ;; completed
12554 (if (and (not (org-entry-is-done-p))
12555 (org-entry-is-todo-p))
12556 (progn (setq org-block-entry-blocking (org-get-heading))
12557 (throw 'dont-block nil)))
12558 (outline-next-heading)
12559 (setq child-level (funcall outline-level))))))
12560 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12561 ;; any previous siblings are undone, it's blocked
12562 (save-excursion
12563 (org-back-to-heading t)
12564 (let* ((pos (point))
12565 (parent-pos (and (org-up-heading-safe) (point))))
12566 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12567 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12568 (forward-line 1)
12569 (re-search-forward org-not-done-heading-regexp pos t))
12570 (setq org-block-entry-blocking (match-string 0))
12571 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12572 ;; Search further up the hierarchy, to see if an ancestor is blocked
12573 (while t
12574 (goto-char parent-pos)
12575 (if (not (looking-at org-not-done-heading-regexp))
12576 (throw 'dont-block t)) ; do not block, parent is not a TODO
12577 (setq pos (point))
12578 (setq parent-pos (and (org-up-heading-safe) (point)))
12579 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12580 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12581 (forward-line 1)
12582 (re-search-forward org-not-done-heading-regexp pos t)
12583 (setq org-block-entry-blocking (org-get-heading)))
12584 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12586 (defcustom org-track-ordered-property-with-tag nil
12587 "Should the ORDERED property also be shown as a tag?
12588 The ORDERED property decides if an entry should require subtasks to be
12589 completed in sequence. Since a property is not very visible, setting
12590 this option means that toggling the ORDERED property with the command
12591 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12592 not relevant for the behavior, but it makes things more visible.
12594 Note that toggling the tag with tags commands will not change the property
12595 and therefore not influence behavior!
12597 This can be t, meaning the tag ORDERED should be used, It can also be a
12598 string to select a different tag for this task."
12599 :group 'org-todo
12600 :type '(choice
12601 (const :tag "No tracking" nil)
12602 (const :tag "Track with ORDERED tag" t)
12603 (string :tag "Use other tag")))
12605 (defun org-toggle-ordered-property ()
12606 "Toggle the ORDERED property of the current entry.
12607 For better visibility, you can track the value of this property with a tag.
12608 See variable `org-track-ordered-property-with-tag'."
12609 (interactive)
12610 (let* ((t1 org-track-ordered-property-with-tag)
12611 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12612 (save-excursion
12613 (org-back-to-heading)
12614 (if (org-entry-get nil "ORDERED")
12615 (progn
12616 (org-delete-property "ORDERED")
12617 (and tag (org-toggle-tag tag 'off))
12618 (message "Subtasks can be completed in arbitrary order"))
12619 (org-entry-put nil "ORDERED" "t")
12620 (and tag (org-toggle-tag tag 'on))
12621 (message "Subtasks must be completed in sequence")))))
12623 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12624 (defun org-block-todo-from-checkboxes (change-plist)
12625 "Block turning an entry into a TODO, using checkboxes.
12626 This checks whether the current task should be blocked from state
12627 changes because there are unchecked boxes in this entry."
12628 (if (not org-enforce-todo-checkbox-dependencies)
12629 t ; if locally turned off don't block
12630 (catch 'dont-block
12631 ;; If this is not a todo state change, or if this entry is already DONE,
12632 ;; do not block
12633 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12634 (member (plist-get change-plist :from)
12635 (cons 'done org-done-keywords))
12636 (member (plist-get change-plist :to)
12637 (cons 'todo org-not-done-keywords))
12638 (not (plist-get change-plist :to)))
12639 (throw 'dont-block t))
12640 ;; If this task has checkboxes that are not checked, it's blocked
12641 (save-excursion
12642 (org-back-to-heading t)
12643 (let ((beg (point)) end)
12644 (outline-next-heading)
12645 (setq end (point))
12646 (goto-char beg)
12647 (if (org-list-search-forward
12648 (concat (org-item-beginning-re)
12649 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12650 "\\[[- ]\\]")
12651 end t)
12652 (progn
12653 (if (boundp 'org-blocked-by-checkboxes)
12654 (setq org-blocked-by-checkboxes t))
12655 (throw 'dont-block nil)))))
12656 t))) ; do not block
12658 (defun org-entry-blocked-p ()
12659 "Is the current entry blocked?"
12660 (org-with-silent-modifications
12661 (if (org-entry-get nil "NOBLOCKING")
12662 nil ;; Never block this entry
12663 (not (run-hook-with-args-until-failure
12664 'org-blocker-hook
12665 (list :type 'todo-state-change
12666 :position (point)
12667 :from 'todo
12668 :to 'done))))))
12670 (defun org-update-statistics-cookies (all)
12671 "Update the statistics cookie, either from TODO or from checkboxes.
12672 This should be called with the cursor in a line with a statistics cookie."
12673 (interactive "P")
12674 (if all
12675 (progn
12676 (org-update-checkbox-count 'all)
12677 (org-map-entries 'org-update-parent-todo-statistics))
12678 (if (not (org-at-heading-p))
12679 (org-update-checkbox-count)
12680 (let ((pos (point-marker))
12681 end l1 l2)
12682 (ignore-errors (org-back-to-heading t))
12683 (if (not (org-at-heading-p))
12684 (org-update-checkbox-count)
12685 (setq l1 (org-outline-level))
12686 (setq end (save-excursion
12687 (outline-next-heading)
12688 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12689 (point)))
12690 (if (and (save-excursion
12691 (re-search-forward
12692 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12693 (not (save-excursion (re-search-forward
12694 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12695 (org-update-checkbox-count)
12696 (if (and l2 (> l2 l1))
12697 (progn
12698 (goto-char end)
12699 (org-update-parent-todo-statistics))
12700 (goto-char pos)
12701 (beginning-of-line 1)
12702 (while (re-search-forward
12703 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12704 (point-at-eol) t)
12705 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12706 (goto-char pos)
12707 (move-marker pos nil)))))
12709 (defvar org-entry-property-inherited-from) ;; defined below
12710 (defun org-update-parent-todo-statistics ()
12711 "Update any statistics cookie in the parent of the current headline.
12712 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12713 the entire subtree and this will travel up the hierarchy and update
12714 statistics everywhere."
12715 (let* ((prop (save-excursion (org-up-heading-safe)
12716 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12717 (recursive (or (not org-hierarchical-todo-statistics)
12718 (and prop (string-match "\\<recursive\\>" prop))))
12719 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12721 (first t)
12722 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12723 level ltoggle l1 new ndel
12724 (cnt-all 0) (cnt-done 0) is-percent kwd
12725 checkbox-beg ov ovs ove cookie-present)
12726 (catch 'exit
12727 (save-excursion
12728 (beginning-of-line 1)
12729 (setq ltoggle (funcall outline-level))
12730 ;; Three situations are to consider:
12732 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12733 ;; to the top-level ancestor on the headline;
12735 ;; 2. If parent has "recursive" property, repeat up to the
12736 ;; headline setting that property, taking inheritance into
12737 ;; account;
12739 ;; 3. Else, move up to direct parent and proceed only once.
12740 (while (and (setq level (org-up-heading-safe))
12741 (or recursive first)
12742 (>= (point) lim))
12743 (setq first nil cookie-present nil)
12744 (unless (and level
12745 (not (string-match
12746 "\\<checkbox\\>"
12747 (downcase (or (org-entry-get nil "COOKIE_DATA")
12748 "")))))
12749 (throw 'exit nil))
12750 (while (re-search-forward box-re (point-at-eol) t)
12751 (setq cnt-all 0 cnt-done 0 cookie-present t)
12752 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12753 (save-match-data
12754 (unless (outline-next-heading) (throw 'exit nil))
12755 (while (and (looking-at org-complex-heading-regexp)
12756 (> (setq l1 (length (match-string 1))) level))
12757 (setq kwd (and (or recursive (= l1 ltoggle))
12758 (match-string 2)))
12759 (if (or (eq org-provide-todo-statistics 'all-headlines)
12760 (and (eq org-provide-todo-statistics t)
12761 (or (member kwd org-done-keywords)))
12762 (and (listp org-provide-todo-statistics)
12763 (stringp (car org-provide-todo-statistics))
12764 (or (member kwd org-provide-todo-statistics)
12765 (member kwd org-done-keywords)))
12766 (and (listp org-provide-todo-statistics)
12767 (listp (car org-provide-todo-statistics))
12768 (or (member kwd (car org-provide-todo-statistics))
12769 (and (member kwd org-done-keywords)
12770 (member kwd (cadr org-provide-todo-statistics))))))
12771 (setq cnt-all (1+ cnt-all))
12772 (if (eq org-provide-todo-statistics t)
12773 (and kwd (setq cnt-all (1+ cnt-all)))))
12774 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12775 (member kwd org-done-keywords))
12776 (and (listp org-provide-todo-statistics)
12777 (listp (car org-provide-todo-statistics))
12778 (member kwd org-done-keywords)
12779 (member kwd (cadr org-provide-todo-statistics)))
12780 (and (listp org-provide-todo-statistics)
12781 (stringp (car org-provide-todo-statistics))
12782 (member kwd org-done-keywords)))
12783 (setq cnt-done (1+ cnt-done)))
12784 (outline-next-heading)))
12785 (setq new
12786 (if is-percent
12787 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12788 (format "[%d/%d]" cnt-done cnt-all))
12789 ndel (- (match-end 0) checkbox-beg))
12790 ;; handle overlays when updating cookie from column view
12791 (when (setq ov (car (overlays-at checkbox-beg)))
12792 (setq ovs (overlay-start ov) ove (overlay-end ov))
12793 (delete-overlay ov))
12794 (goto-char checkbox-beg)
12795 (insert new)
12796 (delete-region (point) (+ (point) ndel))
12797 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12798 (when ov (move-overlay ov ovs ove)))
12799 (when cookie-present
12800 (run-hook-with-args 'org-after-todo-statistics-hook
12801 cnt-done (- cnt-all cnt-done))))))
12802 (run-hooks 'org-todo-statistics-hook)))
12804 (defvar org-after-todo-statistics-hook nil
12805 "Hook that is called after a TODO statistics cookie has been updated.
12806 Each function is called with two arguments: the number of not-done entries
12807 and the number of done entries.
12809 For example, the following function, when added to this hook, will switch
12810 an entry to DONE when all children are done, and back to TODO when new
12811 entries are set to a TODO status. Note that this hook is only called
12812 when there is a statistics cookie in the headline!
12814 (defun org-summary-todo (n-done n-not-done)
12815 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12816 (let (org-log-done org-log-states) ; turn off logging
12817 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12820 (defvar org-todo-statistics-hook nil
12821 "Hook that is run whenever Org thinks TODO statistics should be updated.
12822 This hook runs even if there is no statistics cookie present, in which case
12823 `org-after-todo-statistics-hook' would not run.")
12825 (defun org-todo-trigger-tag-changes (state)
12826 "Apply the changes defined in `org-todo-state-tags-triggers'."
12827 (let ((l org-todo-state-tags-triggers)
12828 changes)
12829 (when (or (not state) (equal state ""))
12830 (setq changes (append changes (cdr (assoc "" l)))))
12831 (when (and (stringp state) (> (length state) 0))
12832 (setq changes (append changes (cdr (assoc state l)))))
12833 (when (member state org-not-done-keywords)
12834 (setq changes (append changes (cdr (assoc 'todo l)))))
12835 (when (member state org-done-keywords)
12836 (setq changes (append changes (cdr (assoc 'done l)))))
12837 (dolist (c changes)
12838 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12840 (defun org-local-logging (value)
12841 "Get logging settings from a property VALUE."
12842 (let* (words w a)
12843 ;; directly set the variables, they are already local.
12844 (setq org-log-done nil
12845 org-log-repeat nil
12846 org-todo-log-states nil)
12847 (setq words (org-split-string value))
12848 (while (setq w (pop words))
12849 (cond
12850 ((setq a (assoc w org-startup-options))
12851 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12852 (set (nth 1 a) (nth 2 a))))
12853 ((setq a (org-extract-log-state-settings w))
12854 (and (member (car a) org-todo-keywords-1)
12855 (push a org-todo-log-states)))))))
12857 (defun org-get-todo-sequence-head (kwd)
12858 "Return the head of the TODO sequence to which KWD belongs.
12859 If KWD is not set, check if there is a text property remembering the
12860 right sequence."
12861 (let (p)
12862 (cond
12863 ((not kwd)
12864 (or (get-text-property (point-at-bol) 'org-todo-head)
12865 (progn
12866 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12867 nil (point-at-eol)))
12868 (get-text-property p 'org-todo-head))))
12869 ((not (member kwd org-todo-keywords-1))
12870 (car org-todo-keywords-1))
12871 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12873 (defun org-fast-todo-selection ()
12874 "Fast TODO keyword selection with single keys.
12875 Returns the new TODO keyword, or nil if no state change should occur."
12876 (let* ((fulltable org-todo-key-alist)
12877 (done-keywords org-done-keywords) ;; needed for the faces.
12878 (maxlen (apply 'max (mapcar
12879 (lambda (x)
12880 (if (stringp (car x)) (string-width (car x)) 0))
12881 fulltable)))
12882 (expert nil)
12883 (fwidth (+ maxlen 3 1 3))
12884 (ncol (/ (- (window-width) 4) fwidth))
12885 tg cnt e c tbl
12886 groups ingroup)
12887 (save-excursion
12888 (save-window-excursion
12889 (if expert
12890 (set-buffer (get-buffer-create " *Org todo*"))
12891 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12892 (erase-buffer)
12893 (org-set-local 'org-done-keywords done-keywords)
12894 (setq tbl fulltable cnt 0)
12895 (while (setq e (pop tbl))
12896 (cond
12897 ((equal e '(:startgroup))
12898 (push '() groups) (setq ingroup t)
12899 (when (not (= cnt 0))
12900 (setq cnt 0)
12901 (insert "\n"))
12902 (insert "{ "))
12903 ((equal e '(:endgroup))
12904 (setq ingroup nil cnt 0)
12905 (insert "}\n"))
12906 ((equal e '(:newline))
12907 (when (not (= cnt 0))
12908 (setq cnt 0)
12909 (insert "\n")
12910 (setq e (car tbl))
12911 (while (equal (car tbl) '(:newline))
12912 (insert "\n")
12913 (setq tbl (cdr tbl)))))
12915 (setq tg (car e) c (cdr e))
12916 (if ingroup (push tg (car groups)))
12917 (setq tg (org-add-props tg nil 'face
12918 (org-get-todo-face tg)))
12919 (if (and (= cnt 0) (not ingroup)) (insert " "))
12920 (insert "[" c "] " tg (make-string
12921 (- fwidth 4 (length tg)) ?\ ))
12922 (when (= (setq cnt (1+ cnt)) ncol)
12923 (insert "\n")
12924 (if ingroup (insert " "))
12925 (setq cnt 0)))))
12926 (insert "\n")
12927 (goto-char (point-min))
12928 (if (not expert) (org-fit-window-to-buffer))
12929 (message "[a-z..]:Set [SPC]:clear")
12930 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12931 (cond
12932 ((or (= c ?\C-g)
12933 (and (= c ?q) (not (rassoc c fulltable))))
12934 (setq quit-flag t))
12935 ((= c ?\ ) nil)
12936 ((setq e (rassoc c fulltable) tg (car e))
12938 (t (setq quit-flag t)))))))
12940 (defun org-entry-is-todo-p ()
12941 (member (org-get-todo-state) org-not-done-keywords))
12943 (defun org-entry-is-done-p ()
12944 (member (org-get-todo-state) org-done-keywords))
12946 (defun org-get-todo-state ()
12947 "Return the TODO keyword of the current subtree."
12948 (save-excursion
12949 (org-back-to-heading t)
12950 (and (looking-at org-todo-line-regexp)
12951 (match-end 2)
12952 (match-string 2))))
12954 (defun org-at-date-range-p (&optional inactive-ok)
12955 "Is the cursor inside a date range?"
12956 (interactive)
12957 (save-excursion
12958 (catch 'exit
12959 (let ((pos (point)))
12960 (skip-chars-backward "^[<\r\n")
12961 (skip-chars-backward "<[")
12962 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12963 (>= (match-end 0) pos)
12964 (throw 'exit t))
12965 (skip-chars-backward "^<[\r\n")
12966 (skip-chars-backward "<[")
12967 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12968 (>= (match-end 0) pos)
12969 (throw 'exit t)))
12970 nil)))
12972 (defun org-get-repeat (&optional tagline)
12973 "Check if there is a deadline/schedule with repeater in this entry."
12974 (save-match-data
12975 (save-excursion
12976 (org-back-to-heading t)
12977 (and (re-search-forward (if tagline
12978 (concat tagline "\\s-*" org-repeat-re)
12979 org-repeat-re)
12980 (org-entry-end-position) t)
12981 (match-string-no-properties 1)))))
12983 (defvar org-last-changed-timestamp)
12984 (defvar org-last-inserted-timestamp)
12985 (defvar org-log-post-message)
12986 (defvar org-log-note-purpose)
12987 (defvar org-log-note-how)
12988 (defvar org-log-note-extra)
12989 (defun org-auto-repeat-maybe (done-word)
12990 "Check if the current headline contains a repeated deadline/schedule.
12991 If yes, set TODO state back to what it was and change the base date
12992 of repeating deadline/scheduled time stamps to new date.
12993 This function is run automatically after each state change to a DONE state."
12994 ;; last-state is dynamically scoped into this function
12995 (let* ((repeat (org-get-repeat))
12996 (aa (assoc org-last-state org-todo-kwd-alist))
12997 (interpret (nth 1 aa))
12998 (head (nth 2 aa))
12999 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13000 (msg "Entry repeats: ")
13001 (org-log-done nil)
13002 (org-todo-log-states nil)
13003 re type n what ts time to-state)
13004 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13005 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13006 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13007 org-todo-repeat-to-state))
13008 (unless (and to-state (member to-state org-todo-keywords-1))
13009 (setq to-state (if (eq interpret 'type) org-last-state head)))
13010 (org-todo to-state)
13011 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13012 (org-entry-put nil "LAST_REPEAT" (format-time-string
13013 (org-time-stamp-format t t))))
13014 (when org-log-repeat
13015 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13016 (memq 'org-add-log-note post-command-hook))
13017 ;; OK, we are already setup for some record
13018 (if (eq org-log-repeat 'note)
13019 ;; make sure we take a note, not only a time stamp
13020 (setq org-log-note-how 'note))
13021 ;; Set up for taking a record
13022 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13023 org-last-state
13024 'findpos org-log-repeat)))
13025 (org-back-to-heading t)
13026 (org-add-planning-info nil nil 'closed)
13027 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13028 org-deadline-time-regexp "\\)\\|\\("
13029 org-ts-regexp "\\)"))
13030 (while (re-search-forward
13031 re (save-excursion (outline-next-heading) (point)) t)
13032 (setq type (if (match-end 1) org-scheduled-string
13033 (if (match-end 3) org-deadline-string "Plain:"))
13034 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13035 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13036 (setq n (string-to-number (match-string 2 ts))
13037 what (match-string 3 ts))
13038 (if (equal what "w") (setq n (* n 7) what "d"))
13039 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13040 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13041 ;; Preparation, see if we need to modify the start date for the change
13042 (when (match-end 1)
13043 (setq time (save-match-data (org-time-string-to-time ts)))
13044 (cond
13045 ((equal (match-string 1 ts) ".")
13046 ;; Shift starting date to today
13047 (org-timestamp-change
13048 (- (org-today) (time-to-days time))
13049 'day))
13050 ((equal (match-string 1 ts) "+")
13051 (let ((nshiftmax 10) (nshift 0))
13052 (while (or (= nshift 0)
13053 (<= (time-to-days time)
13054 (time-to-days (current-time))))
13055 (when (= (incf nshift) nshiftmax)
13056 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13057 (user-error "Abort")))
13058 (org-timestamp-change n (cdr (assoc what whata)))
13059 (org-at-timestamp-p t)
13060 (setq ts (match-string 1))
13061 (setq time (save-match-data (org-time-string-to-time ts)))))
13062 (org-timestamp-change (- n) (cdr (assoc what whata)))
13063 ;; rematch, so that we have everything in place for the real shift
13064 (org-at-timestamp-p t)
13065 (setq ts (match-string 1))
13066 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13067 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13068 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13069 (setq org-log-post-message msg)
13070 (message "%s" msg))))
13072 (defun org-show-todo-tree (arg)
13073 "Make a compact tree which shows all headlines marked with TODO.
13074 The tree will show the lines where the regexp matches, and all higher
13075 headlines above the match.
13076 With a \\[universal-argument] prefix, prompt for a regexp to match.
13077 With a numeric prefix N, construct a sparse tree for the Nth element
13078 of `org-todo-keywords-1'."
13079 (interactive "P")
13080 (let ((case-fold-search nil)
13081 (kwd-re
13082 (cond ((null arg) org-not-done-regexp)
13083 ((equal arg '(4))
13084 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13085 (mapcar 'list org-todo-keywords-1))))
13086 (concat "\\("
13087 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13088 "\\)\\>")))
13089 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13090 (regexp-quote (nth (1- (prefix-numeric-value arg))
13091 org-todo-keywords-1)))
13092 (t (user-error "Invalid prefix argument: %s" arg)))))
13093 (message "%d TODO entries found"
13094 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13096 (defun org-deadline (arg &optional time)
13097 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13098 With one universal prefix argument, remove any deadline from the item.
13099 With two universal prefix arguments, prompt for a warning delay.
13100 With argument TIME, set the deadline at the corresponding date. TIME
13101 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13102 (interactive "P")
13103 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13104 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13105 'region-start-level 'region))
13106 org-loop-over-headlines-in-active-region)
13107 (org-map-entries
13108 `(org-deadline ',arg ,time)
13109 org-loop-over-headlines-in-active-region
13110 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13111 (let* ((old-date (org-entry-get nil "DEADLINE"))
13112 (old-date-time (if old-date (org-time-string-to-time old-date)))
13113 (repeater (and old-date
13114 (string-match
13115 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13116 old-date)
13117 (match-string 1 old-date))))
13118 (cond
13119 ((equal arg '(4))
13120 (when (and old-date org-log-redeadline)
13121 (org-add-log-setup 'deldeadline nil old-date 'findpos
13122 org-log-redeadline))
13123 (org-remove-timestamp-with-keyword org-deadline-string)
13124 (message "Item no longer has a deadline."))
13125 ((equal arg '(16))
13126 (save-excursion
13127 (org-back-to-heading t)
13128 (if (re-search-forward
13129 org-deadline-time-regexp
13130 (save-excursion (outline-next-heading) (point)) t)
13131 (let* ((rpl0 (match-string 1))
13132 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13133 (replace-match
13134 (concat org-deadline-string
13135 " <" rpl
13136 (format " -%dd"
13137 (abs
13138 (- (time-to-days
13139 (save-match-data
13140 (org-read-date nil t nil "Warn starting from" old-date-time)))
13141 (time-to-days old-date-time))))
13142 ">") t t))
13143 (user-error "No deadline information to update"))))
13145 (org-add-planning-info 'deadline time 'closed)
13146 (when (and old-date org-log-redeadline
13147 (not (equal old-date
13148 (substring org-last-inserted-timestamp 1 -1))))
13149 (org-add-log-setup 'redeadline nil old-date 'findpos
13150 org-log-redeadline))
13151 (when repeater
13152 (save-excursion
13153 (org-back-to-heading t)
13154 (when (re-search-forward (concat org-deadline-string " "
13155 org-last-inserted-timestamp)
13156 (save-excursion
13157 (outline-next-heading) (point)) t)
13158 (goto-char (1- (match-end 0)))
13159 (insert " " repeater)
13160 (setq org-last-inserted-timestamp
13161 (concat (substring org-last-inserted-timestamp 0 -1)
13162 " " repeater
13163 (substring org-last-inserted-timestamp -1))))))
13164 (message "Deadline on %s" org-last-inserted-timestamp))))))
13166 (defun org-schedule (arg &optional time)
13167 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13168 With one universal prefix argument, remove any scheduling date from the item.
13169 With two universal prefix arguments, prompt for a delay cookie.
13170 With argument TIME, scheduled at the corresponding date. TIME can
13171 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13172 (interactive "P")
13173 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13174 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13175 'region-start-level 'region))
13176 org-loop-over-headlines-in-active-region)
13177 (org-map-entries
13178 `(org-schedule ',arg ,time)
13179 org-loop-over-headlines-in-active-region
13180 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13181 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13182 (old-date-time (if old-date (org-time-string-to-time old-date)))
13183 (repeater (and old-date
13184 (string-match
13185 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13186 old-date)
13187 (match-string 1 old-date))))
13188 (cond
13189 ((equal arg '(4))
13190 (progn
13191 (when (and old-date org-log-reschedule)
13192 (org-add-log-setup 'delschedule nil old-date 'findpos
13193 org-log-reschedule))
13194 (org-remove-timestamp-with-keyword org-scheduled-string)
13195 (message "Item is no longer scheduled.")))
13196 ((equal arg '(16))
13197 (save-excursion
13198 (org-back-to-heading t)
13199 (if (re-search-forward
13200 org-scheduled-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-scheduled-string
13206 " <" rpl
13207 (format " -%dd"
13208 (abs
13209 (- (time-to-days
13210 (save-match-data
13211 (org-read-date nil t nil "Delay until" old-date-time)))
13212 (time-to-days old-date-time))))
13213 ">") t t))
13214 (user-error "No scheduled information to update"))))
13216 (org-add-planning-info 'scheduled time 'closed)
13217 (when (and old-date org-log-reschedule
13218 (not (equal old-date
13219 (substring org-last-inserted-timestamp 1 -1))))
13220 (org-add-log-setup 'reschedule nil old-date 'findpos
13221 org-log-reschedule))
13222 (when repeater
13223 (save-excursion
13224 (org-back-to-heading t)
13225 (when (re-search-forward (concat org-scheduled-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 "Scheduled to %s" org-last-inserted-timestamp))))))
13237 (defun org-get-scheduled-time (pom &optional inherit)
13238 "Get the scheduled time as a time tuple, of a format suitable
13239 for calling org-schedule with, or if there is no scheduling,
13240 returns nil."
13241 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13242 (when time
13243 (apply 'encode-time (org-parse-time-string time)))))
13245 (defun org-get-deadline-time (pom &optional inherit)
13246 "Get the deadline as a time tuple, of a format suitable for
13247 calling org-deadline with, or if there is no scheduling, returns
13248 nil."
13249 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13250 (when time
13251 (apply 'encode-time (org-parse-time-string time)))))
13253 (defun org-remove-timestamp-with-keyword (keyword)
13254 "Remove all time stamps with KEYWORD in the current entry."
13255 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13256 beg)
13257 (save-excursion
13258 (org-back-to-heading t)
13259 (setq beg (point))
13260 (outline-next-heading)
13261 (while (re-search-backward re beg t)
13262 (replace-match "")
13263 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13264 (equal (char-before) ?\ ))
13265 (backward-delete-char 1)
13266 (if (string-match "^[ \t]*$" (buffer-substring
13267 (point-at-bol) (point-at-eol)))
13268 (delete-region (point-at-bol)
13269 (min (point-max) (1+ (point-at-eol))))))))))
13271 (defvar org-time-was-given) ; dynamically scoped parameter
13272 (defvar org-end-time-was-given) ; dynamically scoped parameter
13274 (defun org-add-planning-info (what &optional time &rest remove)
13275 "Insert new timestamp with keyword in the line directly after the headline.
13276 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13277 If non is given, the user is prompted for a date.
13278 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13279 be removed."
13280 (interactive)
13281 (let (org-time-was-given org-end-time-was-given ts
13282 end default-time default-input)
13284 (catch 'exit
13285 (when (and (memq what '(scheduled deadline))
13286 (or (not time)
13287 (and (stringp time)
13288 (string-match "^[-+]+[0-9]" time))))
13289 ;; Try to get a default date/time from existing timestamp
13290 (save-excursion
13291 (org-back-to-heading t)
13292 (setq end (save-excursion (outline-next-heading) (point)))
13293 (when (re-search-forward (if (eq what 'scheduled)
13294 org-scheduled-time-regexp
13295 org-deadline-time-regexp)
13296 end t)
13297 (setq ts (match-string 1)
13298 default-time
13299 (apply 'encode-time (org-parse-time-string ts))
13300 default-input (and ts (org-get-compact-tod ts))))))
13301 (when what
13302 (setq time
13303 (if (stringp time)
13304 ;; This is a string (relative or absolute), set proper date
13305 (apply 'encode-time
13306 (org-read-date-analyze
13307 time default-time (decode-time default-time)))
13308 ;; If necessary, get the time from the user
13309 (or time (org-read-date nil 'to-time nil nil
13310 default-time default-input)))))
13312 (when (and org-insert-labeled-timestamps-at-point
13313 (member what '(scheduled deadline)))
13314 (insert
13315 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13316 (org-insert-time-stamp time org-time-was-given
13317 nil nil nil (list org-end-time-was-given))
13318 (setq what nil))
13319 (save-excursion
13320 (save-restriction
13321 (let (col list elt ts buffer-invisibility-spec)
13322 (org-back-to-heading t)
13323 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13324 (goto-char (match-end 1))
13325 (setq col (current-column))
13326 (goto-char (match-end 0))
13327 (if (eobp) (insert "\n") (forward-char 1))
13328 (when (and (not what)
13329 (not (looking-at
13330 (concat "[ \t]*"
13331 org-keyword-time-not-clock-regexp))))
13332 ;; Nothing to add, nothing to remove...... :-)
13333 (throw 'exit nil))
13334 (if (and (not (looking-at org-outline-regexp))
13335 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13336 "[^\r\n]*"))
13337 (not (equal (match-string 1) org-clock-string)))
13338 (narrow-to-region (match-beginning 0) (match-end 0))
13339 (insert-before-markers "\n")
13340 (backward-char 1)
13341 (narrow-to-region (point) (point))
13342 (and org-adapt-indentation (org-indent-to-column col)))
13343 ;; Check if we have to remove something.
13344 (setq list (cons what remove))
13345 (while list
13346 (setq elt (pop list))
13347 (when (or (and (eq elt 'scheduled)
13348 (re-search-forward org-scheduled-time-regexp nil t))
13349 (and (eq elt 'deadline)
13350 (re-search-forward org-deadline-time-regexp nil t))
13351 (and (eq elt 'closed)
13352 (re-search-forward org-closed-time-regexp nil t)))
13353 (replace-match "")
13354 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13355 (and (looking-at "[ \t]+") (replace-match ""))
13356 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13357 (when what
13358 (insert
13359 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13360 (cond ((eq what 'scheduled) org-scheduled-string)
13361 ((eq what 'deadline) org-deadline-string)
13362 ((eq what 'closed) org-closed-string))
13363 " ")
13364 (setq ts (org-insert-time-stamp
13365 time
13366 (or org-time-was-given
13367 (and (eq what 'closed) org-log-done-with-time))
13368 (eq what 'closed)
13369 nil nil (list org-end-time-was-given)))
13370 (insert
13371 (if (not (or (bolp) (eq (char-before) ?\ )
13372 (memq (char-after) '(32 10))
13373 (eobp))) " " ""))
13374 (end-of-line 1))
13375 (goto-char (point-min))
13376 (widen)
13377 (if (and (looking-at "[ \t]*\n")
13378 (equal (char-before) ?\n))
13379 (delete-region (1- (point)) (point-at-eol)))
13380 ts))))))
13382 (defvar org-log-note-marker (make-marker))
13383 (defvar org-log-note-purpose nil)
13384 (defvar org-log-note-state nil)
13385 (defvar org-log-note-previous-state nil)
13386 (defvar org-log-note-how nil)
13387 (defvar org-log-note-extra nil)
13388 (defvar org-log-note-window-configuration nil)
13389 (defvar org-log-note-return-to (make-marker))
13390 (defvar org-log-note-effective-time nil
13391 "Remembered current time so that dynamically scoped
13392 `org-extend-today-until' affects tha timestamps in state change
13393 log")
13395 (defvar org-log-post-message nil
13396 "Message to be displayed after a log note has been stored.
13397 The auto-repeater uses this.")
13399 (defun org-add-note ()
13400 "Add a note to the current entry.
13401 This is done in the same way as adding a state change note."
13402 (interactive)
13403 (org-add-log-setup 'note nil nil 'findpos nil))
13405 (defvar org-property-end-re)
13406 (defun org-add-log-setup (&optional purpose state prev-state
13407 findpos how extra)
13408 "Set up the post command hook to take a note.
13409 If this is about to TODO state change, the new state is expected in STATE.
13410 When FINDPOS is non-nil, find the correct position for the note in
13411 the current entry. If not, assume that it can be inserted at point.
13412 HOW is an indicator what kind of note should be created.
13413 EXTRA is additional text that will be inserted into the notes buffer."
13414 (let* ((org-log-into-drawer (org-log-into-drawer))
13415 (drawer (cond ((stringp org-log-into-drawer)
13416 org-log-into-drawer)
13417 (org-log-into-drawer "LOGBOOK"))))
13418 (save-restriction
13419 (save-excursion
13420 (when findpos
13421 (org-back-to-heading t)
13422 (narrow-to-region (point) (save-excursion
13423 (outline-next-heading) (point)))
13424 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13425 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13426 "[^\r\n]*\\)?"))
13427 (goto-char (match-end 0))
13428 (cond
13429 (drawer
13430 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13431 nil t)
13432 (progn
13433 (goto-char (match-end 0))
13434 (or org-log-states-order-reversed
13435 (and (re-search-forward org-property-end-re nil t)
13436 (goto-char (1- (match-beginning 0))))))
13437 (insert "\n:" drawer ":\n:END:")
13438 (beginning-of-line 0)
13439 (org-indent-line)
13440 (beginning-of-line 2)
13441 (org-indent-line)
13442 (end-of-line 0)))
13443 ((and org-log-state-notes-insert-after-drawers
13444 (save-excursion
13445 (forward-line) (looking-at org-drawer-regexp)))
13446 (forward-line)
13447 (while (looking-at org-drawer-regexp)
13448 (goto-char (match-end 0))
13449 (re-search-forward org-property-end-re (point-max) t)
13450 (forward-line))
13451 (forward-line -1)))
13452 (unless org-log-states-order-reversed
13453 (and (= (char-after) ?\n) (forward-char 1))
13454 (org-skip-over-state-notes)
13455 (skip-chars-backward " \t\n\r")))
13456 (move-marker org-log-note-marker (point))
13457 (setq org-log-note-purpose purpose
13458 org-log-note-state state
13459 org-log-note-previous-state prev-state
13460 org-log-note-how how
13461 org-log-note-extra extra
13462 org-log-note-effective-time (org-current-effective-time))
13463 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13465 (defun org-skip-over-state-notes ()
13466 "Skip past the list of State notes in an entry."
13467 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13468 (when (ignore-errors (goto-char (org-in-item-p)))
13469 (let* ((struct (org-list-struct))
13470 (prevs (org-list-prevs-alist struct)))
13471 (while (looking-at "[ \t]*- State")
13472 (goto-char (or (org-list-get-next-item (point) struct prevs)
13473 (org-list-get-item-end (point) struct)))))))
13475 (defun org-add-log-note (&optional purpose)
13476 "Pop up a window for taking a note, and add this note later at point."
13477 (remove-hook 'post-command-hook 'org-add-log-note)
13478 (setq org-log-note-window-configuration (current-window-configuration))
13479 (delete-other-windows)
13480 (move-marker org-log-note-return-to (point))
13481 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13482 (goto-char org-log-note-marker)
13483 (org-switch-to-buffer-other-window "*Org Note*")
13484 (erase-buffer)
13485 (if (memq org-log-note-how '(time state))
13486 (let (current-prefix-arg) (org-store-log-note))
13487 (let ((org-inhibit-startup t)) (org-mode))
13488 (insert (format "# Insert note for %s.
13489 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13490 (cond
13491 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13492 ((eq org-log-note-purpose 'done) "closed todo item")
13493 ((eq org-log-note-purpose 'state)
13494 (format "state change from \"%s\" to \"%s\""
13495 (or org-log-note-previous-state "")
13496 (or org-log-note-state "")))
13497 ((eq org-log-note-purpose 'reschedule)
13498 "rescheduling")
13499 ((eq org-log-note-purpose 'delschedule)
13500 "no longer scheduled")
13501 ((eq org-log-note-purpose 'redeadline)
13502 "changing deadline")
13503 ((eq org-log-note-purpose 'deldeadline)
13504 "removing deadline")
13505 ((eq org-log-note-purpose 'refile)
13506 "refiling")
13507 ((eq org-log-note-purpose 'note)
13508 "this entry")
13509 (t (error "This should not happen")))))
13510 (if org-log-note-extra (insert org-log-note-extra))
13511 (org-set-local 'org-finish-function 'org-store-log-note)
13512 (run-hooks 'org-log-buffer-setup-hook)))
13514 (defvar org-note-abort nil) ; dynamically scoped
13515 (defun org-store-log-note ()
13516 "Finish taking a log note, and insert it to where it belongs."
13517 (let ((txt (buffer-string)))
13518 (kill-buffer (current-buffer))
13519 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13520 lines ind bul)
13521 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13522 (setq txt (replace-match "" t t txt)))
13523 (if (string-match "\\s-+\\'" txt)
13524 (setq txt (replace-match "" t t txt)))
13525 (setq lines (org-split-string txt "\n"))
13526 (when (and note (string-match "\\S-" note))
13527 (setq note
13528 (org-replace-escapes
13529 note
13530 (list (cons "%u" (user-login-name))
13531 (cons "%U" user-full-name)
13532 (cons "%t" (format-time-string
13533 (org-time-stamp-format 'long 'inactive)
13534 org-log-note-effective-time))
13535 (cons "%T" (format-time-string
13536 (org-time-stamp-format 'long nil)
13537 org-log-note-effective-time))
13538 (cons "%d" (format-time-string
13539 (org-time-stamp-format nil 'inactive)
13540 org-log-note-effective-time))
13541 (cons "%D" (format-time-string
13542 (org-time-stamp-format nil nil)
13543 org-log-note-effective-time))
13544 (cons "%s" (if org-log-note-state
13545 (concat "\"" org-log-note-state "\"")
13546 ""))
13547 (cons "%S" (if org-log-note-previous-state
13548 (concat "\"" org-log-note-previous-state "\"")
13549 "\"\"")))))
13550 (if lines (setq note (concat note " \\\\")))
13551 (push note lines))
13552 (when (or current-prefix-arg org-note-abort)
13553 (when org-log-into-drawer
13554 (org-remove-empty-drawer-at org-log-note-marker))
13555 (setq lines nil))
13556 (when lines
13557 (with-current-buffer (marker-buffer org-log-note-marker)
13558 (save-excursion
13559 (goto-char org-log-note-marker)
13560 (move-marker org-log-note-marker nil)
13561 (end-of-line 1)
13562 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13563 (setq ind (save-excursion
13564 (if (ignore-errors (goto-char (org-in-item-p)))
13565 (let ((struct (org-list-struct)))
13566 (org-list-get-ind
13567 (org-list-get-top-point struct) struct))
13568 (skip-chars-backward " \r\t\n")
13569 (cond
13570 ((and (org-at-heading-p)
13571 org-adapt-indentation)
13572 (1+ (org-current-level)))
13573 ((org-at-heading-p) 0)
13574 (t (org-get-indentation))))))
13575 (setq bul (org-list-bullet-string "-"))
13576 (org-indent-line-to ind)
13577 (insert bul (pop lines))
13578 (let ((ind-body (+ (length bul) ind)))
13579 (while lines
13580 (insert "\n")
13581 (org-indent-line-to ind-body)
13582 (insert (pop lines))))
13583 (message "Note stored")
13584 (org-back-to-heading t)
13585 (org-cycle-hide-drawers 'children))
13586 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13587 ;; from within `org-add-log-note' because `buffer-undo-list'
13588 ;; is then modified outside of `org-with-remote-undo'.
13589 (when (eq this-command 'org-agenda-todo)
13590 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13591 ;; Don't add undo information when called from `org-agenda-todo'
13592 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13593 (set-window-configuration org-log-note-window-configuration)
13594 (with-current-buffer (marker-buffer org-log-note-return-to)
13595 (goto-char org-log-note-return-to))
13596 (move-marker org-log-note-return-to nil)
13597 (and org-log-post-message (message "%s" org-log-post-message))))
13599 (defun org-remove-empty-drawer-at (pos)
13600 "Remove an empty drawer at position POS.
13601 POS may also be a marker."
13602 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13603 (org-with-wide-buffer
13604 (goto-char pos)
13605 (let ((drawer (org-element-at-point)))
13606 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13607 (not (org-element-property :contents-begin drawer)))
13608 (delete-region (org-element-property :begin drawer)
13609 (progn (goto-char (org-element-property :end drawer))
13610 (skip-chars-backward " \r\t\n")
13611 (forward-line)
13612 (point))))))))
13614 (defvar org-ts-type nil)
13615 (defun org-sparse-tree (&optional arg type)
13616 "Create a sparse tree, prompt for the details.
13617 This command can create sparse trees. You first need to select the type
13618 of match used to create the tree:
13620 t Show all TODO entries.
13621 T Show entries with a specific TODO keyword.
13622 m Show entries selected by a tags/property match.
13623 p Enter a property name and its value (both with completion on existing
13624 names/values) and show entries with that property.
13625 r Show entries matching a regular expression (`/' can be used as well).
13626 b Show deadlines and scheduled items before a date.
13627 a Show deadlines and scheduled items after a date.
13628 d Show deadlines due within `org-deadline-warning-days'.
13629 D Show deadlines and scheduled items between a date range."
13630 (interactive "P")
13631 (setq type (or type org-sparse-tree-default-date-type))
13632 (setq org-ts-type type)
13633 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13634 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13635 [c]ycle through date types: %s"
13636 (case type
13637 (all "all timestamps")
13638 (scheduled "only scheduled")
13639 (deadline "only deadline")
13640 (active "only active timestamps")
13641 (inactive "only inactive timestamps")
13642 (scheduled-or-deadline "scheduled/deadline")
13643 (closed "with a closed time-stamp")
13644 (otherwise "scheduled/deadline")))
13645 (let ((answer (read-char-exclusive)))
13646 (case answer
13648 (org-sparse-tree
13650 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13651 inactive closed)))))
13652 (?d (call-interactively #'org-check-deadlines))
13653 (?b (call-interactively #'org-check-before-date))
13654 (?a (call-interactively #'org-check-after-date))
13655 (?D (call-interactively #'org-check-dates-range))
13656 (?t (call-interactively #'org-show-todo-tree))
13657 (?T (org-show-todo-tree '(4)))
13658 (?m (call-interactively #'org-match-sparse-tree))
13659 ((?p ?P)
13660 (let* ((kwd (org-icompleting-read
13661 "Property: " (mapcar #'list (org-buffer-property-keys))))
13662 (value (org-icompleting-read
13663 "Value: " (mapcar #'list (org-property-values kwd)))))
13664 (unless (string-match "\\`{.*}\\'" value)
13665 (setq value (concat "\"" value "\"")))
13666 (org-match-sparse-tree arg (concat kwd "=" value))))
13667 ((?r ?R ?/) (call-interactively #'org-occur))
13668 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13670 (defvar org-occur-highlights nil
13671 "List of overlays used for occur matches.")
13672 (make-variable-buffer-local 'org-occur-highlights)
13673 (defvar org-occur-parameters nil
13674 "Parameters of the active org-occur calls.
13675 This is a list, each call to org-occur pushes as cons cell,
13676 containing the regular expression and the callback, onto the list.
13677 The list can contain several entries if `org-occur' has been called
13678 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13679 will only contain one set of parameters. When the highlights are
13680 removed (for example with `C-c C-c', or with the next edit (depending
13681 on `org-remove-highlights-with-change'), this variable is emptied
13682 as well.")
13683 (make-variable-buffer-local 'org-occur-parameters)
13685 (defun org-occur (regexp &optional keep-previous callback)
13686 "Make a compact tree which shows all matches of REGEXP.
13687 The tree will show the lines where the regexp matches, and all higher
13688 headlines above the match. It will also show the heading after the match,
13689 to make sure editing the matching entry is easy.
13690 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13691 call to `org-occur' will be kept, to allow stacking of calls to this
13692 command.
13693 If CALLBACK is non-nil, it is a function which is called to confirm
13694 that the match should indeed be shown."
13695 (interactive "sRegexp: \nP")
13696 (when (equal regexp "")
13697 (user-error "Regexp cannot be empty"))
13698 (unless keep-previous
13699 (org-remove-occur-highlights nil nil t))
13700 (push (cons regexp callback) org-occur-parameters)
13701 (let ((cnt 0))
13702 (save-excursion
13703 (goto-char (point-min))
13704 (if (or (not keep-previous) ; do not want to keep
13705 (not org-occur-highlights)) ; no previous matches
13706 ;; hide everything
13707 (org-overview))
13708 (while (re-search-forward regexp nil t)
13709 (when (or (not callback)
13710 (save-match-data (funcall callback)))
13711 (setq cnt (1+ cnt))
13712 (when org-highlight-sparse-tree-matches
13713 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13714 (org-show-context 'occur-tree))))
13715 (when org-remove-highlights-with-change
13716 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13717 nil 'local))
13718 (unless org-sparse-tree-open-archived-trees
13719 (org-hide-archived-subtrees (point-min) (point-max)))
13720 (run-hooks 'org-occur-hook)
13721 (if (org-called-interactively-p 'interactive)
13722 (message "%d match(es) for regexp %s" cnt regexp))
13723 cnt))
13725 (defun org-occur-next-match (&optional n reset)
13726 "Function for `next-error-function' to find sparse tree matches.
13727 N is the number of matches to move, when negative move backwards.
13728 RESET is entirely ignored - this function always goes back to the
13729 starting point when no match is found."
13730 (let* ((limit (if (< n 0) (point-min) (point-max)))
13731 (search-func (if (< n 0)
13732 'previous-single-char-property-change
13733 'next-single-char-property-change))
13734 (n (abs n))
13735 (pos (point))
13737 (catch 'exit
13738 (while (setq p1 (funcall search-func (point) 'org-type))
13739 (when (equal p1 limit)
13740 (goto-char pos)
13741 (user-error "No more matches"))
13742 (when (equal (get-char-property p1 'org-type) 'org-occur)
13743 (setq n (1- n))
13744 (when (= n 0)
13745 (goto-char p1)
13746 (throw 'exit (point))))
13747 (goto-char p1))
13748 (goto-char p1)
13749 (user-error "No more matches"))))
13751 (defun org-show-context (&optional key)
13752 "Make sure point and context are visible.
13753 How much context is shown depends upon the variables
13754 `org-show-hierarchy-above', `org-show-following-heading',
13755 `org-show-entry-below' and `org-show-siblings'."
13756 (let ((heading-p (org-at-heading-p t))
13757 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13758 (following-p (org-get-alist-option org-show-following-heading key))
13759 (entry-p (org-get-alist-option org-show-entry-below key))
13760 (siblings-p (org-get-alist-option org-show-siblings key)))
13761 ;; Show heading or entry text
13762 (if (and heading-p (not entry-p))
13763 (org-flag-heading nil) ; only show the heading
13764 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13765 (org-show-hidden-entry))) ; show entire entry
13766 (when following-p
13767 ;; Show next sibling, or heading below text
13768 (save-excursion
13769 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13770 (org-flag-heading nil))))
13771 (when siblings-p (org-show-siblings))
13772 (when hierarchy-p
13773 ;; show all higher headings, possibly with siblings
13774 (save-excursion
13775 (while (and (condition-case nil
13776 (progn (org-up-heading-all 1) t)
13777 (error nil))
13778 (not (bobp)))
13779 (org-flag-heading nil)
13780 (when siblings-p (org-show-siblings)))))
13781 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13783 (defvar org-reveal-start-hook nil
13784 "Hook run before revealing a location.")
13786 (defun org-reveal (&optional siblings)
13787 "Show current entry, hierarchy above it, and the following headline.
13788 This can be used to show a consistent set of context around locations
13789 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13790 not t for the search context.
13792 With optional argument SIBLINGS, on each level of the hierarchy all
13793 siblings are shown. This repairs the tree structure to what it would
13794 look like when opened with hierarchical calls to `org-cycle'.
13795 With double optional argument \\[universal-argument] \\[universal-argument], \
13796 go to the parent and show the
13797 entire tree."
13798 (interactive "P")
13799 (run-hooks 'org-reveal-start-hook)
13800 (let ((org-show-hierarchy-above t)
13801 (org-show-following-heading t)
13802 (org-show-siblings (if siblings t org-show-siblings)))
13803 (org-show-context nil))
13804 (when (equal siblings '(16))
13805 (save-excursion
13806 (when (org-up-heading-safe)
13807 (org-show-subtree)
13808 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13810 (defun org-highlight-new-match (beg end)
13811 "Highlight from BEG to END and mark the highlight is an occur headline."
13812 (let ((ov (make-overlay beg end)))
13813 (overlay-put ov 'face 'secondary-selection)
13814 (overlay-put ov 'org-type 'org-occur)
13815 (push ov org-occur-highlights)))
13817 (defun org-remove-occur-highlights (&optional beg end noremove)
13818 "Remove the occur highlights from the buffer.
13819 BEG and END are ignored. If NOREMOVE is nil, remove this function
13820 from the `before-change-functions' in the current buffer."
13821 (interactive)
13822 (unless org-inhibit-highlight-removal
13823 (mapc 'delete-overlay org-occur-highlights)
13824 (setq org-occur-highlights nil)
13825 (setq org-occur-parameters nil)
13826 (unless noremove
13827 (remove-hook 'before-change-functions
13828 'org-remove-occur-highlights 'local))))
13830 ;;;; Priorities
13832 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13833 "Regular expression matching the priority indicator.")
13835 (defvar org-remove-priority-next-time nil)
13837 (defun org-priority-up ()
13838 "Increase the priority of the current item."
13839 (interactive)
13840 (org-priority 'up))
13842 (defun org-priority-down ()
13843 "Decrease the priority of the current item."
13844 (interactive)
13845 (org-priority 'down))
13847 (defun org-priority (&optional action show)
13848 "Change the priority of an item.
13849 ACTION can be `set', `up', `down', or a character."
13850 (interactive "P")
13851 (if (equal action '(4))
13852 (org-show-priority)
13853 (unless org-enable-priority-commands
13854 (user-error "Priority commands are disabled"))
13855 (setq action (or action 'set))
13856 (let (current new news have remove)
13857 (save-excursion
13858 (org-back-to-heading t)
13859 (if (looking-at org-priority-regexp)
13860 (setq current (string-to-char (match-string 2))
13861 have t))
13862 (cond
13863 ((eq action 'remove)
13864 (setq remove t new ?\ ))
13865 ((or (eq action 'set)
13866 (if (featurep 'xemacs) (characterp action) (integerp action)))
13867 (if (not (eq action 'set))
13868 (setq new action)
13869 (message "Priority %c-%c, SPC to remove: "
13870 org-highest-priority org-lowest-priority)
13871 (save-match-data
13872 (setq new (read-char-exclusive))))
13873 (if (and (= (upcase org-highest-priority) org-highest-priority)
13874 (= (upcase org-lowest-priority) org-lowest-priority))
13875 (setq new (upcase new)))
13876 (cond ((equal new ?\ ) (setq remove t))
13877 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13878 (user-error "Priority must be between `%c' and `%c'"
13879 org-highest-priority org-lowest-priority))))
13880 ((eq action 'up)
13881 (setq new (if have
13882 (1- current) ; normal cycling
13883 ;; last priority was empty
13884 (if (eq last-command this-command)
13885 org-lowest-priority ; wrap around empty to lowest
13886 ;; default
13887 (if org-priority-start-cycle-with-default
13888 org-default-priority
13889 (1- org-default-priority))))))
13890 ((eq action 'down)
13891 (setq new (if have
13892 (1+ current) ; normal cycling
13893 ;; last priority was empty
13894 (if (eq last-command this-command)
13895 org-highest-priority ; wrap around empty to highest
13896 ;; default
13897 (if org-priority-start-cycle-with-default
13898 org-default-priority
13899 (1+ org-default-priority))))))
13900 (t (user-error "Invalid action")))
13901 (if (or (< (upcase new) org-highest-priority)
13902 (> (upcase new) org-lowest-priority))
13903 (if (and (memq action '(up down))
13904 (not have) (not (eq last-command this-command)))
13905 ;; `new' is from default priority
13906 (error
13907 "The default can not be set, see `org-default-priority' why")
13908 ;; normal cycling: `new' is beyond highest/lowest priority
13909 ;; and is wrapped around to the empty priority
13910 (setq remove t)))
13911 (setq news (format "%c" new))
13912 (if have
13913 (if remove
13914 (replace-match "" t t nil 1)
13915 (replace-match news t t nil 2))
13916 (if remove
13917 (user-error "No priority cookie found in line")
13918 (let ((case-fold-search nil))
13919 (looking-at org-todo-line-regexp))
13920 (if (match-end 2)
13921 (progn
13922 (goto-char (match-end 2))
13923 (insert " [#" news "]"))
13924 (goto-char (match-beginning 3))
13925 (insert "[#" news "] "))))
13926 (org-set-tags nil 'align))
13927 (if remove
13928 (message "Priority removed")
13929 (message "Priority of current item set to %s" news)))))
13931 (defun org-show-priority ()
13932 "Show the priority of the current item.
13933 This priority is composed of the main priority given with the [#A] cookies,
13934 and by additional input from the age of a schedules or deadline entry."
13935 (interactive)
13936 (let ((pri (if (eq major-mode 'org-agenda-mode)
13937 (org-get-at-bol 'priority)
13938 (save-excursion
13939 (save-match-data
13940 (beginning-of-line)
13941 (and (looking-at org-heading-regexp)
13942 (org-get-priority (match-string 0))))))))
13943 (message "Priority is %d" (if pri pri -1000))))
13945 (defun org-get-priority (s)
13946 "Find priority cookie and return priority."
13947 (save-match-data
13948 (if (functionp org-get-priority-function)
13949 (funcall org-get-priority-function)
13950 (if (not (string-match org-priority-regexp s))
13951 (* 1000 (- org-lowest-priority org-default-priority))
13952 (* 1000 (- org-lowest-priority
13953 (string-to-char (match-string 2 s))))))))
13955 ;;;; Tags
13957 (defvar org-agenda-archives-mode)
13958 (defvar org-map-continue-from nil
13959 "Position from where mapping should continue.
13960 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13962 (defvar org-scanner-tags nil
13963 "The current tag list while the tags scanner is running.")
13964 (defvar org-trust-scanner-tags nil
13965 "Should `org-get-tags-at' use the tags for the scanner.
13966 This is for internal dynamical scoping only.
13967 When this is non-nil, the function `org-get-tags-at' will return the value
13968 of `org-scanner-tags' instead of building the list by itself. This
13969 can lead to large speed-ups when the tags scanner is used in a file with
13970 many entries, and when the list of tags is retrieved, for example to
13971 obtain a list of properties. Building the tags list for each entry in such
13972 a file becomes an N^2 operation - but with this variable set, it scales
13973 as N.")
13975 (defun org-scan-tags (action matcher todo-only &optional start-level)
13976 "Sca headline tags with inheritance and produce output ACTION.
13978 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13979 or `agenda' to produce an entry list for an agenda view. It can also be
13980 a Lisp form or a function that should be called at each matched headline, in
13981 this case the return value is a list of all return values from these calls.
13983 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13984 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13985 only lines with a not-done TODO keyword are included in the output.
13986 This should be the same variable that was scoped into
13987 and set by `org-make-tags-matcher' when it constructed MATCHER.
13989 START-LEVEL can be a string with asterisks, reducing the scope to
13990 headlines matching this string."
13991 (require 'org-agenda)
13992 (let* ((re (concat "^"
13993 (if start-level
13994 ;; Get the correct level to match
13995 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13996 org-outline-regexp)
13997 " *\\(\\<\\("
13998 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13999 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14000 (props (list 'face 'default
14001 'done-face 'org-agenda-done
14002 'undone-face 'default
14003 'mouse-face 'highlight
14004 'org-not-done-regexp org-not-done-regexp
14005 'org-todo-regexp org-todo-regexp
14006 'org-complex-heading-regexp org-complex-heading-regexp
14007 'help-echo
14008 (format "mouse-2 or RET jump to org file %s"
14009 (abbreviate-file-name
14010 (or (buffer-file-name (buffer-base-buffer))
14011 (buffer-name (buffer-base-buffer)))))))
14012 (org-map-continue-from nil)
14013 lspos tags tags-list
14014 (tags-alist (list (cons 0 org-file-tags)))
14015 (llast 0) rtn rtn1 level category i txt
14016 todo marker entry priority)
14017 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14018 (setq action (list 'lambda nil action)))
14019 (save-excursion
14020 (goto-char (point-min))
14021 (when (eq action 'sparse-tree)
14022 (org-overview)
14023 (org-remove-occur-highlights))
14024 (while (let (case-fold-search)
14025 (re-search-forward re nil t))
14026 (setq org-map-continue-from nil)
14027 (catch :skip
14028 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14029 tags (if (match-end 4) (org-match-string-no-properties 4)))
14030 (goto-char (setq lspos (match-beginning 0)))
14031 (setq level (org-reduced-level (org-outline-level))
14032 category (org-get-category))
14033 (setq i llast llast level)
14034 ;; remove tag lists from same and sublevels
14035 (while (>= i level)
14036 (when (setq entry (assoc i tags-alist))
14037 (setq tags-alist (delete entry tags-alist)))
14038 (setq i (1- i)))
14039 ;; add the next tags
14040 (when tags
14041 (setq tags (org-split-string tags ":")
14042 tags-alist
14043 (cons (cons level tags) tags-alist)))
14044 ;; compile tags for current headline
14045 (setq tags-list
14046 (if org-use-tag-inheritance
14047 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14048 tags)
14049 org-scanner-tags tags-list)
14050 (when org-use-tag-inheritance
14051 (setcdr (car tags-alist)
14052 (mapcar (lambda (x)
14053 (setq x (copy-sequence x))
14054 (org-add-prop-inherited x))
14055 (cdar tags-alist))))
14056 (when (and tags org-use-tag-inheritance
14057 (or (not (eq t org-use-tag-inheritance))
14058 org-tags-exclude-from-inheritance))
14059 ;; selective inheritance, remove uninherited ones
14060 (setcdr (car tags-alist)
14061 (org-remove-uninherited-tags (cdar tags-alist))))
14062 (when (and
14064 ;; eval matcher only when the todo condition is OK
14065 (and (or (not todo-only) (member todo org-not-done-keywords))
14066 (let ((case-fold-search t) (org-trust-scanner-tags t))
14067 (eval matcher)))
14069 ;; Call the skipper, but return t if it does not skip,
14070 ;; so that the `and' form continues evaluating
14071 (progn
14072 (unless (eq action 'sparse-tree) (org-agenda-skip))
14075 ;; Check if timestamps are deselecting this entry
14076 (or (not todo-only)
14077 (and (member todo org-not-done-keywords)
14078 (or (not org-agenda-tags-todo-honor-ignore-options)
14079 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14081 ;; select this headline
14082 (cond
14083 ((eq action 'sparse-tree)
14084 (and org-highlight-sparse-tree-matches
14085 (org-get-heading) (match-end 0)
14086 (org-highlight-new-match
14087 (match-beginning 1) (match-end 1)))
14088 (org-show-context 'tags-tree))
14089 ((eq action 'agenda)
14090 (setq txt (org-agenda-format-item
14092 (concat
14093 (if (eq org-tags-match-list-sublevels 'indented)
14094 (make-string (1- level) ?.) "")
14095 (org-get-heading))
14096 level category
14097 tags-list)
14098 priority (org-get-priority txt))
14099 (goto-char lspos)
14100 (setq marker (org-agenda-new-marker))
14101 (org-add-props txt props
14102 'org-marker marker 'org-hd-marker marker 'org-category category
14103 'todo-state todo
14104 'priority priority 'type "tagsmatch")
14105 (push txt rtn))
14106 ((functionp action)
14107 (setq org-map-continue-from nil)
14108 (save-excursion
14109 (setq rtn1 (funcall action))
14110 (push rtn1 rtn)))
14111 (t (user-error "Invalid action")))
14113 ;; if we are to skip sublevels, jump to end of subtree
14114 (unless org-tags-match-list-sublevels
14115 (org-end-of-subtree t)
14116 (backward-char 1))))
14117 ;; Get the correct position from where to continue
14118 (if org-map-continue-from
14119 (goto-char org-map-continue-from)
14120 (and (= (point) lspos) (end-of-line 1)))))
14121 (when (and (eq action 'sparse-tree)
14122 (not org-sparse-tree-open-archived-trees))
14123 (org-hide-archived-subtrees (point-min) (point-max)))
14124 (nreverse rtn)))
14126 (defun org-remove-uninherited-tags (tags)
14127 "Remove all tags that are not inherited from the list TAGS."
14128 (cond
14129 ((eq org-use-tag-inheritance t)
14130 (if org-tags-exclude-from-inheritance
14131 (org-delete-all org-tags-exclude-from-inheritance tags)
14132 tags))
14133 ((not org-use-tag-inheritance) nil)
14134 ((stringp org-use-tag-inheritance)
14135 (delq nil (mapcar
14136 (lambda (x)
14137 (if (and (string-match org-use-tag-inheritance x)
14138 (not (member x org-tags-exclude-from-inheritance)))
14139 x nil))
14140 tags)))
14141 ((listp org-use-tag-inheritance)
14142 (delq nil (mapcar
14143 (lambda (x)
14144 (if (member x org-use-tag-inheritance) x nil))
14145 tags)))))
14147 (defun org-match-sparse-tree (&optional todo-only match)
14148 "Create a sparse tree according to tags string MATCH.
14149 MATCH can contain positive and negative selection of tags, like
14150 \"+WORK+URGENT-WITHBOSS\".
14151 If optional argument TODO-ONLY is non-nil, only select lines that are
14152 also TODO lines."
14153 (interactive "P")
14154 (org-agenda-prepare-buffers (list (current-buffer)))
14155 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14157 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14159 (defvar org-cached-props nil)
14160 (defun org-cached-entry-get (pom property)
14161 (if (or (eq t org-use-property-inheritance)
14162 (and (stringp org-use-property-inheritance)
14163 (string-match org-use-property-inheritance property))
14164 (and (listp org-use-property-inheritance)
14165 (member property org-use-property-inheritance)))
14166 ;; Caching is not possible, check it directly
14167 (org-entry-get pom property 'inherit)
14168 ;; Get all properties, so that we can do complicated checks easily
14169 (cdr (assoc property (or org-cached-props
14170 (setq org-cached-props
14171 (org-entry-properties pom)))))))
14173 (defun org-global-tags-completion-table (&optional files)
14174 "Return the list of all tags in all agenda buffer/files.
14175 Optional FILES argument is a list of files which can be used
14176 instead of the agenda files."
14177 (save-excursion
14178 (org-uniquify
14179 (delq nil
14180 (apply 'append
14181 (mapcar
14182 (lambda (file)
14183 (set-buffer (find-file-noselect file))
14184 (append (org-get-buffer-tags)
14185 (mapcar (lambda (x) (if (stringp (car-safe x))
14186 (list (car-safe x)) nil))
14187 org-tag-alist)))
14188 (if (and files (car files))
14189 files
14190 (org-agenda-files))))))))
14192 (defun org-make-tags-matcher (match)
14193 "Create the TAGS/TODO matcher form for the selection string MATCH.
14195 The variable `todo-only' is scoped dynamically into this function.
14196 It will be set to t if the matcher restricts matching to TODO entries,
14197 otherwise will not be touched.
14199 Returns a cons of the selection string MATCH and the constructed
14200 lisp form implementing the matcher. The matcher is to be evaluated
14201 at an Org entry, with point on the headline, and returns t if the
14202 entry matches the selection string MATCH. The returned lisp form
14203 references two variables with information about the entry, which
14204 must be bound around the form's evaluation: todo, the TODO keyword
14205 at the entry (or nil of none); and tags-list, the list of all tags
14206 at the entry including inherited ones. Additionally, the category
14207 of the entry (if any) must be specified as the text property
14208 'org-category on the headline.
14210 See also `org-scan-tags'.
14212 (declare (special todo-only))
14213 (unless (boundp 'todo-only)
14214 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14215 (unless match
14216 ;; Get a new match request, with completion against the global
14217 ;; tags table and the local tags in current buffer
14218 (let ((org-last-tags-completion-table
14219 (org-uniquify
14220 (delq nil (append (org-get-buffer-tags)
14221 (org-global-tags-completion-table))))))
14222 (setq match (org-completing-read-no-i
14223 "Match: " 'org-tags-completion-function nil nil nil
14224 'org-tags-history))))
14226 ;; Parse the string and create a lisp form
14227 (let ((match0 match)
14228 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14229 minus tag mm
14230 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14231 orterms term orlist re-p str-p level-p level-op time-p
14232 prop-p pn pv po gv rest (start 0) (ss 0))
14233 ;; Expand group tags
14234 (setq match (org-tags-expand match))
14236 ;; Check if there is a TODO part of this match, which would be the
14237 ;; part after a "/". TO make sure that this slash is not part of
14238 ;; a property value to be matched against, we also check that there
14239 ;; is no " after that slash.
14240 ;; First, find the last slash
14241 (while (string-match "/+" match ss)
14242 (setq start (match-beginning 0) ss (match-end 0)))
14243 (if (and (string-match "/+" match start)
14244 (not (save-match-data (string-match "\"" match start))))
14245 ;; match contains also a todo-matching request
14246 (progn
14247 (setq tagsmatch (substring match 0 (match-beginning 0))
14248 todomatch (substring match (match-end 0)))
14249 (if (string-match "^!" todomatch)
14250 (setq todo-only t todomatch (substring todomatch 1)))
14251 (if (string-match "^\\s-*$" todomatch)
14252 (setq todomatch nil)))
14253 ;; only matching tags
14254 (setq tagsmatch match todomatch nil))
14256 ;; Make the tags matcher
14257 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14258 (setq tagsmatcher t)
14259 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14260 (while (setq term (pop orterms))
14261 (while (and (equal (substring term -1) "\\") orterms)
14262 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14263 (while (string-match re term)
14264 (setq rest (substring term (match-end 0))
14265 minus (and (match-end 1)
14266 (equal (match-string 1 term) "-"))
14267 tag (save-match-data (replace-regexp-in-string
14268 "\\\\-" "-"
14269 (match-string 2 term)))
14270 re-p (equal (string-to-char tag) ?{)
14271 level-p (match-end 4)
14272 prop-p (match-end 5)
14273 mm (cond
14274 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14275 (level-p
14276 (setq level-op (org-op-to-function (match-string 3 term)))
14277 `(,level-op level ,(string-to-number
14278 (match-string 4 term))))
14279 (prop-p
14280 (setq pn (match-string 5 term)
14281 po (match-string 6 term)
14282 pv (match-string 7 term)
14283 re-p (equal (string-to-char pv) ?{)
14284 str-p (equal (string-to-char pv) ?\")
14285 time-p (save-match-data
14286 (string-match "^\"[[<].*[]>]\"$" pv))
14287 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14288 (if time-p (setq pv (org-matcher-time pv)))
14289 (setq po (org-op-to-function po (if time-p 'time str-p)))
14290 (cond
14291 ((equal pn "CATEGORY")
14292 (setq gv '(get-text-property (point) 'org-category)))
14293 ((equal pn "TODO")
14294 (setq gv 'todo))
14296 (setq gv `(org-cached-entry-get nil ,pn))))
14297 (if re-p
14298 (if (eq po 'org<>)
14299 `(not (string-match ,pv (or ,gv "")))
14300 `(string-match ,pv (or ,gv "")))
14301 (if str-p
14302 `(,po (or ,gv "") ,pv)
14303 `(,po (string-to-number (or ,gv ""))
14304 ,(string-to-number pv) ))))
14305 (t `(member ,tag tags-list)))
14306 mm (if minus (list 'not mm) mm)
14307 term rest)
14308 (push mm tagsmatcher))
14309 (push (if (> (length tagsmatcher) 1)
14310 (cons 'and tagsmatcher)
14311 (car tagsmatcher))
14312 orlist)
14313 (setq tagsmatcher nil))
14314 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14315 (setq tagsmatcher
14316 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14317 ;; Make the todo matcher
14318 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14319 (setq todomatcher t)
14320 (setq orterms (org-split-string todomatch "|") orlist nil)
14321 (while (setq term (pop orterms))
14322 (while (string-match re term)
14323 (setq minus (and (match-end 1)
14324 (equal (match-string 1 term) "-"))
14325 kwd (match-string 2 term)
14326 re-p (equal (string-to-char kwd) ?{)
14327 term (substring term (match-end 0))
14328 mm (if re-p
14329 `(string-match ,(substring kwd 1 -1) todo)
14330 (list 'equal 'todo kwd))
14331 mm (if minus (list 'not mm) mm))
14332 (push mm todomatcher))
14333 (push (if (> (length todomatcher) 1)
14334 (cons 'and todomatcher)
14335 (car todomatcher))
14336 orlist)
14337 (setq todomatcher nil))
14338 (setq todomatcher (if (> (length orlist) 1)
14339 (cons 'or orlist) (car orlist))))
14341 ;; Return the string and lisp forms of the matcher
14342 (setq matcher (if todomatcher
14343 (list 'and tagsmatcher todomatcher)
14344 tagsmatcher))
14345 (when todo-only
14346 (setq matcher (list 'and '(member todo org-not-done-keywords)
14347 matcher)))
14348 (cons match0 matcher)))
14350 (defun org-tags-expand (match &optional single-as-list downcased)
14351 "Expand group tags in MATCH.
14353 This replaces every group tag in MATCH with a regexp tag search.
14354 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14355 will be replaced like this:
14357 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14358 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14359 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14361 Replacing by a regexp preserves the structure of the match.
14362 E.g., this expansion
14364 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14366 will match anything tagged with \"Lab\" and \"Home\", or tagged
14367 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14369 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14370 assumed to be a single group tag, and the function will return
14371 the list of tags in this group.
14373 When DOWNCASE is non-nil, expand downcased TAGS."
14374 (if org-group-tags
14375 (let* ((case-fold-search t)
14376 (stable org-mode-syntax-table)
14377 (tal (or org-tag-groups-alist-for-agenda
14378 org-tag-groups-alist))
14379 (tal (if downcased
14380 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14381 (tml (mapcar 'car tal))
14382 (rtnmatch match) rpl)
14383 ;; @ and _ are allowed as word-components in tags
14384 (modify-syntax-entry ?@ "w" stable)
14385 (modify-syntax-entry ?_ "w" stable)
14386 (while (and tml
14387 (with-syntax-table stable
14388 (string-match
14389 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14390 (regexp-opt tml) "\\>\\)") rtnmatch)))
14391 (let* ((dir (match-string 1 rtnmatch))
14392 (tag (match-string 2 rtnmatch))
14393 (tag (if downcased (downcase tag) tag)))
14394 (setq tml (delete tag tml))
14395 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14396 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14397 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14398 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14399 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14400 (if single-as-list
14401 (or (reverse rpl) (list rtnmatch))
14402 rtnmatch))
14403 (if single-as-list (list (if downcased (downcase match) match))
14404 match)))
14406 (defun org-op-to-function (op &optional stringp)
14407 "Turn an operator into the appropriate function."
14408 (setq op
14409 (cond
14410 ((equal op "<" ) '(< string< org-time<))
14411 ((equal op ">" ) '(> org-string> org-time>))
14412 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14413 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14414 ((member op '("=" "==")) '(= string= org-time=))
14415 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14416 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14418 (defun org<> (a b) (not (= a b)))
14419 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14420 (defun org-string>= (a b) (not (string< a b)))
14421 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14422 (defun org-string<> (a b) (not (string= a b)))
14423 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14424 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14425 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14426 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14427 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14428 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14429 (defun org-2ft (s)
14430 "Convert S to a floating point time.
14431 If S is already a number, just return it. If it is a string, parse
14432 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14433 (cond
14434 ((numberp s) s)
14435 ((stringp s)
14436 (condition-case nil
14437 (float-time (apply 'encode-time (org-parse-time-string s)))
14438 (error 0.)))
14439 (t 0.)))
14441 (defun org-time-today ()
14442 "Time in seconds today at 0:00.
14443 Returns the float number of seconds since the beginning of the
14444 epoch to the beginning of today (00:00)."
14445 (float-time (apply 'encode-time
14446 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14448 (defun org-matcher-time (s)
14449 "Interpret a time comparison value."
14450 (save-match-data
14451 (cond
14452 ((string= s "<now>") (float-time))
14453 ((string= s "<today>") (org-time-today))
14454 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14455 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14456 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14457 (+ (org-time-today)
14458 (* (string-to-number (match-string 1 s))
14459 (cdr (assoc (match-string 2 s)
14460 '(("d" . 86400.0) ("w" . 604800.0)
14461 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14462 (t (org-2ft s)))))
14464 (defun org-match-any-p (re list)
14465 "Does re match any element of list?"
14466 (setq list (mapcar (lambda (x) (string-match re x)) list))
14467 (delq nil list))
14469 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14470 (defvar org-tags-overlay (make-overlay 1 1))
14471 (org-detach-overlay org-tags-overlay)
14473 (defun org-get-local-tags-at (&optional pos)
14474 "Get a list of tags defined in the current headline."
14475 (org-get-tags-at pos 'local))
14477 (defun org-get-local-tags ()
14478 "Get a list of tags defined in the current headline."
14479 (org-get-tags-at nil 'local))
14481 (defun org-get-tags-at (&optional pos local)
14482 "Get a list of all headline tags applicable at POS.
14483 POS defaults to point. If tags are inherited, the list contains
14484 the targets in the same sequence as the headlines appear, i.e.
14485 the tags of the current headline come last.
14486 When LOCAL is non-nil, only return tags from the current headline,
14487 ignore inherited ones."
14488 (interactive)
14489 (if (and org-trust-scanner-tags
14490 (or (not pos) (equal pos (point)))
14491 (not local))
14492 org-scanner-tags
14493 (let (tags ltags lastpos parent)
14494 (save-excursion
14495 (save-restriction
14496 (widen)
14497 (goto-char (or pos (point)))
14498 (save-match-data
14499 (catch 'done
14500 (condition-case nil
14501 (progn
14502 (org-back-to-heading t)
14503 (while (not (equal lastpos (point)))
14504 (setq lastpos (point))
14505 (when (looking-at
14506 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14507 (setq ltags (org-split-string
14508 (org-match-string-no-properties 1) ":"))
14509 (when parent
14510 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14511 (setq tags (append
14512 (if parent
14513 (org-remove-uninherited-tags ltags)
14514 ltags)
14515 tags)))
14516 (or org-use-tag-inheritance (throw 'done t))
14517 (if local (throw 'done t))
14518 (or (org-up-heading-safe) (error nil))
14519 (setq parent t)))
14520 (error nil)))))
14521 (if local
14522 tags
14523 (reverse (delete-dups
14524 (reverse (append
14525 (org-remove-uninherited-tags
14526 org-file-tags) tags)))))))))
14528 (defun org-add-prop-inherited (s)
14529 (add-text-properties 0 (length s) '(inherited t) s)
14532 (defun org-toggle-tag (tag &optional onoff)
14533 "Toggle the tag TAG for the current line.
14534 If ONOFF is `on' or `off', don't toggle but set to this state."
14535 (let (res current)
14536 (save-excursion
14537 (org-back-to-heading t)
14538 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14539 (point-at-eol) t)
14540 (progn
14541 (setq current (match-string 1))
14542 (replace-match ""))
14543 (setq current ""))
14544 (setq current (nreverse (org-split-string current ":")))
14545 (cond
14546 ((eq onoff 'on)
14547 (setq res t)
14548 (or (member tag current) (push tag current)))
14549 ((eq onoff 'off)
14550 (or (not (member tag current)) (setq current (delete tag current))))
14551 (t (if (member tag current)
14552 (setq current (delete tag current))
14553 (setq res t)
14554 (push tag current))))
14555 (end-of-line 1)
14556 (if current
14557 (progn
14558 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14559 (org-set-tags nil t))
14560 (delete-horizontal-space))
14561 (run-hooks 'org-after-tags-change-hook))
14562 res))
14564 (defun org-align-tags-here (to-col)
14565 ;; Assumes that this is a headline
14566 "Align tags on the current headline to TO-COL."
14567 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14568 (beginning-of-line 1)
14569 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14570 (< pos (match-beginning 2)))
14571 (progn
14572 (setq tags-l (- (match-end 2) (match-beginning 2)))
14573 (goto-char (match-beginning 1))
14574 (insert " ")
14575 (delete-region (point) (1+ (match-beginning 2)))
14576 (setq ncol (max (current-column)
14577 (1+ col)
14578 (if (> to-col 0)
14579 to-col
14580 (- (abs to-col) tags-l))))
14581 (setq p (point))
14582 (insert (make-string (- ncol (current-column)) ?\ ))
14583 (setq ncol (current-column))
14584 (when indent-tabs-mode (tabify p (point-at-eol)))
14585 (org-move-to-column (min ncol col)))
14586 (goto-char pos))))
14588 (defun org-set-tags-command (&optional arg just-align)
14589 "Call the set-tags command for the current entry."
14590 (interactive "P")
14591 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14592 (org-set-tags arg just-align)
14593 (save-excursion
14594 (unless (and (org-region-active-p)
14595 org-loop-over-headlines-in-active-region)
14596 (org-back-to-heading t))
14597 (org-set-tags arg just-align))))
14599 (defun org-set-tags-to (data)
14600 "Set the tags of the current entry to DATA, replacing the current tags.
14601 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14602 If DATA is nil or the empty string, any tags will be removed."
14603 (interactive "sTags: ")
14604 (setq data
14605 (cond
14606 ((eq data nil) "")
14607 ((equal data "") "")
14608 ((stringp data)
14609 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14610 ":"))
14611 ((listp data)
14612 (concat ":" (mapconcat 'identity data ":") ":"))))
14613 (when data
14614 (save-excursion
14615 (org-back-to-heading t)
14616 (when (looking-at org-complex-heading-regexp)
14617 (if (match-end 5)
14618 (progn
14619 (goto-char (match-beginning 5))
14620 (insert data)
14621 (delete-region (point) (point-at-eol))
14622 (org-set-tags nil 'align))
14623 (goto-char (point-at-eol))
14624 (insert " " data)
14625 (org-set-tags nil 'align)))
14626 (beginning-of-line 1)
14627 (if (looking-at ".*?\\([ \t]+\\)$")
14628 (delete-region (match-beginning 1) (match-end 1))))))
14630 (defun org-align-all-tags ()
14631 "Align the tags i all headings."
14632 (interactive)
14633 (save-excursion
14634 (or (ignore-errors (org-back-to-heading t))
14635 (outline-next-heading))
14636 (if (org-at-heading-p)
14637 (org-set-tags t)
14638 (message "No headings"))))
14640 (defvar org-indent-indentation-per-level)
14641 (defun org-set-tags (&optional arg just-align)
14642 "Set the tags for the current headline.
14643 With prefix ARG, realign all tags in headings in the current buffer.
14644 When JUST-ALIGN is non-nil, only align tags."
14645 (interactive "P")
14646 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14647 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14648 'region-start-level 'region))
14649 org-loop-over-headlines-in-active-region)
14650 (org-map-entries
14651 ;; We don't use ARG and JUST-ALIGN here because these args
14652 ;; are not useful when looping over headlines.
14653 `(org-set-tags)
14654 org-loop-over-headlines-in-active-region
14655 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14656 (let* ((re org-outline-regexp-bol)
14657 (current (unless arg (org-get-tags-string)))
14658 (col (current-column))
14659 (org-setting-tags t)
14660 table current-tags inherited-tags ; computed below when needed
14661 tags p0 c0 c1 rpl di tc level)
14662 (if arg
14663 (save-excursion
14664 (goto-char (point-min))
14665 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14666 (while (re-search-forward re nil t)
14667 (org-set-tags nil t)
14668 (end-of-line 1)))
14669 (message "All tags realigned to column %d" org-tags-column))
14670 (if just-align
14671 (setq tags current)
14672 ;; Get a new set of tags from the user
14673 (save-excursion
14674 (setq table (append org-tag-persistent-alist
14675 (or org-tag-alist (org-get-buffer-tags))
14676 (and
14677 org-complete-tags-always-offer-all-agenda-tags
14678 (org-global-tags-completion-table
14679 (org-agenda-files))))
14680 org-last-tags-completion-table table
14681 current-tags (org-split-string current ":")
14682 inherited-tags (nreverse
14683 (nthcdr (length current-tags)
14684 (nreverse (org-get-tags-at))))
14685 tags
14686 (if (or (eq t org-use-fast-tag-selection)
14687 (and org-use-fast-tag-selection
14688 (delq nil (mapcar 'cdr table))))
14689 (org-fast-tag-selection
14690 current-tags inherited-tags table
14691 (if org-fast-tag-selection-include-todo
14692 org-todo-key-alist))
14693 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14694 (org-trim
14695 (org-icompleting-read "Tags: "
14696 'org-tags-completion-function
14697 nil nil current 'org-tags-history))))))
14698 (while (string-match "[-+&]+" tags)
14699 ;; No boolean logic, just a list
14700 (setq tags (replace-match ":" t t tags))))
14702 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14704 (if org-tags-sort-function
14705 (setq tags (mapconcat 'identity
14706 (sort (org-split-string
14707 tags (org-re "[^[:alnum:]_@#%]+"))
14708 org-tags-sort-function) ":")))
14710 (if (string-match "\\`[\t ]*\\'" tags)
14711 (setq tags "")
14712 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14713 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14715 ;; Insert new tags at the correct column
14716 (beginning-of-line 1)
14717 (setq level (or (and (looking-at org-outline-regexp)
14718 (- (match-end 0) (point) 1))
14720 (cond
14721 ((and (equal current "") (equal tags "")))
14722 ((re-search-forward
14723 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14724 (point-at-eol) t)
14725 (if (equal tags "")
14726 (setq rpl "")
14727 (goto-char (match-beginning 0))
14728 (setq c0 (current-column)
14729 ;; compute offset for the case of org-indent-mode active
14730 di (if (org-bound-and-true-p org-indent-mode)
14731 (* (1- org-indent-indentation-per-level) (1- level))
14733 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14734 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14735 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14736 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14737 (replace-match rpl t t)
14738 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14739 tags)
14740 (t (error "Tags alignment failed")))
14741 (org-move-to-column col)
14742 (unless just-align
14743 (run-hooks 'org-after-tags-change-hook))))))
14745 (defun org-change-tag-in-region (beg end tag off)
14746 "Add or remove TAG for each entry in the region.
14747 This works in the agenda, and also in an org-mode buffer."
14748 (interactive
14749 (list (region-beginning) (region-end)
14750 (let ((org-last-tags-completion-table
14751 (if (derived-mode-p 'org-mode)
14752 (org-uniquify
14753 (delq nil (append (org-get-buffer-tags)
14754 (org-global-tags-completion-table))))
14755 (org-global-tags-completion-table))))
14756 (org-icompleting-read
14757 "Tag: " 'org-tags-completion-function nil nil nil
14758 'org-tags-history))
14759 (progn
14760 (message "[s]et or [r]emove? ")
14761 (equal (read-char-exclusive) ?r))))
14762 (if (fboundp 'deactivate-mark) (deactivate-mark))
14763 (let ((agendap (equal major-mode 'org-agenda-mode))
14764 l1 l2 m buf pos newhead (cnt 0))
14765 (goto-char end)
14766 (setq l2 (1- (org-current-line)))
14767 (goto-char beg)
14768 (setq l1 (org-current-line))
14769 (loop for l from l1 to l2 do
14770 (org-goto-line l)
14771 (setq m (get-text-property (point) 'org-hd-marker))
14772 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14773 (and agendap m))
14774 (setq buf (if agendap (marker-buffer m) (current-buffer))
14775 pos (if agendap m (point)))
14776 (with-current-buffer buf
14777 (save-excursion
14778 (save-restriction
14779 (goto-char pos)
14780 (setq cnt (1+ cnt))
14781 (org-toggle-tag tag (if off 'off 'on))
14782 (setq newhead (org-get-heading)))))
14783 (and agendap (org-agenda-change-all-lines newhead m))))
14784 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14786 (defun org-tags-completion-function (string predicate &optional flag)
14787 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14788 (confirm (lambda (x) (stringp (car x)))))
14789 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14790 (setq s1 (match-string 1 string)
14791 s2 (match-string 2 string))
14792 (setq s1 "" s2 string))
14793 (cond
14794 ((eq flag nil)
14795 ;; try completion
14796 (setq rtn (try-completion s2 ctable confirm))
14797 (if (stringp rtn)
14798 (setq rtn
14799 (concat s1 s2 (substring rtn (length s2))
14800 (if (and org-add-colon-after-tag-completion
14801 (assoc rtn ctable))
14802 ":" ""))))
14803 rtn)
14804 ((eq flag t)
14805 ;; all-completions
14806 (all-completions s2 ctable confirm))
14807 ((eq flag 'lambda)
14808 ;; exact match?
14809 (assoc s2 ctable)))))
14811 (defun org-fast-tag-insert (kwd tags face &optional end)
14812 "Insert KDW, and the TAGS, the latter with face FACE.
14813 Also insert END."
14814 (insert (format "%-12s" (concat kwd ":"))
14815 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14816 (or end "")))
14818 (defun org-fast-tag-show-exit (flag)
14819 (save-excursion
14820 (org-goto-line 3)
14821 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14822 (replace-match ""))
14823 (when flag
14824 (end-of-line 1)
14825 (org-move-to-column (- (window-width) 19) t)
14826 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14828 (defun org-set-current-tags-overlay (current prefix)
14829 "Add an overlay to CURRENT tag with PREFIX."
14830 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14831 (if (featurep 'xemacs)
14832 (org-overlay-display org-tags-overlay (concat prefix s)
14833 'secondary-selection)
14834 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14835 (org-overlay-display org-tags-overlay (concat prefix s)))))
14837 (defvar org-last-tag-selection-key nil)
14838 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14839 "Fast tag selection with single keys.
14840 CURRENT is the current list of tags in the headline, INHERITED is the
14841 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14842 possibly with grouping information. TODO-TABLE is a similar table with
14843 TODO keywords, should these have keys assigned to them.
14844 If the keys are nil, a-z are automatically assigned.
14845 Returns the new tags string, or nil to not change the current settings."
14846 (let* ((fulltable (append table todo-table))
14847 (maxlen (apply 'max (mapcar
14848 (lambda (x)
14849 (if (stringp (car x)) (string-width (car x)) 0))
14850 fulltable)))
14851 (buf (current-buffer))
14852 (expert (eq org-fast-tag-selection-single-key 'expert))
14853 (buffer-tags nil)
14854 (fwidth (+ maxlen 3 1 3))
14855 (ncol (/ (- (window-width) 4) fwidth))
14856 (i-face 'org-done)
14857 (c-face 'org-todo)
14858 tg cnt e c char c1 c2 ntable tbl rtn
14859 ov-start ov-end ov-prefix
14860 (exit-after-next org-fast-tag-selection-single-key)
14861 (done-keywords org-done-keywords)
14862 groups ingroup)
14863 (save-excursion
14864 (beginning-of-line 1)
14865 (if (looking-at
14866 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14867 (setq ov-start (match-beginning 1)
14868 ov-end (match-end 1)
14869 ov-prefix "")
14870 (setq ov-start (1- (point-at-eol))
14871 ov-end (1+ ov-start))
14872 (skip-chars-forward "^\n\r")
14873 (setq ov-prefix
14874 (concat
14875 (buffer-substring (1- (point)) (point))
14876 (if (> (current-column) org-tags-column)
14878 (make-string (- org-tags-column (current-column)) ?\ ))))))
14879 (move-overlay org-tags-overlay ov-start ov-end)
14880 (save-window-excursion
14881 (if expert
14882 (set-buffer (get-buffer-create " *Org tags*"))
14883 (delete-other-windows)
14884 (split-window-vertically)
14885 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14886 (erase-buffer)
14887 (org-set-local 'org-done-keywords done-keywords)
14888 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14889 (org-fast-tag-insert "Current" current c-face "\n\n")
14890 (org-fast-tag-show-exit exit-after-next)
14891 (org-set-current-tags-overlay current ov-prefix)
14892 (setq tbl fulltable char ?a cnt 0)
14893 (while (setq e (pop tbl))
14894 (cond
14895 ((equal (car e) :startgroup)
14896 (push '() groups) (setq ingroup t)
14897 (when (not (= cnt 0))
14898 (setq cnt 0)
14899 (insert "\n"))
14900 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14901 ((equal (car e) :endgroup)
14902 (setq ingroup nil cnt 0)
14903 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14904 ((equal e '(:newline))
14905 (when (not (= cnt 0))
14906 (setq cnt 0)
14907 (insert "\n")
14908 (setq e (car tbl))
14909 (while (equal (car tbl) '(:newline))
14910 (insert "\n")
14911 (setq tbl (cdr tbl)))))
14912 ((equal e '(:grouptags)) nil)
14914 (setq tg (copy-sequence (car e)) c2 nil)
14915 (if (cdr e)
14916 (setq c (cdr e))
14917 ;; automatically assign a character.
14918 (setq c1 (string-to-char
14919 (downcase (substring
14920 tg (if (= (string-to-char tg) ?@) 1 0)))))
14921 (if (or (rassoc c1 ntable) (rassoc c1 table))
14922 (while (or (rassoc char ntable) (rassoc char table))
14923 (setq char (1+ char)))
14924 (setq c2 c1))
14925 (setq c (or c2 char)))
14926 (if ingroup (push tg (car groups)))
14927 (setq tg (org-add-props tg nil 'face
14928 (cond
14929 ((not (assoc tg table))
14930 (org-get-todo-face tg))
14931 ((member tg current) c-face)
14932 ((member tg inherited) i-face))))
14933 (if (equal (caar tbl) :grouptags)
14934 (org-add-props tg nil 'face 'org-tag-group))
14935 (if (and (= cnt 0) (not ingroup)) (insert " "))
14936 (insert "[" c "] " tg (make-string
14937 (- fwidth 4 (length tg)) ?\ ))
14938 (push (cons tg c) ntable)
14939 (when (= (setq cnt (1+ cnt)) ncol)
14940 (insert "\n")
14941 (if ingroup (insert " "))
14942 (setq cnt 0)))))
14943 (setq ntable (nreverse ntable))
14944 (insert "\n")
14945 (goto-char (point-min))
14946 (if (not expert) (org-fit-window-to-buffer))
14947 (setq rtn
14948 (catch 'exit
14949 (while t
14950 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14951 (if (not groups) "no " "")
14952 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14953 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14954 (setq org-last-tag-selection-key c)
14955 (cond
14956 ((= c ?\r) (throw 'exit t))
14957 ((= c ?!)
14958 (setq groups (not groups))
14959 (goto-char (point-min))
14960 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14961 ((= c ?\C-c)
14962 (if (not expert)
14963 (org-fast-tag-show-exit
14964 (setq exit-after-next (not exit-after-next)))
14965 (setq expert nil)
14966 (delete-other-windows)
14967 (set-window-buffer (split-window-vertically) " *Org tags*")
14968 (org-switch-to-buffer-other-window " *Org tags*")
14969 (org-fit-window-to-buffer)))
14970 ((or (= c ?\C-g)
14971 (and (= c ?q) (not (rassoc c ntable))))
14972 (org-detach-overlay org-tags-overlay)
14973 (setq quit-flag t))
14974 ((= c ?\ )
14975 (setq current nil)
14976 (if exit-after-next (setq exit-after-next 'now)))
14977 ((= c ?\t)
14978 (condition-case nil
14979 (setq tg (org-icompleting-read
14980 "Tag: "
14981 (or buffer-tags
14982 (with-current-buffer buf
14983 (org-get-buffer-tags)))))
14984 (quit (setq tg "")))
14985 (when (string-match "\\S-" tg)
14986 (add-to-list 'buffer-tags (list tg))
14987 (if (member tg current)
14988 (setq current (delete tg current))
14989 (push tg current)))
14990 (if exit-after-next (setq exit-after-next 'now)))
14991 ((setq e (rassoc c todo-table) tg (car e))
14992 (with-current-buffer buf
14993 (save-excursion (org-todo tg)))
14994 (if exit-after-next (setq exit-after-next 'now)))
14995 ((setq e (rassoc c ntable) tg (car e))
14996 (if (member tg current)
14997 (setq current (delete tg current))
14998 (loop for g in groups do
14999 (if (member tg g)
15000 (mapc (lambda (x)
15001 (setq current (delete x current)))
15002 g)))
15003 (push tg current))
15004 (if exit-after-next (setq exit-after-next 'now))))
15006 ;; Create a sorted list
15007 (setq current
15008 (sort current
15009 (lambda (a b)
15010 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15011 (if (eq exit-after-next 'now) (throw 'exit t))
15012 (goto-char (point-min))
15013 (beginning-of-line 2)
15014 (delete-region (point) (point-at-eol))
15015 (org-fast-tag-insert "Current" current c-face)
15016 (org-set-current-tags-overlay current ov-prefix)
15017 (while (re-search-forward
15018 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15019 (setq tg (match-string 1))
15020 (add-text-properties
15021 (match-beginning 1) (match-end 1)
15022 (list 'face
15023 (cond
15024 ((member tg current) c-face)
15025 ((member tg inherited) i-face)
15026 (t (get-text-property (match-beginning 1) 'face))))))
15027 (goto-char (point-min)))))
15028 (org-detach-overlay org-tags-overlay)
15029 (if rtn
15030 (mapconcat 'identity current ":")
15031 nil))))
15033 (defun org-get-tags-string ()
15034 "Get the TAGS string in the current headline."
15035 (unless (org-at-heading-p t)
15036 (user-error "Not on a heading"))
15037 (save-excursion
15038 (beginning-of-line 1)
15039 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15040 (org-match-string-no-properties 1)
15041 "")))
15043 (defun org-get-tags ()
15044 "Get the list of tags specified in the current headline."
15045 (org-split-string (org-get-tags-string) ":"))
15047 (defun org-get-buffer-tags ()
15048 "Get a table of all tags used in the buffer, for completion."
15049 (let (tags)
15050 (save-excursion
15051 (goto-char (point-min))
15052 (while (re-search-forward
15053 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15054 (when (equal (char-after (point-at-bol 0)) ?*)
15055 (mapc (lambda (x) (add-to-list 'tags x))
15056 (org-split-string (org-match-string-no-properties 1) ":")))))
15057 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15058 (mapcar 'list tags)))
15060 ;;;; The mapping API
15062 (defun org-map-entries (func &optional match scope &rest skip)
15063 "Call FUNC at each headline selected by MATCH in SCOPE.
15065 FUNC is a function or a lisp form. The function will be called without
15066 arguments, with the cursor positioned at the beginning of the headline.
15067 The return values of all calls to the function will be collected and
15068 returned as a list.
15070 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15071 does not need to preserve point. After evaluation, the cursor will be
15072 moved to the end of the line (presumably of the headline of the
15073 processed entry) and search continues from there. Under some
15074 circumstances, this may not produce the wanted results. For example,
15075 if you have removed (e.g. archived) the current (sub)tree it could
15076 mean that the next entry will be skipped entirely. In such cases, you
15077 can specify the position from where search should continue by making
15078 FUNC set the variable `org-map-continue-from' to the desired buffer
15079 position.
15081 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15082 Only headlines that are matched by this query will be considered during
15083 the iteration. When MATCH is nil or t, all headlines will be
15084 visited by the iteration.
15086 SCOPE determines the scope of this command. It can be any of:
15088 nil The current buffer, respecting the restriction if any
15089 tree The subtree started with the entry at point
15090 region The entries within the active region, if any
15091 region-start-level
15092 The entries within the active region, but only those at
15093 the same level than the first one.
15094 file The current buffer, without restriction
15095 file-with-archives
15096 The current buffer, and any archives associated with it
15097 agenda All agenda files
15098 agenda-with-archives
15099 All agenda files with any archive files associated with them
15100 \(file1 file2 ...)
15101 If this is a list, all files in the list will be scanned
15103 The remaining args are treated as settings for the skipping facilities of
15104 the scanner. The following items can be given here:
15106 archive skip trees with the archive tag
15107 comment skip trees with the COMMENT keyword
15108 function or Emacs Lisp form:
15109 will be used as value for `org-agenda-skip-function', so
15110 whenever the function returns a position, FUNC will not be
15111 called for that entry and search will continue from the
15112 position returned
15114 If your function needs to retrieve the tags including inherited tags
15115 at the *current* entry, you can use the value of the variable
15116 `org-scanner-tags' which will be much faster than getting the value
15117 with `org-get-tags-at'. If your function gets properties with
15118 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15119 to t around the call to `org-entry-properties' to get the same speedup.
15120 Note that if your function moves around to retrieve tags and properties at
15121 a *different* entry, you cannot use these techniques."
15122 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15123 (not (org-region-active-p)))
15124 (let* ((org-agenda-archives-mode nil) ; just to make sure
15125 (org-agenda-skip-archived-trees (memq 'archive skip))
15126 (org-agenda-skip-comment-trees (memq 'comment skip))
15127 (org-agenda-skip-function
15128 (car (org-delete-all '(comment archive) skip)))
15129 (org-tags-match-list-sublevels t)
15130 (start-level (eq scope 'region-start-level))
15131 matcher file res
15132 org-todo-keywords-for-agenda
15133 org-done-keywords-for-agenda
15134 org-todo-keyword-alist-for-agenda
15135 org-tag-alist-for-agenda
15136 todo-only)
15138 (cond
15139 ((eq match t) (setq matcher t))
15140 ((eq match nil) (setq matcher t))
15141 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15143 (save-excursion
15144 (save-restriction
15145 (cond ((eq scope 'tree)
15146 (org-back-to-heading t)
15147 (org-narrow-to-subtree)
15148 (setq scope nil))
15149 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15150 (org-region-active-p))
15151 ;; If needed, set start-level to a string like "2"
15152 (when start-level
15153 (save-excursion
15154 (goto-char (region-beginning))
15155 (unless (org-at-heading-p) (outline-next-heading))
15156 (setq start-level (org-current-level))))
15157 (narrow-to-region (region-beginning)
15158 (save-excursion
15159 (goto-char (region-end))
15160 (unless (and (bolp) (org-at-heading-p))
15161 (outline-next-heading))
15162 (point)))
15163 (setq scope nil)))
15165 (if (not scope)
15166 (progn
15167 (org-agenda-prepare-buffers
15168 (list (buffer-file-name (current-buffer))))
15169 (setq res (org-scan-tags func matcher todo-only start-level)))
15170 ;; Get the right scope
15171 (cond
15172 ((and scope (listp scope) (symbolp (car scope)))
15173 (setq scope (eval scope)))
15174 ((eq scope 'agenda)
15175 (setq scope (org-agenda-files t)))
15176 ((eq scope 'agenda-with-archives)
15177 (setq scope (org-agenda-files t))
15178 (setq scope (org-add-archive-files scope)))
15179 ((eq scope 'file)
15180 (setq scope (list (buffer-file-name))))
15181 ((eq scope 'file-with-archives)
15182 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15183 (org-agenda-prepare-buffers scope)
15184 (while (setq file (pop scope))
15185 (with-current-buffer (org-find-base-buffer-visiting file)
15186 (save-excursion
15187 (save-restriction
15188 (widen)
15189 (goto-char (point-min))
15190 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15191 res)))
15193 ;;;; Properties
15195 ;;; Setting and retrieving properties
15197 (defconst org-special-properties
15198 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15199 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15200 "The special properties valid in Org-mode.
15202 These are properties that are not defined in the property drawer,
15203 but in some other way.")
15205 (defconst org-default-properties
15206 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15207 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15208 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15209 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15210 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15211 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15212 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15213 "Some properties that are used by Org-mode for various purposes.
15214 Being in this list makes sure that they are offered for completion.")
15216 (defun org-property-action ()
15217 "Do an action on properties."
15218 (interactive)
15219 (let (c)
15220 (org-at-property-p)
15221 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15222 (setq c (read-char-exclusive))
15223 (cond
15224 ((equal c ?s)
15225 (call-interactively 'org-set-property))
15226 ((equal c ?d)
15227 (call-interactively 'org-delete-property))
15228 ((equal c ?D)
15229 (call-interactively 'org-delete-property-globally))
15230 ((equal c ?c)
15231 (call-interactively 'org-compute-property-at-point))
15232 (t (user-error "No such property action %c" c)))))
15234 (defun org-inc-effort ()
15235 "Increment the value of the effort property in the current entry."
15236 (interactive)
15237 (org-set-effort nil t))
15239 (defvar org-clock-effort) ;; Defined in org-clock.el
15240 (defvar org-clock-current-task) ;; Defined in org-clock.el
15241 (defun org-set-effort (&optional value increment)
15242 "Set the effort property of the current entry.
15243 With numerical prefix arg, use the nth allowed value, 0 stands for the
15244 10th allowed value.
15246 When INCREMENT is non-nil, set the property to the next allowed value."
15247 (interactive "P")
15248 (if (equal value 0) (setq value 10))
15249 (let* ((completion-ignore-case t)
15250 (prop org-effort-property)
15251 (cur (org-entry-get nil prop))
15252 (allowed (org-property-get-allowed-values nil prop 'table))
15253 (existing (mapcar 'list (org-property-values prop)))
15254 (heading (nth 4 (org-heading-components)))
15256 (val (cond
15257 ((stringp value) value)
15258 ((and allowed (integerp value))
15259 (or (car (nth (1- value) allowed))
15260 (car (org-last allowed))))
15261 ((and allowed increment)
15262 (or (caadr (member (list cur) allowed))
15263 (user-error "Allowed effort values are not set")))
15264 (allowed
15265 (message "Select 1-9,0, [RET%s]: %s"
15266 (if cur (concat "=" cur) "")
15267 (mapconcat 'car allowed " "))
15268 (setq rpl (read-char-exclusive))
15269 (if (equal rpl ?\r)
15271 (setq rpl (- rpl ?0))
15272 (if (equal rpl 0) (setq rpl 10))
15273 (if (and (> rpl 0) (<= rpl (length allowed)))
15274 (car (nth (1- rpl) allowed))
15275 (org-completing-read "Effort: " allowed nil))))
15277 (let (org-completion-use-ido org-completion-use-iswitchb)
15278 (org-completing-read
15279 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15280 (concat "[" cur "]") "")
15281 ": ")
15282 existing nil nil "" nil cur))))))
15283 (unless (equal (org-entry-get nil prop) val)
15284 (org-entry-put nil prop val))
15285 (save-excursion
15286 (org-back-to-heading t)
15287 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15288 (when (string= heading org-clock-current-task)
15289 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15290 (org-clock-update-mode-line))
15291 (message "%s is now %s" prop val)))
15293 (defun org-at-property-p ()
15294 "Is cursor inside a property drawer?"
15295 (save-excursion
15296 (when (equal 'node-property (car (org-element-at-point)))
15297 (beginning-of-line 1)
15298 (looking-at org-property-re))))
15300 (defun org-get-property-block (&optional beg end force)
15301 "Return the (beg . end) range of the body of the property drawer.
15302 BEG and END are the beginning and end of the current subtree, or of
15303 the part before the first headline. If they are not given, they will
15304 be found. If the drawer does not exist and FORCE is non-nil, create
15305 the drawer."
15306 (catch 'exit
15307 (save-excursion
15308 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15309 (progn (org-back-to-heading t) (point))))
15310 (end (or end (and (not (outline-next-heading)) (point-max))
15311 (point))))
15312 (goto-char beg)
15313 (if (re-search-forward org-property-start-re end t)
15314 (setq beg (1+ (match-end 0)))
15315 (if force
15316 (save-excursion
15317 (org-insert-property-drawer)
15318 (setq end (progn (outline-next-heading) (point))))
15319 (throw 'exit nil))
15320 (goto-char beg)
15321 (if (re-search-forward org-property-start-re end t)
15322 (setq beg (1+ (match-end 0)))))
15323 (if (re-search-forward org-property-end-re end t)
15324 (setq end (match-beginning 0))
15325 (or force (throw 'exit nil))
15326 (goto-char beg)
15327 (setq end beg)
15328 (org-indent-line)
15329 (insert ":END:\n"))
15330 (cons beg end)))))
15332 (defun org-entry-properties (&optional pom which specific)
15333 "Get all properties of the entry at point-or-marker POM.
15334 This includes the TODO keyword, the tags, time strings for deadline,
15335 scheduled, and clocking, and any additional properties defined in the
15336 entry. The return value is an alist, keys may occur multiple times
15337 if the property key was used several times.
15338 POM may also be nil, in which case the current entry is used.
15339 If WHICH is nil or `all', get all properties. If WHICH is
15340 `special' or `standard', only get that subclass. If WHICH
15341 is a string only get exactly this property. SPECIFIC can be a string, the
15342 specific property we are interested in. Specifying it can speed
15343 things up because then unnecessary parsing is avoided."
15344 (setq which (or which 'all))
15345 (org-with-wide-buffer
15346 (org-with-point-at pom
15347 (let ((clockstr (substring org-clock-string 0 -1))
15348 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15349 (case-fold-search nil)
15350 beg end range props sum-props key key1 value string clocksum clocksumt)
15351 (when (and (derived-mode-p 'org-mode)
15352 (ignore-errors (org-back-to-heading t)))
15353 (setq beg (point))
15354 (setq sum-props (get-text-property (point) 'org-summaries))
15355 (setq clocksum (get-text-property (point) :org-clock-minutes)
15356 clocksumt (get-text-property (point) :org-clock-minutes-today))
15357 (outline-next-heading)
15358 (setq end (point))
15359 (when (memq which '(all special))
15360 ;; Get the special properties, like TODO and tags
15361 (goto-char beg)
15362 (when (and (or (not specific) (string= specific "TODO"))
15363 (looking-at org-todo-line-regexp) (match-end 2))
15364 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15365 (when (and (or (not specific) (string= specific "PRIORITY"))
15366 (looking-at org-priority-regexp))
15367 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15368 (when (or (not specific) (string= specific "FILE"))
15369 (push (cons "FILE" buffer-file-name) props))
15370 (when (and (or (not specific) (string= specific "TAGS"))
15371 (setq value (org-get-tags-string))
15372 (string-match "\\S-" value))
15373 (push (cons "TAGS" value) props))
15374 (when (and (or (not specific) (string= specific "ALLTAGS"))
15375 (setq value (org-get-tags-at)))
15376 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15377 ":"))
15378 props))
15379 (when (or (not specific) (string= specific "BLOCKED"))
15380 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15381 (when (or (not specific)
15382 (member specific
15383 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15384 "TIMESTAMP" "TIMESTAMP_IA")))
15385 (catch 'match
15386 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15387 (setq key (if (match-end 1)
15388 (substring (org-match-string-no-properties 1)
15389 0 -1))
15390 string (if (equal key clockstr)
15391 (org-trim
15392 (buffer-substring-no-properties
15393 (match-beginning 3) (goto-char
15394 (point-at-eol))))
15395 (substring (org-match-string-no-properties 3)
15396 1 -1)))
15397 ;; Get the correct property name from the key. This is
15398 ;; necessary if the user has configured time keywords.
15399 (setq key1 (concat key ":"))
15400 (cond
15401 ((not key)
15402 (setq key
15403 (if (= (char-after (match-beginning 3)) ?\[)
15404 "TIMESTAMP_IA" "TIMESTAMP")))
15405 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15406 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15407 ((equal key1 org-closed-string) (setq key "CLOSED"))
15408 ((equal key1 org-clock-string) (setq key "CLOCK")))
15409 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15410 (progn
15411 (push (cons key string) props)
15412 ;; no need to search further if match is found
15413 (throw 'match t))
15414 (when (or (equal key "CLOCK") (not (assoc key props)))
15415 (push (cons key string) props)))))))
15417 (when (memq which '(all standard))
15418 ;; Get the standard properties, like :PROP: ...
15419 (setq range (org-get-property-block beg end))
15420 (when range
15421 (goto-char (car range))
15422 (while (re-search-forward org-property-re
15423 (cdr range) t)
15424 (setq key (org-match-string-no-properties 2)
15425 value (org-trim (or (org-match-string-no-properties 3) "")))
15426 (unless (member key excluded)
15427 (push (cons key (or value "")) props)))))
15428 (if clocksum
15429 (push (cons "CLOCKSUM"
15430 (org-columns-number-to-string (/ (float clocksum) 60.)
15431 'add_times))
15432 props))
15433 (if clocksumt
15434 (push (cons "CLOCKSUM_T"
15435 (org-columns-number-to-string (/ (float clocksumt) 60.)
15436 'add_times))
15437 props))
15438 (unless (assoc "CATEGORY" props)
15439 (push (cons "CATEGORY" (org-get-category)) props))
15440 (append sum-props (nreverse props)))))))
15442 (defun org-entry-get (pom property &optional inherit literal-nil)
15443 "Get value of PROPERTY for entry or content at point-or-marker POM.
15444 If INHERIT is non-nil and the entry does not have the property,
15445 then also check higher levels of the hierarchy.
15446 If INHERIT is the symbol `selective', use inheritance only if the setting
15447 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15448 If the property is present but empty, the return value is the empty string.
15449 If the property is not present at all, nil is returned.
15451 Return the value as a string.
15453 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15454 do not interpret it as the list atom nil. This is used for inheritance
15455 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15456 (org-with-point-at pom
15457 (if (and inherit (if (eq inherit 'selective)
15458 (org-property-inherit-p property)
15460 (org-entry-get-with-inheritance property literal-nil)
15461 (if (member property org-special-properties)
15462 ;; We need a special property. Use `org-entry-properties'
15463 ;; to retrieve it, but specify the wanted property
15464 (cdr (assoc property (org-entry-properties nil 'special property)))
15465 (org-with-wide-buffer
15466 (let ((range (org-get-property-block)))
15467 (when (and range (not (eq (car range) (cdr range)))
15468 (save-excursion
15469 (goto-char (car range))
15470 (re-search-forward
15471 (concat (org-re-property property) "\\|"
15472 (org-re-property (concat property "+")))
15473 (cdr range) t)))
15474 (let* ((props
15475 (list (or (assoc property org-file-properties)
15476 (assoc property org-global-properties)
15477 (assoc property org-global-properties-fixed))))
15478 (ap (lambda (key)
15479 (when (re-search-forward
15480 (org-re-property key) (cdr range) t)
15481 (setq props
15482 (org-update-property-plist
15484 (if (match-end 3)
15485 (org-match-string-no-properties 3) "")
15486 props)))))
15487 val)
15488 (goto-char (car range))
15489 (funcall ap property)
15490 (goto-char (car range))
15491 (while (funcall ap (concat property "+")))
15492 (setq val (cdr (assoc property props)))
15493 (when val (if literal-nil val (org-not-nil val)))))))))))
15495 (defun org-property-or-variable-value (var &optional inherit)
15496 "Check if there is a property fixing the value of VAR.
15497 If yes, return this value. If not, return the current value of the variable."
15498 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15499 (if (and prop (stringp prop) (string-match "\\S-" prop))
15500 (read prop)
15501 (symbol-value var))))
15503 (defun org-entry-delete (pom property)
15504 "Delete the property PROPERTY from entry at point-or-marker POM."
15505 (unless (member property org-special-properties)
15506 (org-with-point-at pom
15507 (let ((range (org-get-property-block)))
15508 (if (and range
15509 (goto-char (car range))
15510 (re-search-forward
15511 (org-re-property property)
15512 (cdr range) t))
15513 (progn
15514 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15515 (org-remove-empty-drawer-at (car range))
15517 nil)))))
15519 ;; Multi-values properties are properties that contain multiple values
15520 ;; These values are assumed to be single words, separated by whitespace.
15521 (defun org-entry-add-to-multivalued-property (pom property value)
15522 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15523 (let* ((old (org-entry-get pom property))
15524 (values (and old (org-split-string old "[ \t]"))))
15525 (setq value (org-entry-protect-space value))
15526 (unless (member value values)
15527 (setq values (append values (list value)))
15528 (org-entry-put pom property
15529 (mapconcat 'identity values " ")))))
15531 (defun org-entry-remove-from-multivalued-property (pom property value)
15532 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15533 (let* ((old (org-entry-get pom property))
15534 (values (and old (org-split-string old "[ \t]"))))
15535 (setq value (org-entry-protect-space value))
15536 (when (member value values)
15537 (setq values (delete value values))
15538 (org-entry-put pom property
15539 (mapconcat 'identity values " ")))))
15541 (defun org-entry-member-in-multivalued-property (pom property value)
15542 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15543 (let* ((old (org-entry-get pom property))
15544 (values (and old (org-split-string old "[ \t]"))))
15545 (setq value (org-entry-protect-space value))
15546 (member value values)))
15548 (defun org-entry-get-multivalued-property (pom property)
15549 "Return a list of values in a multivalued property."
15550 (let* ((value (org-entry-get pom property))
15551 (values (and value (org-split-string value "[ \t]"))))
15552 (mapcar 'org-entry-restore-space values)))
15554 (defun org-entry-put-multivalued-property (pom property &rest values)
15555 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15556 VALUES should be a list of strings. Spaces will be protected."
15557 (org-entry-put pom property
15558 (mapconcat 'org-entry-protect-space values " "))
15559 (let* ((value (org-entry-get pom property))
15560 (values (and value (org-split-string value "[ \t]"))))
15561 (mapcar 'org-entry-restore-space values)))
15563 (defun org-entry-protect-space (s)
15564 "Protect spaces and newline in string S."
15565 (while (string-match " " s)
15566 (setq s (replace-match "%20" t t s)))
15567 (while (string-match "\n" s)
15568 (setq s (replace-match "%0A" t t s)))
15571 (defun org-entry-restore-space (s)
15572 "Restore spaces and newline in string S."
15573 (while (string-match "%20" s)
15574 (setq s (replace-match " " t t s)))
15575 (while (string-match "%0A" s)
15576 (setq s (replace-match "\n" t t s)))
15579 (defvar org-entry-property-inherited-from (make-marker)
15580 "Marker pointing to the entry from where a property was inherited.
15581 Each call to `org-entry-get-with-inheritance' will set this marker to the
15582 location of the entry where the inheritance search matched. If there was
15583 no match, the marker will point nowhere.
15584 Note that also `org-entry-get' calls this function, if the INHERIT flag
15585 is set.")
15587 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15588 "Get PROPERTY of entry or content at point, search higher levels if needed.
15589 The search will stop at the first ancestor which has the property defined.
15590 If the value found is \"nil\", return nil to show that the property
15591 should be considered as undefined (this is the meaning of nil here).
15592 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15593 (move-marker org-entry-property-inherited-from nil)
15594 (let (tmp)
15595 (save-excursion
15596 (save-restriction
15597 (widen)
15598 (catch 'ex
15599 (while t
15600 (when (setq tmp (org-entry-get nil property nil literal-nil))
15601 (or (ignore-errors (org-back-to-heading t))
15602 (goto-char (point-min)))
15603 (move-marker org-entry-property-inherited-from (point))
15604 (throw 'ex tmp))
15605 (or (ignore-errors (org-up-heading-safe))
15606 (throw 'ex nil))))))
15607 (setq tmp (or tmp
15608 (cdr (assoc property org-file-properties))
15609 (cdr (assoc property org-global-properties))
15610 (cdr (assoc property org-global-properties-fixed))))
15611 (if literal-nil tmp (org-not-nil tmp))))
15613 (defvar org-property-changed-functions nil
15614 "Hook called when the value of a property has changed.
15615 Each hook function should accept two arguments, the name of the property
15616 and the new value.")
15618 (defun org-entry-put (pom property value)
15619 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15620 If the value is `nil', it is converted to the empty string.
15621 If it is not a string, an error is raised."
15622 (cond ((null value) (setq value ""))
15623 ((not (stringp value))
15624 (error "Properties values should be strings.")))
15625 (org-with-point-at pom
15626 (org-back-to-heading t)
15627 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15628 range)
15629 (cond
15630 ((equal property "TODO")
15631 (when (and (string-match "\\S-" value)
15632 (not (member value org-todo-keywords-1)))
15633 (user-error "\"%s\" is not a valid TODO state" value))
15634 (if (or (not value)
15635 (not (string-match "\\S-" value)))
15636 (setq value 'none))
15637 (org-todo value)
15638 (org-set-tags nil 'align))
15639 ((equal property "PRIORITY")
15640 (org-priority (if (and value (string-match "\\S-" value))
15641 (string-to-char value) ?\ ))
15642 (org-set-tags nil 'align))
15643 ((equal property "CLOCKSUM")
15644 (if (not (re-search-forward
15645 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15646 (error "Cannot find a clock log")
15647 (goto-char (- (match-end 1) 2))
15648 (cond
15649 ((eq value 'earlier) (org-timestamp-down))
15650 ((eq value 'later) (org-timestamp-up)))
15651 (org-clock-sum-current-item)))
15652 ((equal property "SCHEDULED")
15653 (if (re-search-forward org-scheduled-time-regexp end t)
15654 (cond
15655 ((eq value 'earlier) (org-timestamp-change -1 'day))
15656 ((eq value 'later) (org-timestamp-change 1 'day))
15657 (t (call-interactively 'org-schedule)))
15658 (call-interactively 'org-schedule)))
15659 ((equal property "DEADLINE")
15660 (if (re-search-forward org-deadline-time-regexp end t)
15661 (cond
15662 ((eq value 'earlier) (org-timestamp-change -1 'day))
15663 ((eq value 'later) (org-timestamp-change 1 'day))
15664 (t (call-interactively 'org-deadline)))
15665 (call-interactively 'org-deadline)))
15666 ((member property org-special-properties)
15667 (error "The %s property can not yet be set with `org-entry-put'"
15668 property))
15669 (t ; a non-special property
15670 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15671 (setq range (org-get-property-block beg end 'force))
15672 (goto-char (car range))
15673 (if (re-search-forward
15674 (org-re-property property) (cdr range) t)
15675 (progn
15676 (delete-region (match-beginning 0) (match-end 0))
15677 (goto-char (match-beginning 0)))
15678 (goto-char (cdr range))
15679 (insert "\n")
15680 (backward-char 1)
15681 (org-indent-line))
15682 (insert ":" property ":")
15683 (and value (insert " " value))
15684 (org-indent-line)))))
15685 (run-hook-with-args 'org-property-changed-functions property value)))
15687 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15688 "Get all property keys in the current buffer.
15689 With INCLUDE-SPECIALS, also list the special properties that reflect things
15690 like tags and TODO state.
15691 With INCLUDE-DEFAULTS, also include properties that has special meaning
15692 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15693 and others.
15694 With INCLUDE-COLUMNS, also include property names given in COLUMN
15695 formats in the current buffer."
15696 (let (rtn range cfmt s p)
15697 (save-excursion
15698 (save-restriction
15699 (widen)
15700 (goto-char (point-min))
15701 (while (re-search-forward org-property-start-re nil t)
15702 (setq range (org-get-property-block))
15703 (goto-char (car range))
15704 (while (re-search-forward org-property-re
15705 (cdr range) t)
15706 (add-to-list 'rtn (org-match-string-no-properties 2)))
15707 (outline-next-heading))))
15709 (when include-specials
15710 (setq rtn (append org-special-properties rtn)))
15712 (when include-defaults
15713 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15714 (add-to-list 'rtn org-effort-property))
15716 (when include-columns
15717 (save-excursion
15718 (save-restriction
15719 (widen)
15720 (goto-char (point-min))
15721 (while (re-search-forward
15722 "^[ \t]*\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15723 nil t)
15724 (setq cfmt (match-string 2) s 0)
15725 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15726 cfmt s)
15727 (setq s (match-end 0)
15728 p (match-string 1 cfmt))
15729 (unless (or (equal p "ITEM")
15730 (member p org-special-properties))
15731 (add-to-list 'rtn (match-string 1 cfmt))))))))
15733 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15735 (defun org-property-values (key)
15736 "Return a list of all values of property KEY in the current buffer."
15737 (save-excursion
15738 (save-restriction
15739 (widen)
15740 (goto-char (point-min))
15741 (let ((re (org-re-property key))
15742 values)
15743 (while (re-search-forward re nil t)
15744 (add-to-list 'values (org-trim (match-string 3))))
15745 (delete "" values)))))
15747 (defun org-insert-property-drawer ()
15748 "Insert a property drawer into the current entry."
15749 (org-back-to-heading t)
15750 (looking-at org-outline-regexp)
15751 (let ((indent (if org-adapt-indentation
15752 (- (match-end 0) (match-beginning 0))
15754 (beg (point))
15755 (re (concat "^[ \t]*" org-keyword-time-regexp))
15756 end hiddenp)
15757 (outline-next-heading)
15758 (setq end (point))
15759 (goto-char beg)
15760 (while (re-search-forward re end t))
15761 (setq hiddenp (outline-invisible-p))
15762 (end-of-line 1)
15763 (and (equal (char-after) ?\n) (forward-char 1))
15764 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15765 (if (member (match-string 1) '("CLOCK:" ":END:"))
15766 ;; just skip this line
15767 (beginning-of-line 2)
15768 ;; Drawer start, find the end
15769 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15770 (beginning-of-line 1)))
15771 (org-skip-over-state-notes)
15772 (skip-chars-backward " \t\n\r")
15773 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15774 (forward-char 1))
15775 (goto-char (point-at-eol))
15776 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15777 (beginning-of-line 0)
15778 (org-indent-to-column indent)
15779 (beginning-of-line 2)
15780 (org-indent-to-column indent)
15781 (beginning-of-line 0)
15782 (if hiddenp
15783 (save-excursion
15784 (org-back-to-heading t)
15785 (hide-entry))
15786 (org-flag-drawer t))))
15788 (defun org-insert-drawer (&optional arg drawer)
15789 "Insert a drawer at point.
15791 Optional argument DRAWER, when non-nil, is a string representing
15792 drawer's name. Otherwise, the user is prompted for a name.
15794 If a region is active, insert the drawer around that region
15795 instead.
15797 Point is left between drawer's boundaries."
15798 (interactive "P")
15799 (let* ((drawer (if arg "PROPERTIES"
15800 (or drawer (read-from-minibuffer "Drawer: ")))))
15801 (cond
15802 ;; With C-u, fall back on `org-insert-property-drawer'
15803 (arg (org-insert-property-drawer))
15805 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15806 (user-error "Invalid drawer name"))
15807 ;; With an active region, insert a drawer at point.
15808 ((not (org-region-active-p))
15809 (progn
15810 (unless (bolp) (insert "\n"))
15811 (insert (format ":%s:\n\n:END:\n" drawer))
15812 (forward-line -2)))
15813 ;; Otherwise, insert the drawer at point
15815 (let ((rbeg (region-beginning))
15816 (rend (copy-marker (region-end))))
15817 (unwind-protect
15818 (progn
15819 (goto-char rbeg)
15820 (beginning-of-line)
15821 (when (save-excursion
15822 (re-search-forward org-outline-regexp-bol rend t))
15823 (user-error "Drawers cannot contain headlines"))
15824 ;; Position point at the beginning of the first
15825 ;; non-blank line in region. Insert drawer's opening
15826 ;; there, then indent it.
15827 (org-skip-whitespace)
15828 (beginning-of-line)
15829 (insert ":" drawer ":\n")
15830 (forward-line -1)
15831 (indent-for-tab-command)
15832 ;; Move point to the beginning of the first blank line
15833 ;; after the last non-blank line in region. Insert
15834 ;; drawer's closing, then indent it.
15835 (goto-char rend)
15836 (skip-chars-backward " \r\t\n")
15837 (insert "\n:END:")
15838 (deactivate-mark t)
15839 (indent-for-tab-command)
15840 (unless (eolp) (insert "\n")))
15841 ;; Clear marker, whatever the outcome of insertion is.
15842 (set-marker rend nil)))))))
15844 (defvar org-property-set-functions-alist nil
15845 "Property set function alist.
15846 Each entry should have the following format:
15848 (PROPERTY . READ-FUNCTION)
15850 The read function will be called with the same argument as
15851 `org-completing-read'.")
15853 (defun org-set-property-function (property)
15854 "Get the function that should be used to set PROPERTY.
15855 This is computed according to `org-property-set-functions-alist'."
15856 (or (cdr (assoc property org-property-set-functions-alist))
15857 'org-completing-read))
15859 (defun org-read-property-value (property)
15860 "Read PROPERTY value from user."
15861 (let* ((completion-ignore-case t)
15862 (allowed (org-property-get-allowed-values nil property 'table))
15863 (cur (org-entry-get nil property))
15864 (prompt (concat property " value"
15865 (if (and cur (string-match "\\S-" cur))
15866 (concat " [" cur "]") "") ": "))
15867 (set-function (org-set-property-function property))
15868 (val (if allowed
15869 (funcall set-function prompt allowed nil
15870 (not (get-text-property 0 'org-unrestricted
15871 (caar allowed))))
15872 (let (org-completion-use-ido org-completion-use-iswitchb)
15873 (funcall set-function prompt
15874 (mapcar 'list (org-property-values property))
15875 nil nil "" nil cur)))))
15876 (if (equal val "")
15878 val)))
15880 (defvar org-last-set-property nil)
15881 (defvar org-last-set-property-value nil)
15882 (defun org-read-property-name ()
15883 "Read a property name."
15884 (let* ((completion-ignore-case t)
15885 (keys (org-buffer-property-keys nil t t))
15886 (default-prop (or (save-excursion
15887 (save-match-data
15888 (beginning-of-line)
15889 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15890 (null (string= (match-string 1) "END"))
15891 (match-string 1))))
15892 org-last-set-property))
15893 (property (org-icompleting-read
15894 (concat "Property"
15895 (if default-prop (concat " [" default-prop "]") "")
15896 ": ")
15897 (mapcar 'list keys)
15898 nil nil nil nil
15899 default-prop)))
15900 (if (member property keys)
15901 property
15902 (or (cdr (assoc (downcase property)
15903 (mapcar (lambda (x) (cons (downcase x) x))
15904 keys)))
15905 property))))
15907 (defun org-set-property-and-value (use-last)
15908 "Allow to set [PROPERTY]: [value] direction from prompt.
15909 When use-default, don't even ask, just use the last
15910 \"[PROPERTY]: [value]\" string from the history."
15911 (interactive "P")
15912 (let* ((completion-ignore-case t)
15913 (pv (or (and use-last org-last-set-property-value)
15914 (org-completing-read
15915 "Enter a \"[Property]: [value]\" pair: "
15916 nil nil nil nil nil
15917 org-last-set-property-value)))
15918 prop val)
15919 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15920 (setq prop (match-string 1 pv)
15921 val (match-string 2 pv))
15922 (org-set-property prop val))))
15924 (defun org-set-property (property value)
15925 "In the current entry, set PROPERTY to VALUE.
15926 When called interactively, this will prompt for a property name, offering
15927 completion on existing and default properties. And then it will prompt
15928 for a value, offering completion either on allowed values (via an inherited
15929 xxx_ALL property) or on existing values in other instances of this property
15930 in the current file."
15931 (interactive (list nil nil))
15932 (let* ((property (or property (org-read-property-name)))
15933 (value (or value (org-read-property-value property)))
15934 (fn (cdr (assoc property org-properties-postprocess-alist))))
15935 (setq org-last-set-property property)
15936 (setq org-last-set-property-value (concat property ": " value))
15937 ;; Possibly postprocess the inserted value:
15938 (when fn (setq value (funcall fn value)))
15939 (unless (equal (org-entry-get nil property) value)
15940 (org-entry-put nil property value))))
15942 (defun org-delete-property (property)
15943 "In the current entry, delete PROPERTY."
15944 (interactive
15945 (let* ((completion-ignore-case t)
15946 (cat (org-entry-get (point) "CATEGORY"))
15947 (props0 (org-entry-properties nil 'standard))
15948 (props (if cat props0
15949 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15950 (prop (if (< 1 (length props))
15951 (org-icompleting-read "Property: " props nil t)
15952 (caar props))))
15953 (list prop)))
15954 (if (org-entry-delete nil property)
15955 (message "Property %s deleted" property)))
15957 (defun org-delete-property-globally (property)
15958 "Remove PROPERTY globally, from all entries."
15959 (interactive
15960 (let* ((completion-ignore-case t)
15961 (prop (org-icompleting-read
15962 "Globally remove property: "
15963 (mapcar 'list (org-buffer-property-keys)))))
15964 (list prop)))
15965 (save-excursion
15966 (save-restriction
15967 (widen)
15968 (goto-char (point-min))
15969 (let ((cnt 0))
15970 (while (re-search-forward
15971 (org-re-property property)
15972 nil t)
15973 (setq cnt (1+ cnt))
15974 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15975 (message "Property \"%s\" removed from %d entries" property cnt)))))
15977 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15979 (defun org-compute-property-at-point ()
15980 "Compute the property at point.
15981 This looks for an enclosing column format, extracts the operator and
15982 then applies it to the property in the column format's scope."
15983 (interactive)
15984 (unless (org-at-property-p)
15985 (user-error "Not at a property"))
15986 (let ((prop (org-match-string-no-properties 2)))
15987 (org-columns-get-format-and-top-level)
15988 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15989 (user-error "No operator defined for property %s" prop))
15990 (org-columns-compute prop)))
15992 (defvar org-property-allowed-value-functions nil
15993 "Hook for functions supplying allowed values for a specific property.
15994 The functions must take a single argument, the name of the property, and
15995 return a flat list of allowed values. If \":ETC\" is one of
15996 the values, this means that these values are intended as defaults for
15997 completion, but that other values should be allowed too.
15998 The functions must return nil if they are not responsible for this
15999 property.")
16001 (defun org-property-get-allowed-values (pom property &optional table)
16002 "Get allowed values for the property PROPERTY.
16003 When TABLE is non-nil, return an alist that can directly be used for
16004 completion."
16005 (let (vals)
16006 (cond
16007 ((equal property "TODO")
16008 (setq vals (org-with-point-at pom
16009 (append org-todo-keywords-1 '("")))))
16010 ((equal property "PRIORITY")
16011 (let ((n org-lowest-priority))
16012 (while (>= n org-highest-priority)
16013 (push (char-to-string n) vals)
16014 (setq n (1- n)))))
16015 ((member property org-special-properties))
16016 ((setq vals (run-hook-with-args-until-success
16017 'org-property-allowed-value-functions property)))
16019 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16020 (when (and vals (string-match "\\S-" vals))
16021 (setq vals (car (read-from-string (concat "(" vals ")"))))
16022 (setq vals (mapcar (lambda (x)
16023 (cond ((stringp x) x)
16024 ((numberp x) (number-to-string x))
16025 ((symbolp x) (symbol-name x))
16026 (t "???")))
16027 vals)))))
16028 (when (member ":ETC" vals)
16029 (setq vals (remove ":ETC" vals))
16030 (org-add-props (car vals) '(org-unrestricted t)))
16031 (if table (mapcar 'list vals) vals)))
16033 (defun org-property-previous-allowed-value (&optional previous)
16034 "Switch to the next allowed value for this property."
16035 (interactive)
16036 (org-property-next-allowed-value t))
16038 (defun org-property-next-allowed-value (&optional previous)
16039 "Switch to the next allowed value for this property."
16040 (interactive)
16041 (unless (org-at-property-p)
16042 (user-error "Not at a property"))
16043 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16044 (key (match-string 2))
16045 (value (match-string 3))
16046 (allowed (or (org-property-get-allowed-values (point) key)
16047 (and (member value '("[ ]" "[-]" "[X]"))
16048 '("[ ]" "[X]"))))
16049 (heading (save-match-data (nth 4 (org-heading-components))))
16050 nval)
16051 (unless allowed
16052 (user-error "Allowed values for this property have not been defined"))
16053 (if previous (setq allowed (reverse allowed)))
16054 (if (member value allowed)
16055 (setq nval (car (cdr (member value allowed)))))
16056 (setq nval (or nval (car allowed)))
16057 (if (equal nval value)
16058 (user-error "Only one allowed value for this property"))
16059 (org-at-property-p)
16060 (replace-match (concat " :" key ": " nval) t t)
16061 (org-indent-line)
16062 (beginning-of-line 1)
16063 (skip-chars-forward " \t")
16064 (when (equal prop org-effort-property)
16065 (save-excursion
16066 (org-back-to-heading t)
16067 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
16068 (when (string= org-clock-current-task heading)
16069 (setq org-clock-effort nval)
16070 (org-clock-update-mode-line)))
16071 (run-hook-with-args 'org-property-changed-functions key nval)))
16073 (defun org-find-olp (path &optional this-buffer)
16074 "Return a marker pointing to the entry at outline path OLP.
16075 If anything goes wrong, throw an error.
16076 You can wrap this call to catch the error like this:
16078 (condition-case msg
16079 (org-mobile-locate-entry (match-string 4))
16080 (error (nth 1 msg)))
16082 The return value will then be either a string with the error message,
16083 or a marker if everything is OK.
16085 If THIS-BUFFER is set, the outline path does not contain a file,
16086 only headings."
16087 (let* ((file (if this-buffer buffer-file-name (pop path)))
16088 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16089 (level 1)
16090 (lmin 1)
16091 (lmax 1)
16092 limit re end found pos heading cnt flevel)
16093 (unless buffer (error "File not found :%s" file))
16094 (with-current-buffer buffer
16095 (save-excursion
16096 (save-restriction
16097 (widen)
16098 (setq limit (point-max))
16099 (goto-char (point-min))
16100 (while (setq heading (pop path))
16101 (setq re (format org-complex-heading-regexp-format
16102 (regexp-quote heading)))
16103 (setq cnt 0 pos (point))
16104 (while (re-search-forward re end t)
16105 (setq level (- (match-end 1) (match-beginning 1)))
16106 (if (and (>= level lmin) (<= level lmax))
16107 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16108 (when (= cnt 0) (error "Heading not found on level %d: %s"
16109 lmax heading))
16110 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16111 lmax heading))
16112 (goto-char found)
16113 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16114 (setq end (save-excursion (org-end-of-subtree t t))))
16115 (when (org-at-heading-p)
16116 (point-marker)))))))
16118 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16119 "Find node HEADING in BUFFER.
16120 Return a marker to the heading if it was found, or nil if not.
16121 If POS-ONLY is set, return just the position instead of a marker.
16123 The heading text must match exact, but it may have a TODO keyword,
16124 a priority cookie and tags in the standard locations."
16125 (with-current-buffer (or buffer (current-buffer))
16126 (save-excursion
16127 (save-restriction
16128 (widen)
16129 (goto-char (point-min))
16130 (let (case-fold-search)
16131 (if (re-search-forward
16132 (format org-complex-heading-regexp-format
16133 (regexp-quote heading)) nil t)
16134 (if pos-only
16135 (match-beginning 0)
16136 (move-marker (make-marker) (match-beginning 0)))))))))
16138 (defun org-find-exact-heading-in-directory (heading &optional dir)
16139 "Find Org node headline HEADING in all .org files in directory DIR.
16140 When the target headline is found, return a marker to this location."
16141 (let ((files (directory-files (or dir default-directory)
16142 t "\\`[^.#].*\\.org\\'"))
16143 file visiting m buffer)
16144 (catch 'found
16145 (while (setq file (pop files))
16146 (message "trying %s" file)
16147 (setq visiting (org-find-base-buffer-visiting file))
16148 (setq buffer (or visiting (find-file-noselect file)))
16149 (setq m (org-find-exact-headline-in-buffer
16150 heading buffer))
16151 (when (and (not m) (not visiting)) (kill-buffer buffer))
16152 (and m (throw 'found m))))))
16154 (defun org-find-entry-with-id (ident)
16155 "Locate the entry that contains the ID property with exact value IDENT.
16156 IDENT can be a string, a symbol or a number, this function will search for
16157 the string representation of it.
16158 Return the position where this entry starts, or nil if there is no such entry."
16159 (interactive "sID: ")
16160 (let ((id (cond
16161 ((stringp ident) ident)
16162 ((symbol-name ident) (symbol-name ident))
16163 ((numberp ident) (number-to-string ident))
16164 (t (error "IDENT %s must be a string, symbol or number" ident))))
16165 (case-fold-search nil))
16166 (save-excursion
16167 (save-restriction
16168 (widen)
16169 (goto-char (point-min))
16170 (when (re-search-forward
16171 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16172 nil t)
16173 (org-back-to-heading t)
16174 (point))))))
16176 ;;;; Timestamps
16178 (defvar org-last-changed-timestamp nil)
16179 (defvar org-last-inserted-timestamp nil
16180 "The last time stamp inserted with `org-insert-time-stamp'.")
16181 (defvar org-ts-what) ; dynamically scoped parameter
16183 (defun org-time-stamp (arg &optional inactive)
16184 "Prompt for a date/time and insert a time stamp.
16185 If the user specifies a time like HH:MM or if this command is
16186 called with at least one prefix argument, the time stamp contains
16187 the date and the time. Otherwise, only the date is be included.
16189 All parts of a date not specified by the user is filled in from
16190 the current date/time. So if you just press return without
16191 typing anything, the time stamp will represent the current
16192 date/time.
16194 If there is already a timestamp at the cursor, it will be
16195 modified.
16197 With two universal prefix arguments, insert an active timestamp
16198 with the current time without prompting the user.
16200 When called from lisp, the timestamp is inactive if INACTIVE is
16201 non-nil."
16202 (interactive "P")
16203 (let* ((ts nil)
16204 (default-time
16205 ;; Default time is either today, or, when entering a range,
16206 ;; the range start.
16207 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16208 (save-excursion
16209 (re-search-backward
16210 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16211 (- (point) 20) t)))
16212 (apply 'encode-time (org-parse-time-string (match-string 1)))
16213 (current-time)))
16214 (default-input (and ts (org-get-compact-tod ts)))
16215 (repeater (save-excursion
16216 (save-match-data
16217 (beginning-of-line)
16218 (when (re-search-forward
16219 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16220 (save-excursion (progn (end-of-line) (point))) t)
16221 (match-string 0)))))
16222 org-time-was-given org-end-time-was-given time)
16223 (cond
16224 ((and (org-at-timestamp-p t)
16225 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16226 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16227 (insert "--")
16228 (setq time (let ((this-command this-command))
16229 (org-read-date arg 'totime nil nil
16230 default-time default-input inactive)))
16231 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16232 ((org-at-timestamp-p t)
16233 (setq time (let ((this-command this-command))
16234 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16235 (when (org-at-timestamp-p t) ; just to get the match data
16236 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16237 (replace-match "")
16238 (setq org-last-changed-timestamp
16239 (org-insert-time-stamp
16240 time (or org-time-was-given arg)
16241 inactive nil nil (list org-end-time-was-given)))
16242 (when repeater (goto-char (1- (point))) (insert " " repeater)
16243 (setq org-last-changed-timestamp
16244 (concat (substring org-last-inserted-timestamp 0 -1)
16245 " " repeater ">"))))
16246 (message "Timestamp updated"))
16247 ((equal arg '(16))
16248 (org-insert-time-stamp (current-time) t inactive))
16250 (setq time (let ((this-command this-command))
16251 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16252 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16253 nil nil (list org-end-time-was-given))))))
16255 ;; FIXME: can we use this for something else, like computing time differences?
16256 (defun org-get-compact-tod (s)
16257 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16258 (let* ((t1 (match-string 1 s))
16259 (h1 (string-to-number (match-string 2 s)))
16260 (m1 (string-to-number (match-string 3 s)))
16261 (t2 (and (match-end 4) (match-string 5 s)))
16262 (h2 (and t2 (string-to-number (match-string 6 s))))
16263 (m2 (and t2 (string-to-number (match-string 7 s))))
16264 dh dm)
16265 (if (not t2)
16267 (setq dh (- h2 h1) dm (- m2 m1))
16268 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16269 (concat t1 "+" (number-to-string dh)
16270 (and (/= 0 dm) (format ":%02d" dm)))))))
16272 (defun org-time-stamp-inactive (&optional arg)
16273 "Insert an inactive time stamp.
16274 An inactive time stamp is enclosed in square brackets instead of angle
16275 brackets. It is inactive in the sense that it does not trigger agenda entries,
16276 does not link to the calendar and cannot be changed with the S-cursor keys.
16277 So these are more for recording a certain time/date."
16278 (interactive "P")
16279 (org-time-stamp arg 'inactive))
16281 (defvar org-date-ovl (make-overlay 1 1))
16282 (overlay-put org-date-ovl 'face 'org-date-selected)
16283 (org-detach-overlay org-date-ovl)
16285 (defvar org-ans1) ; dynamically scoped parameter
16286 (defvar org-ans2) ; dynamically scoped parameter
16288 (defvar org-plain-time-of-day-regexp) ; defined below
16290 (defvar org-overriding-default-time nil) ; dynamically scoped
16291 (defvar org-read-date-overlay nil)
16292 (defvar org-dcst nil) ; dynamically scoped
16293 (defvar org-read-date-history nil)
16294 (defvar org-read-date-final-answer nil)
16295 (defvar org-read-date-analyze-futurep nil)
16296 (defvar org-read-date-analyze-forced-year nil)
16297 (defvar org-read-date-inactive)
16299 (defvar org-read-date-minibuffer-local-map
16300 (let* ((org-replace-disputed-keys nil)
16301 (map (make-sparse-keymap)))
16302 (set-keymap-parent map minibuffer-local-map)
16303 (org-defkey map (kbd ".")
16304 (lambda () (interactive)
16305 ;; Are we at the beginning of the prompt?
16306 (if (looking-back "^[^:]+: ")
16307 (org-eval-in-calendar '(calendar-goto-today))
16308 (insert "."))))
16309 (org-defkey map (kbd "C-.")
16310 (lambda () (interactive)
16311 (org-eval-in-calendar '(calendar-goto-today))))
16312 (org-defkey map [(meta shift left)]
16313 (lambda () (interactive)
16314 (org-eval-in-calendar '(calendar-backward-month 1))))
16315 (org-defkey map [(meta shift right)]
16316 (lambda () (interactive)
16317 (org-eval-in-calendar '(calendar-forward-month 1))))
16318 (org-defkey map [(meta shift up)]
16319 (lambda () (interactive)
16320 (org-eval-in-calendar '(calendar-backward-year 1))))
16321 (org-defkey map [(meta shift down)]
16322 (lambda () (interactive)
16323 (org-eval-in-calendar '(calendar-forward-year 1))))
16324 (org-defkey map [?\e (shift left)]
16325 (lambda () (interactive)
16326 (org-eval-in-calendar '(calendar-backward-month 1))))
16327 (org-defkey map [?\e (shift right)]
16328 (lambda () (interactive)
16329 (org-eval-in-calendar '(calendar-forward-month 1))))
16330 (org-defkey map [?\e (shift up)]
16331 (lambda () (interactive)
16332 (org-eval-in-calendar '(calendar-backward-year 1))))
16333 (org-defkey map [?\e (shift down)]
16334 (lambda () (interactive)
16335 (org-eval-in-calendar '(calendar-forward-year 1))))
16336 (org-defkey map [(shift up)]
16337 (lambda () (interactive)
16338 (org-eval-in-calendar '(calendar-backward-week 1))))
16339 (org-defkey map [(shift down)]
16340 (lambda () (interactive)
16341 (org-eval-in-calendar '(calendar-forward-week 1))))
16342 (org-defkey map [(shift left)]
16343 (lambda () (interactive)
16344 (org-eval-in-calendar '(calendar-backward-day 1))))
16345 (org-defkey map [(shift right)]
16346 (lambda () (interactive)
16347 (org-eval-in-calendar '(calendar-forward-day 1))))
16348 (org-defkey map "!"
16349 (lambda () (interactive)
16350 (org-eval-in-calendar '(diary-view-entries))
16351 (message "")))
16352 (org-defkey map ">"
16353 (lambda () (interactive)
16354 (org-eval-in-calendar '(scroll-calendar-left 1))))
16355 (org-defkey map "<"
16356 (lambda () (interactive)
16357 (org-eval-in-calendar '(scroll-calendar-right 1))))
16358 (org-defkey map "\C-v"
16359 (lambda () (interactive)
16360 (org-eval-in-calendar
16361 '(calendar-scroll-left-three-months 1))))
16362 (org-defkey map "\M-v"
16363 (lambda () (interactive)
16364 (org-eval-in-calendar
16365 '(calendar-scroll-right-three-months 1))))
16366 map)
16367 "Keymap for minibuffer commands when using `org-read-date'.")
16369 (defvar org-def)
16370 (defvar org-defdecode)
16371 (defvar org-with-time)
16373 (defun org-read-date (&optional org-with-time to-time from-string prompt
16374 default-time default-input inactive)
16375 "Read a date, possibly a time, and make things smooth for the user.
16376 The prompt will suggest to enter an ISO date, but you can also enter anything
16377 which will at least partially be understood by `parse-time-string'.
16378 Unrecognized parts of the date will default to the current day, month, year,
16379 hour and minute. If this command is called to replace a timestamp at point,
16380 or to enter the second timestamp of a range, the default time is taken
16381 from the existing stamp. Furthermore, the command prefers the future,
16382 so if you are giving a date where the year is not given, and the day-month
16383 combination is already past in the current year, it will assume you
16384 mean next year. For details, see the manual. A few examples:
16386 3-2-5 --> 2003-02-05
16387 feb 15 --> currentyear-02-15
16388 2/15 --> currentyear-02-15
16389 sep 12 9 --> 2009-09-12
16390 12:45 --> today 12:45
16391 22 sept 0:34 --> currentyear-09-22 0:34
16392 12 --> currentyear-currentmonth-12
16393 Fri --> nearest Friday after today
16394 -Tue --> last Tuesday
16395 etc.
16397 Furthermore you can specify a relative date by giving, as the *first* thing
16398 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16399 change in days weeks, months, years.
16400 With a single plus or minus, the date is relative to today. With a double
16401 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16402 +4d --> four days from today
16403 +4 --> same as above
16404 +2w --> two weeks from today
16405 ++5 --> five days from default date
16407 The function understands only English month and weekday abbreviations.
16409 While prompting, a calendar is popped up - you can also select the
16410 date with the mouse (button 1). The calendar shows a period of three
16411 months. To scroll it to other months, use the keys `>' and `<'.
16412 If you don't like the calendar, turn it off with
16413 \(setq org-read-date-popup-calendar nil)
16415 With optional argument TO-TIME, the date will immediately be converted
16416 to an internal time.
16417 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16418 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16419 still enter a time, and this function will inform the calling routine
16420 about this change. The calling routine may then choose to change the
16421 format used to insert the time stamp into the buffer to include the time.
16422 With optional argument FROM-STRING, read from this string instead from
16423 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16424 the time/date that is used for everything that is not specified by the
16425 user."
16426 (require 'parse-time)
16427 (let* ((org-time-stamp-rounding-minutes
16428 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16429 (org-dcst org-display-custom-times)
16430 (ct (org-current-time))
16431 (org-def (or org-overriding-default-time default-time ct))
16432 (org-defdecode (decode-time org-def))
16433 (dummy (progn
16434 (when (< (nth 2 org-defdecode) org-extend-today-until)
16435 (setcar (nthcdr 2 org-defdecode) -1)
16436 (setcar (nthcdr 1 org-defdecode) 59)
16437 (setq org-def (apply 'encode-time org-defdecode)
16438 org-defdecode (decode-time org-def)))))
16439 (mouse-autoselect-window nil) ; Don't let the mouse jump
16440 (calendar-frame-setup nil)
16441 (calendar-setup nil)
16442 (calendar-move-hook nil)
16443 (calendar-view-diary-initially-flag nil)
16444 (calendar-view-holidays-initially-flag nil)
16445 (timestr (format-time-string
16446 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16447 (prompt (concat (if prompt (concat prompt " ") "")
16448 (format "Date+time [%s]: " timestr)))
16449 ans (org-ans0 "") org-ans1 org-ans2 final)
16451 (cond
16452 (from-string (setq ans from-string))
16453 (org-read-date-popup-calendar
16454 (save-excursion
16455 (save-window-excursion
16456 (calendar)
16457 (org-eval-in-calendar '(setq cursor-type nil) t)
16458 (unwind-protect
16459 (progn
16460 (calendar-forward-day (- (time-to-days org-def)
16461 (calendar-absolute-from-gregorian
16462 (calendar-current-date))))
16463 (org-eval-in-calendar nil t)
16464 (let* ((old-map (current-local-map))
16465 (map (copy-keymap calendar-mode-map))
16466 (minibuffer-local-map
16467 (copy-keymap org-read-date-minibuffer-local-map)))
16468 (org-defkey map (kbd "RET") 'org-calendar-select)
16469 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16470 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16471 (unwind-protect
16472 (progn
16473 (use-local-map map)
16474 (setq org-read-date-inactive inactive)
16475 (add-hook 'post-command-hook 'org-read-date-display)
16476 (setq org-ans0 (read-string prompt default-input
16477 'org-read-date-history nil))
16478 ;; org-ans0: from prompt
16479 ;; org-ans1: from mouse click
16480 ;; org-ans2: from calendar motion
16481 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16482 (remove-hook 'post-command-hook 'org-read-date-display)
16483 (use-local-map old-map)
16484 (when org-read-date-overlay
16485 (delete-overlay org-read-date-overlay)
16486 (setq org-read-date-overlay nil)))))
16487 (bury-buffer "*Calendar*")))))
16489 (t ; Naked prompt only
16490 (unwind-protect
16491 (setq ans (read-string prompt default-input
16492 'org-read-date-history timestr))
16493 (when org-read-date-overlay
16494 (delete-overlay org-read-date-overlay)
16495 (setq org-read-date-overlay nil)))))
16497 (setq final (org-read-date-analyze ans org-def org-defdecode))
16499 (when org-read-date-analyze-forced-year
16500 (message "Year was forced into %s"
16501 (if org-read-date-force-compatible-dates
16502 "compatible range (1970-2037)"
16503 "range representable on this machine"))
16504 (ding))
16506 ;; One round trip to get rid of 34th of August and stuff like that....
16507 (setq final (decode-time (apply 'encode-time final)))
16509 (setq org-read-date-final-answer ans)
16511 (if to-time
16512 (apply 'encode-time final)
16513 (if (and (boundp 'org-time-was-given) org-time-was-given)
16514 (format "%04d-%02d-%02d %02d:%02d"
16515 (nth 5 final) (nth 4 final) (nth 3 final)
16516 (nth 2 final) (nth 1 final))
16517 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16519 (defun org-read-date-display ()
16520 "Display the current date prompt interpretation in the minibuffer."
16521 (when org-read-date-display-live
16522 (when org-read-date-overlay
16523 (delete-overlay org-read-date-overlay))
16524 (when (minibufferp (current-buffer))
16525 (save-excursion
16526 (end-of-line 1)
16527 (while (not (equal (buffer-substring
16528 (max (point-min) (- (point) 4)) (point))
16529 " "))
16530 (insert " ")))
16531 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16532 " " (or org-ans1 org-ans2)))
16533 (org-end-time-was-given nil)
16534 (f (org-read-date-analyze ans org-def org-defdecode))
16535 (fmts (if org-dcst
16536 org-time-stamp-custom-formats
16537 org-time-stamp-formats))
16538 (fmt (if (or org-with-time
16539 (and (boundp 'org-time-was-given) org-time-was-given))
16540 (cdr fmts)
16541 (car fmts)))
16542 (txt (format-time-string fmt (apply 'encode-time f)))
16543 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16544 (txt (concat "=> " txt)))
16545 (when (and org-end-time-was-given
16546 (string-match org-plain-time-of-day-regexp txt))
16547 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16548 org-end-time-was-given
16549 (substring txt (match-end 0)))))
16550 (when org-read-date-analyze-futurep
16551 (setq txt (concat txt " (=>F)")))
16552 (setq org-read-date-overlay
16553 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16554 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16556 (defun org-read-date-analyze (ans org-def org-defdecode)
16557 "Analyze the combined answer of the date prompt."
16558 ;; FIXME: cleanup and comment
16559 (let ((nowdecode (decode-time (current-time)))
16560 delta deltan deltaw deltadef year month day
16561 hour minute second wday pm h2 m2 tl wday1
16562 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16563 (setq org-read-date-analyze-futurep nil
16564 org-read-date-analyze-forced-year nil)
16565 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16566 (setq ans "+0"))
16568 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16569 (setq ans (replace-match "" t t ans)
16570 deltan (car delta)
16571 deltaw (nth 1 delta)
16572 deltadef (nth 2 delta)))
16574 ;; Check if there is an iso week date in there. If yes, store the
16575 ;; info and postpone interpreting it until the rest of the parsing
16576 ;; is done.
16577 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16578 (setq iso-year (if (match-end 1)
16579 (org-small-year-to-year
16580 (string-to-number (match-string 1 ans))))
16581 iso-weekday (if (match-end 3)
16582 (string-to-number (match-string 3 ans)))
16583 iso-week (string-to-number (match-string 2 ans)))
16584 (setq ans (replace-match "" t t ans)))
16586 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16587 (when (string-match
16588 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16589 (setq year (if (match-end 2)
16590 (string-to-number (match-string 2 ans))
16591 (progn (setq kill-year t)
16592 (string-to-number (format-time-string "%Y"))))
16593 month (string-to-number (match-string 3 ans))
16594 day (string-to-number (match-string 4 ans)))
16595 (if (< year 100) (setq year (+ 2000 year)))
16596 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16597 t nil ans)))
16599 ;; Help matching dotted european dates
16600 (when (string-match
16601 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16602 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16603 (setq kill-year t)
16604 (string-to-number (format-time-string "%Y")))
16605 day (string-to-number (match-string 1 ans))
16606 month (string-to-number (match-string 2 ans))
16607 ans (replace-match (format "%04d-%02d-%02d" year month day)
16608 t nil ans)))
16610 ;; Help matching american dates, like 5/30 or 5/30/7
16611 (when (string-match
16612 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16613 (setq year (if (match-end 4)
16614 (string-to-number (match-string 4 ans))
16615 (progn (setq kill-year t)
16616 (string-to-number (format-time-string "%Y"))))
16617 month (string-to-number (match-string 1 ans))
16618 day (string-to-number (match-string 2 ans)))
16619 (if (< year 100) (setq year (+ 2000 year)))
16620 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16621 t nil ans)))
16622 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16623 ;; If there is a time with am/pm, and *no* time without it, we convert
16624 ;; so that matching will be successful.
16625 (loop for i from 1 to 2 do ; twice, for end time as well
16626 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16627 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16628 (setq hour (string-to-number (match-string 1 ans))
16629 minute (if (match-end 3)
16630 (string-to-number (match-string 3 ans))
16632 pm (equal ?p
16633 (string-to-char (downcase (match-string 4 ans)))))
16634 (if (and (= hour 12) (not pm))
16635 (setq hour 0)
16636 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16637 (setq ans (replace-match (format "%02d:%02d" hour minute)
16638 t t ans))))
16640 ;; Check if a time range is given as a duration
16641 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16642 (setq hour (string-to-number (match-string 1 ans))
16643 h2 (+ hour (string-to-number (match-string 3 ans)))
16644 minute (string-to-number (match-string 2 ans))
16645 m2 (+ minute (if (match-end 5) (string-to-number
16646 (match-string 5 ans))0)))
16647 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16648 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16649 t t ans)))
16651 ;; Check if there is a time range
16652 (when (boundp 'org-end-time-was-given)
16653 (setq org-time-was-given nil)
16654 (when (and (string-match org-plain-time-of-day-regexp ans)
16655 (match-end 8))
16656 (setq org-end-time-was-given (match-string 8 ans))
16657 (setq ans (concat (substring ans 0 (match-beginning 7))
16658 (substring ans (match-end 7))))))
16660 (setq tl (parse-time-string ans)
16661 day (or (nth 3 tl) (nth 3 org-defdecode))
16662 month (or (nth 4 tl)
16663 (if (and org-read-date-prefer-future
16664 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16665 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16666 (nth 4 org-defdecode)))
16667 year (or (and (not kill-year) (nth 5 tl))
16668 (if (and org-read-date-prefer-future
16669 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16670 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16671 (nth 5 org-defdecode)))
16672 hour (or (nth 2 tl) (nth 2 org-defdecode))
16673 minute (or (nth 1 tl) (nth 1 org-defdecode))
16674 second (or (nth 0 tl) 0)
16675 wday (nth 6 tl))
16677 (when (and (eq org-read-date-prefer-future 'time)
16678 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16679 (equal day (nth 3 nowdecode))
16680 (equal month (nth 4 nowdecode))
16681 (equal year (nth 5 nowdecode))
16682 (nth 2 tl)
16683 (or (< (nth 2 tl) (nth 2 nowdecode))
16684 (and (= (nth 2 tl) (nth 2 nowdecode))
16685 (nth 1 tl)
16686 (< (nth 1 tl) (nth 1 nowdecode)))))
16687 (setq day (1+ day)
16688 futurep t))
16690 ;; Special date definitions below
16691 (cond
16692 (iso-week
16693 ;; There was an iso week
16694 (require 'cal-iso)
16695 (setq futurep nil)
16696 (setq year (or iso-year year)
16697 day (or iso-weekday wday 1)
16698 wday nil ; to make sure that the trigger below does not match
16699 iso-date (calendar-gregorian-from-absolute
16700 (calendar-absolute-from-iso
16701 (list iso-week day year))))
16702 ; FIXME: Should we also push ISO weeks into the future?
16703 ; (when (and org-read-date-prefer-future
16704 ; (not iso-year)
16705 ; (< (calendar-absolute-from-gregorian iso-date)
16706 ; (time-to-days (current-time))))
16707 ; (setq year (1+ year)
16708 ; iso-date (calendar-gregorian-from-absolute
16709 ; (calendar-absolute-from-iso
16710 ; (list iso-week day year)))))
16711 (setq month (car iso-date)
16712 year (nth 2 iso-date)
16713 day (nth 1 iso-date)))
16714 (deltan
16715 (setq futurep nil)
16716 (unless deltadef
16717 (let ((now (decode-time (current-time))))
16718 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16719 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16720 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16721 ((equal deltaw "m") (setq month (+ month deltan)))
16722 ((equal deltaw "y") (setq year (+ year deltan)))))
16723 ((and wday (not (nth 3 tl)))
16724 ;; Weekday was given, but no day, so pick that day in the week
16725 ;; on or after the derived date.
16726 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16727 (unless (equal wday wday1)
16728 (setq day (+ day (% (- wday wday1 -7) 7))))))
16729 (if (and (boundp 'org-time-was-given)
16730 (nth 2 tl))
16731 (setq org-time-was-given t))
16732 (if (< year 100) (setq year (+ 2000 year)))
16733 ;; Check of the date is representable
16734 (if org-read-date-force-compatible-dates
16735 (progn
16736 (if (< year 1970)
16737 (setq year 1970 org-read-date-analyze-forced-year t))
16738 (if (> year 2037)
16739 (setq year 2037 org-read-date-analyze-forced-year t)))
16740 (condition-case nil
16741 (ignore (encode-time second minute hour day month year))
16742 (error
16743 (setq year (nth 5 org-defdecode))
16744 (setq org-read-date-analyze-forced-year t))))
16745 (setq org-read-date-analyze-futurep futurep)
16746 (list second minute hour day month year)))
16748 (defvar parse-time-weekdays)
16749 (defun org-read-date-get-relative (s today default)
16750 "Check string S for special relative date string.
16751 TODAY and DEFAULT are internal times, for today and for a default.
16752 Return shift list (N what def-flag)
16753 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16754 N is the number of WHATs to shift.
16755 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16756 the DEFAULT date rather than TODAY."
16757 (require 'parse-time)
16758 (when (and
16759 (string-match
16760 (concat
16761 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16762 "\\([0-9]+\\)?"
16763 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16764 "\\([ \t]\\|$\\)") s)
16765 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16766 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16767 (string-to-char (substring (match-string 1 s) -1))
16768 ?+))
16769 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16770 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16771 (what (if (match-end 3) (match-string 3 s) "d"))
16772 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16773 (date (if rel default today))
16774 (wday (nth 6 (decode-time date)))
16775 delta)
16776 (if wday1
16777 (progn
16778 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16779 (if (= delta 0) (setq delta 7))
16780 (if (= dir ?-)
16781 (progn
16782 (setq delta (- delta 7))
16783 (if (= delta 0) (setq delta -7))))
16784 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16785 (list delta "d" rel))
16786 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16788 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16789 "Turn a user-specified date into the internal representation.
16790 The internal representation needed by the calendar is (month day year).
16791 This is a wrapper to handle the brain-dead convention in calendar that
16792 user function argument order change dependent on argument order."
16793 (if (boundp 'calendar-date-style)
16794 (cond
16795 ((eq calendar-date-style 'american)
16796 (list arg1 arg2 arg3))
16797 ((eq calendar-date-style 'european)
16798 (list arg2 arg1 arg3))
16799 ((eq calendar-date-style 'iso)
16800 (list arg2 arg3 arg1)))
16801 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16802 (if (org-bound-and-true-p european-calendar-style)
16803 (list arg2 arg1 arg3)
16804 (list arg1 arg2 arg3)))))
16806 (defun org-eval-in-calendar (form &optional keepdate)
16807 "Eval FORM in the calendar window and return to current window.
16808 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16809 otherwise stick to the current value of `org-ans2'."
16810 (let ((sf (selected-frame))
16811 (sw (selected-window)))
16812 (select-window (get-buffer-window "*Calendar*" t))
16813 (eval form)
16814 (when (and (not keepdate) (calendar-cursor-to-date))
16815 (let* ((date (calendar-cursor-to-date))
16816 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16817 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16818 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16819 (select-window sw)
16820 (org-select-frame-set-input-focus sf)))
16822 (defun org-calendar-select ()
16823 "Return to `org-read-date' with the date currently selected.
16824 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16825 (interactive)
16826 (when (calendar-cursor-to-date)
16827 (let* ((date (calendar-cursor-to-date))
16828 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16829 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16830 (if (active-minibuffer-window) (exit-minibuffer))))
16832 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16833 "Insert a date stamp for the date given by the internal TIME.
16834 WITH-HM means use the stamp format that includes the time of the day.
16835 INACTIVE means use square brackets instead of angular ones, so that the
16836 stamp will not contribute to the agenda.
16837 PRE and POST are optional strings to be inserted before and after the
16838 stamp.
16839 The command returns the inserted time stamp."
16840 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16841 stamp)
16842 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16843 (insert-before-markers (or pre ""))
16844 (when (listp extra)
16845 (setq extra (car extra))
16846 (if (and (stringp extra)
16847 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16848 (setq extra (format "-%02d:%02d"
16849 (string-to-number (match-string 1 extra))
16850 (string-to-number (match-string 2 extra))))
16851 (setq extra nil)))
16852 (when extra
16853 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16854 (insert-before-markers (setq stamp (format-time-string fmt time)))
16855 (insert-before-markers (or post ""))
16856 (setq org-last-inserted-timestamp stamp)))
16858 (defun org-toggle-time-stamp-overlays ()
16859 "Toggle the use of custom time stamp formats."
16860 (interactive)
16861 (setq org-display-custom-times (not org-display-custom-times))
16862 (unless org-display-custom-times
16863 (let ((p (point-min)) (bmp (buffer-modified-p)))
16864 (while (setq p (next-single-property-change p 'display))
16865 (if (and (get-text-property p 'display)
16866 (eq (get-text-property p 'face) 'org-date))
16867 (remove-text-properties
16868 p (setq p (next-single-property-change p 'display))
16869 '(display t))))
16870 (set-buffer-modified-p bmp)))
16871 (if (featurep 'xemacs)
16872 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16873 (org-restart-font-lock)
16874 (setq org-table-may-need-update t)
16875 (if org-display-custom-times
16876 (message "Time stamps are overlaid with custom format")
16877 (message "Time stamp overlays removed")))
16879 (defun org-display-custom-time (beg end)
16880 "Overlay modified time stamp format over timestamp between BEG and END."
16881 (let* ((ts (buffer-substring beg end))
16882 t1 w1 with-hm tf time str w2 (off 0))
16883 (save-match-data
16884 (setq t1 (org-parse-time-string ts t))
16885 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16886 (setq off (- (match-end 0) (match-beginning 0)))))
16887 (setq end (- end off))
16888 (setq w1 (- end beg)
16889 with-hm (and (nth 1 t1) (nth 2 t1))
16890 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16891 time (org-fix-decoded-time t1)
16892 str (org-add-props
16893 (format-time-string
16894 (substring tf 1 -1) (apply 'encode-time time))
16895 nil 'mouse-face 'highlight)
16896 w2 (length str))
16897 (if (not (= w2 w1))
16898 (add-text-properties (1+ beg) (+ 2 beg)
16899 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16900 (if (featurep 'xemacs)
16901 (progn
16902 (put-text-property beg end 'invisible t)
16903 (put-text-property beg end 'end-glyph (make-glyph str)))
16904 (put-text-property beg end 'display str))))
16906 (defun org-translate-time (string)
16907 "Translate all timestamps in STRING to custom format.
16908 But do this only if the variable `org-display-custom-times' is set."
16909 (when org-display-custom-times
16910 (save-match-data
16911 (let* ((start 0)
16912 (re org-ts-regexp-both)
16913 t1 with-hm inactive tf time str beg end)
16914 (while (setq start (string-match re string start))
16915 (setq beg (match-beginning 0)
16916 end (match-end 0)
16917 t1 (save-match-data
16918 (org-parse-time-string (substring string beg end) t))
16919 with-hm (and (nth 1 t1) (nth 2 t1))
16920 inactive (equal (substring string beg (1+ beg)) "[")
16921 tf (funcall (if with-hm 'cdr 'car)
16922 org-time-stamp-custom-formats)
16923 time (org-fix-decoded-time t1)
16924 str (format-time-string
16925 (concat
16926 (if inactive "[" "<") (substring tf 1 -1)
16927 (if inactive "]" ">"))
16928 (apply 'encode-time time))
16929 string (replace-match str t t string)
16930 start (+ start (length str)))))))
16931 string)
16933 (defun org-fix-decoded-time (time)
16934 "Set 0 instead of nil for the first 6 elements of time.
16935 Don't touch the rest."
16936 (let ((n 0))
16937 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16939 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16941 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16942 "Difference between TIMESTAMP-STRING and now in days.
16943 If SECONDS is non-nil, return the difference in seconds."
16944 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16945 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16946 (funcall fdiff (current-time)))))
16948 (defun org-deadline-close (timestamp-string &optional ndays)
16949 "Is the time in TIMESTAMP-STRING close to the current date?"
16950 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16951 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16952 (not (org-entry-is-done-p))))
16954 (defun org-get-wdays (ts &optional delay zero-delay)
16955 "Get the deadline lead time appropriate for timestring TS.
16956 When DELAY is non-nil, get the delay time for scheduled items
16957 instead of the deadline lead time. When ZERO-DELAY is non-nil
16958 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16959 don't try to find the delay cookie in the scheduled timestamp."
16960 (let ((tv (if delay org-scheduled-delay-days
16961 org-deadline-warning-days)))
16962 (cond
16963 ((or (and delay (< tv 0))
16964 (and delay zero-delay (<= tv 0))
16965 (and (not delay) (<= tv 0)))
16966 ;; Enforce this value no matter what
16967 (- tv))
16968 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16969 ;; lead time is specified.
16970 (floor (* (string-to-number (match-string 1 ts))
16971 (cdr (assoc (match-string 2 ts)
16972 '(("d" . 1) ("w" . 7)
16973 ("m" . 30.4) ("y" . 365.25)
16974 ("h" . 0.041667)))))))
16975 ;; go for the default.
16976 (t tv))))
16978 (defun org-calendar-select-mouse (ev)
16979 "Return to `org-read-date' with the date currently selected.
16980 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16981 (interactive "e")
16982 (mouse-set-point ev)
16983 (when (calendar-cursor-to-date)
16984 (let* ((date (calendar-cursor-to-date))
16985 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16986 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16987 (if (active-minibuffer-window) (exit-minibuffer))))
16989 (defun org-check-deadlines (ndays)
16990 "Check if there are any deadlines due or past due.
16991 A deadline is considered due if it happens within `org-deadline-warning-days'
16992 days from today's date. If the deadline appears in an entry marked DONE,
16993 it is not shown. The prefix arg NDAYS can be used to test that many
16994 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16995 (interactive "P")
16996 (let* ((org-warn-days
16997 (cond
16998 ((equal ndays '(4)) 100000)
16999 (ndays (prefix-numeric-value ndays))
17000 (t (abs org-deadline-warning-days))))
17001 (case-fold-search nil)
17002 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17003 (callback
17004 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17006 (message "%d deadlines past-due or due within %d days"
17007 (org-occur regexp nil callback)
17008 org-warn-days)))
17010 (defsubst org-re-timestamp (type)
17011 "Return a regexp for timestamp TYPE.
17012 Allowed values for TYPE are:
17014 all: all timestamps
17015 active: only active timestamps (<...>)
17016 inactive: only inactive timestamps ([...])
17017 scheduled: only scheduled timestamps
17018 deadline: only deadline timestamps
17019 closed: only closed time-stamps
17021 When TYPE is nil, fall back on returning a regexp that matches
17022 both scheduled and deadline timestamps."
17023 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17024 ((eq type 'active) org-ts-regexp)
17025 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17026 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17027 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17028 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17029 ((eq type 'scheduled-or-deadline)
17030 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17032 (defun org-check-before-date (date)
17033 "Check if there are deadlines or scheduled entries before DATE."
17034 (interactive (list (org-read-date)))
17035 (let ((case-fold-search nil)
17036 (regexp (org-re-timestamp org-ts-type))
17037 (callback
17038 (lambda () (time-less-p
17039 (org-time-string-to-time (match-string 1))
17040 (org-time-string-to-time date)))))
17041 (message "%d entries before %s"
17042 (org-occur regexp nil callback) date)))
17044 (defun org-check-after-date (date)
17045 "Check if there are deadlines or scheduled entries after DATE."
17046 (interactive (list (org-read-date)))
17047 (let ((case-fold-search nil)
17048 (regexp (org-re-timestamp org-ts-type))
17049 (callback
17050 (lambda () (not
17051 (time-less-p
17052 (org-time-string-to-time (match-string 1))
17053 (org-time-string-to-time date))))))
17054 (message "%d entries after %s"
17055 (org-occur regexp nil callback) date)))
17057 (defun org-check-dates-range (start-date end-date)
17058 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17059 (interactive (list (org-read-date nil nil nil "Range starts")
17060 (org-read-date nil nil nil "Range end")))
17061 (let ((case-fold-search nil)
17062 (regexp (org-re-timestamp org-ts-type))
17063 (callback
17064 (lambda ()
17065 (let ((match (match-string 1)))
17066 (and
17067 (not (time-less-p
17068 (org-time-string-to-time match)
17069 (org-time-string-to-time start-date)))
17070 (time-less-p
17071 (org-time-string-to-time match)
17072 (org-time-string-to-time end-date)))))))
17073 (message "%d entries between %s and %s"
17074 (org-occur regexp nil callback) start-date end-date)))
17076 (defun org-evaluate-time-range (&optional to-buffer)
17077 "Evaluate a time range by computing the difference between start and end.
17078 Normally the result is just printed in the echo area, but with prefix arg
17079 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17080 If the time range is actually in a table, the result is inserted into the
17081 next column.
17082 For time difference computation, a year is assumed to be exactly 365
17083 days in order to avoid rounding problems."
17084 (interactive "P")
17086 (org-clock-update-time-maybe)
17087 (save-excursion
17088 (unless (org-at-date-range-p t)
17089 (goto-char (point-at-bol))
17090 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17091 (if (not (org-at-date-range-p t))
17092 (user-error "Not at a time-stamp range, and none found in current line")))
17093 (let* ((ts1 (match-string 1))
17094 (ts2 (match-string 2))
17095 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17096 (match-end (match-end 0))
17097 (time1 (org-time-string-to-time ts1))
17098 (time2 (org-time-string-to-time ts2))
17099 (t1 (org-float-time time1))
17100 (t2 (org-float-time time2))
17101 (diff (abs (- t2 t1)))
17102 (negative (< (- t2 t1) 0))
17103 ;; (ys (floor (* 365 24 60 60)))
17104 (ds (* 24 60 60))
17105 (hs (* 60 60))
17106 (fy "%dy %dd %02d:%02d")
17107 (fy1 "%dy %dd")
17108 (fd "%dd %02d:%02d")
17109 (fd1 "%dd")
17110 (fh "%02d:%02d")
17111 y d h m align)
17112 (if havetime
17113 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17115 d (floor (/ diff ds)) diff (mod diff ds)
17116 h (floor (/ diff hs)) diff (mod diff hs)
17117 m (floor (/ diff 60)))
17118 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17120 d (floor (+ (/ diff ds) 0.5))
17121 h 0 m 0))
17122 (if (not to-buffer)
17123 (message "%s" (org-make-tdiff-string y d h m))
17124 (if (org-at-table-p)
17125 (progn
17126 (goto-char match-end)
17127 (setq align t)
17128 (and (looking-at " *|") (goto-char (match-end 0))))
17129 (goto-char match-end))
17130 (if (looking-at
17131 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17132 (replace-match ""))
17133 (if negative (insert " -"))
17134 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17135 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17136 (insert " " (format fh h m))))
17137 (if align (org-table-align))
17138 (message "Time difference inserted")))))
17140 (defun org-make-tdiff-string (y d h m)
17141 (let ((fmt "")
17142 (l nil))
17143 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17144 l (push y l)))
17145 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17146 l (push d l)))
17147 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17148 l (push h l)))
17149 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17150 l (push m l)))
17151 (apply 'format fmt (nreverse l))))
17153 (defun org-time-string-to-time (s &optional buffer pos)
17154 "Convert a timestamp string into internal time."
17155 (condition-case errdata
17156 (apply 'encode-time (org-parse-time-string s))
17157 (error (error "Bad timestamp `%s'%s\nError was: %s"
17158 s (if (not (and buffer pos))
17160 (format " at %d in buffer `%s'" pos buffer))
17161 (cdr errdata)))))
17163 (defun org-time-string-to-seconds (s)
17164 "Convert a timestamp string to a number of seconds."
17165 (org-float-time (org-time-string-to-time s)))
17167 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17168 "Convert a time stamp to an absolute day number.
17169 If there is a specifier for a cyclic time stamp, get the closest
17170 date to DAYNR.
17171 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17172 The variable `date' is bound by the calendar when this is called."
17173 (cond
17174 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17175 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17176 daynr
17177 (+ daynr 1000)))
17178 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17179 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17180 (time-to-days (current-time))) (match-string 0 s)
17181 prefer show-all))
17182 (t (time-to-days
17183 (condition-case errdata
17184 (apply 'encode-time (org-parse-time-string s))
17185 (error (error "Bad timestamp `%s'%s\nError was: %s"
17186 s (if (not (and buffer pos))
17188 (format " at %d in buffer `%s'" pos buffer))
17189 (cdr errdata))))))))
17191 (defun org-days-to-iso-week (days)
17192 "Return the iso week number."
17193 (require 'cal-iso)
17194 (car (calendar-iso-from-absolute days)))
17196 (defun org-small-year-to-year (year)
17197 "Convert 2-digit years into 4-digit years.
17198 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17199 The year 2000 cannot be abbreviated. Any year larger than 99
17200 is returned unchanged."
17201 (if (< year 38)
17202 (setq year (+ 2000 year))
17203 (if (< year 100)
17204 (setq year (+ 1900 year))))
17205 year)
17207 (defun org-time-from-absolute (d)
17208 "Return the time corresponding to date D.
17209 D may be an absolute day number, or a calendar-type list (month day year)."
17210 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17211 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17213 (defun org-calendar-holiday ()
17214 "List of holidays, for Diary display in Org-mode."
17215 (require 'holidays)
17216 (let ((hl (funcall
17217 (if (fboundp 'calendar-check-holidays)
17218 'calendar-check-holidays 'check-calendar-holidays) date)))
17219 (if hl (mapconcat 'identity hl "; "))))
17221 (defun org-diary-sexp-entry (sexp entry date)
17222 "Process a SEXP diary ENTRY for DATE."
17223 (require 'diary-lib)
17224 (let ((result (if calendar-debug-sexp
17225 (let ((stack-trace-on-error t))
17226 (eval (car (read-from-string sexp))))
17227 (condition-case nil
17228 (eval (car (read-from-string sexp)))
17229 (error
17230 (beep)
17231 (message "Bad sexp at line %d in %s: %s"
17232 (org-current-line)
17233 (buffer-file-name) sexp)
17234 (sleep-for 2))))))
17235 (cond ((stringp result) (split-string result "; "))
17236 ((and (consp result)
17237 (not (consp (cdr result)))
17238 (stringp (cdr result))) (cdr result))
17239 ((and (consp result)
17240 (stringp (car result))) result)
17241 (result entry))))
17243 (defun org-diary-to-ical-string (frombuf)
17244 "Get iCalendar entries from diary entries in buffer FROMBUF.
17245 This uses the icalendar.el library."
17246 (let* ((tmpdir (if (featurep 'xemacs)
17247 (temp-directory)
17248 temporary-file-directory))
17249 (tmpfile (make-temp-name
17250 (expand-file-name "orgics" tmpdir)))
17251 buf rtn b e)
17252 (with-current-buffer frombuf
17253 (icalendar-export-region (point-min) (point-max) tmpfile)
17254 (setq buf (find-buffer-visiting tmpfile))
17255 (set-buffer buf)
17256 (goto-char (point-min))
17257 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17258 (setq b (match-beginning 0)))
17259 (goto-char (point-max))
17260 (if (re-search-backward "^END:VEVENT" nil t)
17261 (setq e (match-end 0)))
17262 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17263 (kill-buffer buf)
17264 (delete-file tmpfile)
17265 rtn))
17267 (defun org-closest-date (start current change prefer show-all)
17268 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17269 When PREFER is `past', return a date that is either CURRENT or past.
17270 When PREFER is `future', return a date that is either CURRENT or future.
17271 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17272 ;; Make the proper lists from the dates
17273 (catch 'exit
17274 (let ((a1 '(("h" . hour)
17275 ("d" . day)
17276 ("w" . week)
17277 ("m" . month)
17278 ("y" . year)))
17279 (shour (nth 2 (org-parse-time-string start)))
17280 dn dw sday cday n1 n2 n0
17281 d m y y1 y2 date1 date2 nmonths nm ny m2)
17283 (setq start (org-date-to-gregorian start)
17284 current (org-date-to-gregorian
17285 (if show-all
17286 current
17287 (time-to-days (current-time))))
17288 sday (calendar-absolute-from-gregorian start)
17289 cday (calendar-absolute-from-gregorian current))
17291 (if (<= cday sday) (throw 'exit sday))
17293 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17294 (setq dn (string-to-number (match-string 1 change))
17295 dw (cdr (assoc (match-string 2 change) a1)))
17296 (user-error "Invalid change specifier: %s" change))
17297 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17298 (cond
17299 ((eq dw 'hour)
17300 (let ((missing-hours
17301 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17302 dn)))
17303 (setq n1 (if (zerop missing-hours) cday
17304 (- cday (1+ (floor (/ missing-hours 24)))))
17305 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17306 ((eq dw 'day)
17307 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17308 n2 (+ n1 dn)))
17309 ((eq dw 'year)
17310 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17311 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17312 (setq date1 (list m d y1)
17313 n1 (calendar-absolute-from-gregorian date1)
17314 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17315 n2 (calendar-absolute-from-gregorian date2)))
17316 ((eq dw 'month)
17317 ;; approx number of month between the two dates
17318 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17319 ;; How often does dn fit in there?
17320 (setq d (nth 1 start) m (car start) y (nth 2 start)
17321 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17322 m (+ m nm)
17323 ny (floor (/ m 12))
17324 y (+ y ny)
17325 m (- m (* ny 12)))
17326 (while (> m 12) (setq m (- m 12) y (1+ y)))
17327 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17328 (setq m2 (+ m dn) y2 y)
17329 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17330 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17331 (while (<= n2 cday)
17332 (setq n1 n2 m m2 y y2)
17333 (setq m2 (+ m dn) y2 y)
17334 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17335 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17336 ;; Make sure n1 is the earlier date
17337 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17338 (if show-all
17339 (cond
17340 ((eq prefer 'past) (if (= cday n2) n2 n1))
17341 ((eq prefer 'future) (if (= cday n1) n1 n2))
17342 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17343 (cond
17344 ((eq prefer 'past) (if (= cday n2) n2 n1))
17345 ((eq prefer 'future) (if (= cday n1) n1 n2))
17346 (t (if (= cday n1) n1 n2)))))))
17348 (defun org-date-to-gregorian (date)
17349 "Turn any specification of DATE into a Gregorian date for the calendar."
17350 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17351 ((and (listp date) (= (length date) 3)) date)
17352 ((stringp date)
17353 (setq date (org-parse-time-string date))
17354 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17355 ((listp date)
17356 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17358 (defun org-parse-time-string (s &optional nodefault)
17359 "Parse the standard Org-mode time string.
17360 This should be a lot faster than the normal `parse-time-string'.
17361 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17362 hour and minute fields will be nil if not given."
17363 (cond ((string-match org-ts-regexp0 s)
17364 (list 0
17365 (if (or (match-beginning 8) (not nodefault))
17366 (string-to-number (or (match-string 8 s) "0")))
17367 (if (or (match-beginning 7) (not nodefault))
17368 (string-to-number (or (match-string 7 s) "0")))
17369 (string-to-number (match-string 4 s))
17370 (string-to-number (match-string 3 s))
17371 (string-to-number (match-string 2 s))
17372 nil nil nil))
17373 ((string-match "^<[^>]+>$" s)
17374 (decode-time (seconds-to-time (org-matcher-time s))))
17375 (t (error "Not a standard Org-mode time string: %s" s))))
17377 (defun org-timestamp-up (&optional arg)
17378 "Increase the date item at the cursor by one.
17379 If the cursor is on the year, change the year. If it is on the month,
17380 the day or the time, change that.
17381 With prefix ARG, change by that many units."
17382 (interactive "p")
17383 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17385 (defun org-timestamp-down (&optional arg)
17386 "Decrease the date item at the cursor by one.
17387 If the cursor is on the year, change the year. If it is on the month,
17388 the day or the time, change that.
17389 With prefix ARG, change by that many units."
17390 (interactive "p")
17391 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17393 (defun org-timestamp-up-day (&optional arg)
17394 "Increase the date in the time stamp by one day.
17395 With prefix ARG, change that many days."
17396 (interactive "p")
17397 (if (and (not (org-at-timestamp-p t))
17398 (org-at-heading-p))
17399 (org-todo 'up)
17400 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17402 (defun org-timestamp-down-day (&optional arg)
17403 "Decrease the date in the time stamp by one day.
17404 With prefix ARG, change that many days."
17405 (interactive "p")
17406 (if (and (not (org-at-timestamp-p t))
17407 (org-at-heading-p))
17408 (org-todo 'down)
17409 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17411 (defun org-at-timestamp-p (&optional inactive-ok)
17412 "Determine if the cursor is in or at a timestamp."
17413 (interactive)
17414 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17415 (pos (point))
17416 (ans (or (looking-at tsr)
17417 (save-excursion
17418 (skip-chars-backward "^[<\n\r\t")
17419 (if (> (point) (point-min)) (backward-char 1))
17420 (and (looking-at tsr)
17421 (> (- (match-end 0) pos) -1))))))
17422 (and ans
17423 (boundp 'org-ts-what)
17424 (setq org-ts-what
17425 (cond
17426 ((= pos (match-beginning 0)) 'bracket)
17427 ;; Point is considered to be "on the bracket" whether
17428 ;; it's really on it or right after it.
17429 ((= pos (1- (match-end 0))) 'bracket)
17430 ((= pos (match-end 0)) 'after)
17431 ((org-pos-in-match-range pos 2) 'year)
17432 ((org-pos-in-match-range pos 3) 'month)
17433 ((org-pos-in-match-range pos 7) 'hour)
17434 ((org-pos-in-match-range pos 8) 'minute)
17435 ((or (org-pos-in-match-range pos 4)
17436 (org-pos-in-match-range pos 5)) 'day)
17437 ((and (> pos (or (match-end 8) (match-end 5)))
17438 (< pos (match-end 0)))
17439 (- pos (or (match-end 8) (match-end 5))))
17440 (t 'day))))
17441 ans))
17443 (defun org-toggle-timestamp-type ()
17444 "Toggle the type (<active> or [inactive]) of a time stamp."
17445 (interactive)
17446 (when (org-at-timestamp-p t)
17447 (let ((beg (match-beginning 0)) (end (match-end 0))
17448 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17449 (save-excursion
17450 (goto-char beg)
17451 (while (re-search-forward "[][<>]" end t)
17452 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17453 t t)))
17454 (message "Timestamp is now %sactive"
17455 (if (equal (char-after beg) ?<) "" "in")))))
17457 (defun org-at-clock-log-p nil
17458 "Is the cursor on the clock log line?"
17459 (save-excursion
17460 (move-beginning-of-line 1)
17461 (looking-at "^[ \t]*CLOCK:")))
17463 (defvar org-clock-history) ; defined in org-clock.el
17464 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17465 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17466 "Change the date in the time stamp at point.
17467 The date will be changed by N times WHAT. WHAT can be `day', `month',
17468 `year', `minute', `second'. If WHAT is not given, the cursor position
17469 in the timestamp determines what will be changed.
17470 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17471 (let ((origin (point)) origin-cat
17472 with-hm inactive
17473 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17474 org-ts-what
17475 extra rem
17476 ts time time0 fixnext clrgx)
17477 (if (not (org-at-timestamp-p t))
17478 (user-error "Not at a timestamp"))
17479 (if (and (not what) (eq org-ts-what 'bracket))
17480 (org-toggle-timestamp-type)
17481 ;; Point isn't on brackets. Remember the part of the time-stamp
17482 ;; the point was in. Indeed, size of time-stamps may change,
17483 ;; but point must be kept in the same category nonetheless.
17484 (setq origin-cat org-ts-what)
17485 (if (and (not what) (not (eq org-ts-what 'day))
17486 org-display-custom-times
17487 (get-text-property (point) 'display)
17488 (not (get-text-property (1- (point)) 'display)))
17489 (setq org-ts-what 'day))
17490 (setq org-ts-what (or what org-ts-what)
17491 inactive (= (char-after (match-beginning 0)) ?\[)
17492 ts (match-string 0))
17493 (replace-match "")
17494 (when (string-match
17495 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17497 (setq extra (match-string 1 ts))
17498 (if suppress-tmp-delay
17499 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17500 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17501 (setq with-hm t))
17502 (setq time0 (org-parse-time-string ts))
17503 (when (and updown
17504 (eq org-ts-what 'minute)
17505 (not current-prefix-arg))
17506 ;; This looks like s-up and s-down. Change by one rounding step.
17507 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17508 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17509 (setcar (cdr time0) (+ (nth 1 time0)
17510 (if (> n 0) (- rem) (- dm rem))))))
17511 (setq time
17512 (encode-time (or (car time0) 0)
17513 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17514 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17515 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17516 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17517 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17518 (nthcdr 6 time0)))
17519 (when (and (member org-ts-what '(hour minute))
17520 extra
17521 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17522 (setq extra (org-modify-ts-extra
17523 extra
17524 (if (eq org-ts-what 'hour) 2 5)
17525 n dm)))
17526 (when (integerp org-ts-what)
17527 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17528 (if (eq what 'calendar)
17529 (let ((cal-date (org-get-date-from-calendar)))
17530 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17531 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17532 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17533 (setcar time0 (or (car time0) 0))
17534 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17535 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17536 (setq time (apply 'encode-time time0))))
17537 ;; Insert the new time-stamp, and ensure point stays in the same
17538 ;; category as before (i.e. not after the last position in that
17539 ;; category).
17540 (let ((pos (point)))
17541 ;; Stay before inserted string. `save-excursion' is of no use.
17542 (setq org-last-changed-timestamp
17543 (org-insert-time-stamp time with-hm inactive nil nil extra))
17544 (goto-char pos))
17545 (save-match-data
17546 (looking-at org-ts-regexp3)
17547 (goto-char (cond
17548 ;; `day' category ends before `hour' if any, or at
17549 ;; the end of the day name.
17550 ((eq origin-cat 'day)
17551 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17552 ((eq origin-cat 'hour) (min (match-end 7) origin))
17553 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17554 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17555 ;; `year' and `month' have both fixed size: point
17556 ;; couldn't have moved into another part.
17557 (t origin))))
17558 ;; Update clock if on a CLOCK line.
17559 (org-clock-update-time-maybe)
17560 ;; Maybe adjust the closest clock in `org-clock-history'
17561 (when org-clock-adjust-closest
17562 (if (not (and (org-at-clock-log-p)
17563 (< 1 (length (delq nil (mapcar 'marker-position
17564 org-clock-history))))))
17565 (message "No clock to adjust")
17566 (cond ((save-excursion ; fix previous clock?
17567 (re-search-backward org-ts-regexp0 nil t)
17568 (org-looking-back (concat org-clock-string " \\[")))
17569 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17570 ((save-excursion ; fix next clock?
17571 (re-search-backward org-ts-regexp0 nil t)
17572 (looking-at (concat org-ts-regexp0 "\\] =>")))
17573 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17574 (save-window-excursion
17575 ;; Find closest clock to point, adjust the previous/next one in history
17576 (let* ((p (save-excursion (org-back-to-heading t)))
17577 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17578 (clfixnth
17579 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17580 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17581 (if (not clfixpos)
17582 (message "No clock to adjust")
17583 (save-excursion
17584 (org-goto-marker-or-bmk clfixpos)
17585 (org-show-subtree)
17586 (when (re-search-forward clrgx nil t)
17587 (goto-char (match-beginning 1))
17588 (let (org-clock-adjust-closest)
17589 (org-timestamp-change n org-ts-what updown))
17590 (message "Clock adjusted in %s for heading: %s"
17591 (file-name-nondirectory (buffer-file-name))
17592 (org-get-heading t t)))))))))
17593 ;; Try to recenter the calendar window, if any.
17594 (if (and org-calendar-follow-timestamp-change
17595 (get-buffer-window "*Calendar*" t)
17596 (memq org-ts-what '(day month year)))
17597 (org-recenter-calendar (time-to-days time))))))
17599 (defun org-modify-ts-extra (s pos n dm)
17600 "Change the different parts of the lead-time and repeat fields in timestamp."
17601 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17602 ng h m new rem)
17603 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17604 (cond
17605 ((or (org-pos-in-match-range pos 2)
17606 (org-pos-in-match-range pos 3))
17607 (setq m (string-to-number (match-string 3 s))
17608 h (string-to-number (match-string 2 s)))
17609 (if (org-pos-in-match-range pos 2)
17610 (setq h (+ h n))
17611 (setq n (* dm (org-no-warnings (signum n))))
17612 (when (not (= 0 (setq rem (% m dm))))
17613 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17614 (setq m (+ m n)))
17615 (if (< m 0) (setq m (+ m 60) h (1- h)))
17616 (if (> m 59) (setq m (- m 60) h (1+ h)))
17617 (setq h (min 24 (max 0 h)))
17618 (setq ng 1 new (format "-%02d:%02d" h m)))
17619 ((org-pos-in-match-range pos 6)
17620 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17621 ((org-pos-in-match-range pos 5)
17622 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17624 ((org-pos-in-match-range pos 9)
17625 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17626 ((org-pos-in-match-range pos 8)
17627 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17629 (when ng
17630 (setq s (concat
17631 (substring s 0 (match-beginning ng))
17633 (substring s (match-end ng))))))
17636 (defun org-recenter-calendar (date)
17637 "If the calendar is visible, recenter it to DATE."
17638 (let ((cwin (get-buffer-window "*Calendar*" t)))
17639 (when cwin
17640 (let ((calendar-move-hook nil))
17641 (with-selected-window cwin
17642 (calendar-goto-date (if (listp date) date
17643 (calendar-gregorian-from-absolute date))))))))
17645 (defun org-goto-calendar (&optional arg)
17646 "Go to the Emacs calendar at the current date.
17647 If there is a time stamp in the current line, go to that date.
17648 A prefix ARG can be used to force the current date."
17649 (interactive "P")
17650 (let ((tsr org-ts-regexp) diff
17651 (calendar-move-hook nil)
17652 (calendar-view-holidays-initially-flag nil)
17653 (calendar-view-diary-initially-flag nil))
17654 (if (or (org-at-timestamp-p)
17655 (save-excursion
17656 (beginning-of-line 1)
17657 (looking-at (concat ".*" tsr))))
17658 (let ((d1 (time-to-days (current-time)))
17659 (d2 (time-to-days
17660 (org-time-string-to-time (match-string 1)))))
17661 (setq diff (- d2 d1))))
17662 (calendar)
17663 (calendar-goto-today)
17664 (if (and diff (not arg)) (calendar-forward-day diff))))
17666 (defun org-get-date-from-calendar ()
17667 "Return a list (month day year) of date at point in calendar."
17668 (with-current-buffer "*Calendar*"
17669 (save-match-data
17670 (calendar-cursor-to-date))))
17672 (defun org-date-from-calendar ()
17673 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17674 If there is already a time stamp at the cursor position, update it."
17675 (interactive)
17676 (if (org-at-timestamp-p t)
17677 (org-timestamp-change 0 'calendar)
17678 (let ((cal-date (org-get-date-from-calendar)))
17679 (org-insert-time-stamp
17680 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17682 (defcustom org-effort-durations
17683 `(("h" . 60)
17684 ("d" . ,(* 60 8))
17685 ("w" . ,(* 60 8 5))
17686 ("m" . ,(* 60 8 5 4))
17687 ("y" . ,(* 60 8 5 40)))
17688 "Conversion factor to minutes for an effort modifier.
17690 Each entry has the form (MODIFIER . MINUTES).
17692 In an effort string, a number followed by MODIFIER is multiplied
17693 by the specified number of MINUTES to obtain an effort in
17694 minutes.
17696 For example, if the value of this variable is ((\"hours\" . 60)), then an
17697 effort string \"2hours\" is equivalent to 120 minutes."
17698 :group 'org-agenda
17699 :version "24.1"
17700 :type '(alist :key-type (string :tag "Modifier")
17701 :value-type (number :tag "Minutes")))
17703 (defun org-minutes-to-clocksum-string (m)
17704 "Format number of minutes as a clocksum string.
17705 The format is determined by `org-time-clocksum-format',
17706 `org-time-clocksum-use-fractional' and
17707 `org-time-clocksum-fractional-format' and
17708 `org-time-clocksum-use-effort-durations'."
17709 (let ((clocksum "")
17710 (m (round m)) ; Don't allow fractions of minutes
17711 h d w mo y fmt n)
17712 (setq h (if org-time-clocksum-use-effort-durations
17713 (cdr (assoc "h" org-effort-durations)) 60)
17714 d (if org-time-clocksum-use-effort-durations
17715 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17716 w (if org-time-clocksum-use-effort-durations
17717 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17718 mo (if org-time-clocksum-use-effort-durations
17719 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17720 y (if org-time-clocksum-use-effort-durations
17721 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17722 ;; fractional format
17723 (if org-time-clocksum-use-fractional
17724 (cond
17725 ;; single format string
17726 ((stringp org-time-clocksum-fractional-format)
17727 (format org-time-clocksum-fractional-format (/ m (float h))))
17728 ;; choice of fractional formats for different time units
17729 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17730 (> (/ (truncate m) (* y d h)) 0))
17731 (format fmt (/ m (* y d (float h)))))
17732 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17733 (> (/ (truncate m) (* mo d h)) 0))
17734 (format fmt (/ m (* mo d (float h)))))
17735 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17736 (> (/ (truncate m) (* w d h)) 0))
17737 (format fmt (/ m (* w d (float h)))))
17738 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17739 (> (/ (truncate m) (* d h)) 0))
17740 (format fmt (/ m (* d (float h)))))
17741 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17742 (> (/ (truncate m) h) 0))
17743 (format fmt (/ m (float h))))
17744 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17745 (format fmt m))
17746 ;; fall back to smallest time unit with a format
17747 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17748 (format fmt (/ m (float h))))
17749 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17750 (format fmt (/ m (* d (float h)))))
17751 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17752 (format fmt (/ m (* w d (float h)))))
17753 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17754 (format fmt (/ m (* mo d (float h)))))
17755 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17756 (format fmt (/ m (* y d (float h))))))
17757 ;; standard (non-fractional) format, with single format string
17758 (if (stringp org-time-clocksum-format)
17759 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17760 ;; separate formats components
17761 (and (setq fmt (plist-get org-time-clocksum-format :years))
17762 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17763 (plist-get org-time-clocksum-format :require-years))
17764 (setq clocksum (concat clocksum (format fmt n))
17765 m (- m (* n y d h))))
17766 (and (setq fmt (plist-get org-time-clocksum-format :months))
17767 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17768 (plist-get org-time-clocksum-format :require-months))
17769 (setq clocksum (concat clocksum (format fmt n))
17770 m (- m (* n mo d h))))
17771 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17772 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17773 (plist-get org-time-clocksum-format :require-weeks))
17774 (setq clocksum (concat clocksum (format fmt n))
17775 m (- m (* n w d h))))
17776 (and (setq fmt (plist-get org-time-clocksum-format :days))
17777 (or (> (setq n (/ (truncate m) (* d h))) 0)
17778 (plist-get org-time-clocksum-format :require-days))
17779 (setq clocksum (concat clocksum (format fmt n))
17780 m (- m (* n d h))))
17781 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17782 (or (> (setq n (/ (truncate m) h)) 0)
17783 (plist-get org-time-clocksum-format :require-hours))
17784 (setq clocksum (concat clocksum (format fmt n))
17785 m (- m (* n h))))
17786 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17787 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17788 (setq clocksum (concat clocksum (format fmt m))))
17789 ;; return formatted time duration
17790 clocksum))))
17792 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17793 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17794 "Org mode version 8.0")
17796 (defun org-hours-to-clocksum-string (n)
17797 (org-minutes-to-clocksum-string (* n 60)))
17799 (defun org-hh:mm-string-to-minutes (s)
17800 "Convert a string H:MM to a number of minutes.
17801 If the string is just a number, interpret it as minutes.
17802 In fact, the first hh:mm or number in the string will be taken,
17803 there can be extra stuff in the string.
17804 If no number is found, the return value is 0."
17805 (cond
17806 ((integerp s) s)
17807 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17808 (+ (* (string-to-number (match-string 1 s)) 60)
17809 (string-to-number (match-string 2 s))))
17810 ((string-match "\\([0-9]+\\)" s)
17811 (string-to-number (match-string 1 s)))
17812 (t 0)))
17814 (defcustom org-image-actual-width t
17815 "Should we use the actual width of images when inlining them?
17817 When set to `t', always use the image width.
17819 When set to a number, use imagemagick (when available) to set
17820 the image's width to this value.
17822 When set to a number in a list, try to get the width from any
17823 #+ATTR.* keyword if it matches a width specification like
17825 #+ATTR_HTML: :width 300px
17827 and fall back on that number if none is found.
17829 When set to nil, try to get the width from an #+ATTR.* keyword
17830 and fall back on the original width if none is found.
17832 This requires Emacs >= 24.1, build with imagemagick support."
17833 :group 'org-appearance
17834 :version "24.4"
17835 :package-version '(Org . "8.0")
17836 :type '(choice
17837 (const :tag "Use the image width" t)
17838 (integer :tag "Use a number of pixels")
17839 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17840 (const :tag "Use #+ATTR* or don't resize" nil)))
17842 (defcustom org-agenda-inhibit-startup nil
17843 "Inhibit startup when preparing agenda buffers.
17844 When this variable is `t' (the default), the initialization of
17845 the Org agenda buffers is inhibited: e.g. the visibility state
17846 is not set, the tables are not re-aligned, etc."
17847 :type 'boolean
17848 :version "24.3"
17849 :group 'org-agenda)
17851 (defcustom org-agenda-ignore-drawer-properties nil
17852 "Avoid updating text properties when building the agenda.
17853 Properties are used to prepare buffers for effort estimates, appointments,
17854 and subtree-local categories.
17855 If you don't use these in the agenda, you can add them to this list and
17856 agenda building will be a bit faster.
17857 The value is a list, with zero or more of the symbols `effort', `appt',
17858 or `category'."
17859 :type '(set :greedy t
17860 (const effort)
17861 (const appt)
17862 (const category))
17863 :version "24.3"
17864 :group 'org-agenda)
17866 (defun org-duration-string-to-minutes (s &optional output-to-string)
17867 "Convert a duration string S to minutes.
17869 A bare number is interpreted as minutes, modifiers can be set by
17870 customizing `org-effort-durations' (which see).
17872 Entries containing a colon are interpreted as H:MM by
17873 `org-hh:mm-string-to-minutes'."
17874 (let ((result 0)
17875 (re (concat "\\([0-9.]+\\) *\\("
17876 (regexp-opt (mapcar 'car org-effort-durations))
17877 "\\)")))
17878 (while (string-match re s)
17879 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17880 (string-to-number (match-string 1 s))))
17881 (setq s (replace-match "" nil t s)))
17882 (setq result (floor result))
17883 (incf result (org-hh:mm-string-to-minutes s))
17884 (if output-to-string (number-to-string result) result)))
17886 ;;;; Files
17888 (defun org-save-all-org-buffers ()
17889 "Save all Org-mode buffers without user confirmation."
17890 (interactive)
17891 (message "Saving all Org-mode buffers...")
17892 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17893 (when (featurep 'org-id) (org-id-locations-save))
17894 (message "Saving all Org-mode buffers... done"))
17896 (defun org-revert-all-org-buffers ()
17897 "Revert all Org-mode buffers.
17898 Prompt for confirmation when there are unsaved changes.
17899 Be sure you know what you are doing before letting this function
17900 overwrite your changes.
17902 This function is useful in a setup where one tracks org files
17903 with a version control system, to revert on one machine after pulling
17904 changes from another. I believe the procedure must be like this:
17906 1. M-x org-save-all-org-buffers
17907 2. Pull changes from the other machine, resolve conflicts
17908 3. M-x org-revert-all-org-buffers"
17909 (interactive)
17910 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17911 (user-error "Abort"))
17912 (save-excursion
17913 (save-window-excursion
17914 (mapc
17915 (lambda (b)
17916 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17917 (with-current-buffer b buffer-file-name))
17918 (org-pop-to-buffer-same-window b)
17919 (revert-buffer t 'no-confirm)))
17920 (buffer-list))
17921 (when (and (featurep 'org-id) org-id-track-globally)
17922 (org-id-locations-load)))))
17924 ;;;; Agenda files
17926 ;;;###autoload
17927 (defun org-switchb (&optional arg)
17928 "Switch between Org buffers.
17929 With one prefix argument, restrict available buffers to files.
17930 With two prefix arguments, restrict available buffers to agenda files.
17932 Defaults to `iswitchb' for buffer name completion.
17933 Set `org-completion-use-ido' to make it use ido instead."
17934 (interactive "P")
17935 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17936 ((equal arg '(16)) (org-buffer-list 'agenda))
17937 (t (org-buffer-list))))
17938 (org-completion-use-iswitchb org-completion-use-iswitchb)
17939 (org-completion-use-ido org-completion-use-ido))
17940 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17941 (setq org-completion-use-iswitchb t))
17942 (org-pop-to-buffer-same-window
17943 (org-icompleting-read "Org buffer: "
17944 (mapcar 'list (mapcar 'buffer-name blist))
17945 nil t))))
17947 ;;; Define some older names previously used for this functionality
17948 ;;;###autoload
17949 (defalias 'org-ido-switchb 'org-switchb)
17950 ;;;###autoload
17951 (defalias 'org-iswitchb 'org-switchb)
17953 (defun org-buffer-list (&optional predicate exclude-tmp)
17954 "Return a list of Org buffers.
17955 PREDICATE can be `export', `files' or `agenda'.
17957 export restrict the list to Export buffers.
17958 files restrict the list to buffers visiting Org files.
17959 agenda restrict the list to buffers visiting agenda files.
17961 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17962 (let* ((bfn nil)
17963 (agenda-files (and (eq predicate 'agenda)
17964 (mapcar 'file-truename (org-agenda-files t))))
17965 (filter
17966 (cond
17967 ((eq predicate 'files)
17968 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17969 ((eq predicate 'export)
17970 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17971 ((eq predicate 'agenda)
17972 (lambda (b)
17973 (with-current-buffer b
17974 (and (derived-mode-p 'org-mode)
17975 (setq bfn (buffer-file-name b))
17976 (member (file-truename bfn) agenda-files)))))
17977 (t (lambda (b) (with-current-buffer b
17978 (or (derived-mode-p 'org-mode)
17979 (string-match "\*Org .*Export"
17980 (buffer-name b)))))))))
17981 (delq nil
17982 (mapcar
17983 (lambda(b)
17984 (if (and (funcall filter b)
17985 (or (not exclude-tmp)
17986 (not (string-match "tmp" (buffer-name b)))))
17988 nil))
17989 (buffer-list)))))
17991 (defun org-agenda-files (&optional unrestricted archives)
17992 "Get the list of agenda files.
17993 Optional UNRESTRICTED means return the full list even if a restriction
17994 is currently in place.
17995 When ARCHIVES is t, include all archive files that are really being
17996 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17997 `org-agenda-archives-mode' is t."
17998 (let ((files
17999 (cond
18000 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18001 ((stringp org-agenda-files) (org-read-agenda-file-list))
18002 ((listp org-agenda-files) org-agenda-files)
18003 (t (error "Invalid value of `org-agenda-files'")))))
18004 (setq files (apply 'append
18005 (mapcar (lambda (f)
18006 (if (file-directory-p f)
18007 (directory-files
18008 f t org-agenda-file-regexp)
18009 (list f)))
18010 files)))
18011 (when org-agenda-skip-unavailable-files
18012 (setq files (delq nil
18013 (mapcar (function
18014 (lambda (file)
18015 (and (file-readable-p file) file)))
18016 files))))
18017 (when (or (eq archives t)
18018 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18019 (setq files (org-add-archive-files files)))
18020 files))
18022 (defun org-agenda-file-p (&optional file)
18023 "Return non-nil, if FILE is an agenda file.
18024 If FILE is omitted, use the file associated with the current
18025 buffer."
18026 (member (or file (buffer-file-name))
18027 (org-agenda-files t)))
18029 (defun org-edit-agenda-file-list ()
18030 "Edit the list of agenda files.
18031 Depending on setup, this either uses customize to edit the variable
18032 `org-agenda-files', or it visits the file that is holding the list. In the
18033 latter case, the buffer is set up in a way that saving it automatically kills
18034 the buffer and restores the previous window configuration."
18035 (interactive)
18036 (if (stringp org-agenda-files)
18037 (let ((cw (current-window-configuration)))
18038 (find-file org-agenda-files)
18039 (org-set-local 'org-window-configuration cw)
18040 (org-add-hook 'after-save-hook
18041 (lambda ()
18042 (set-window-configuration
18043 (prog1 org-window-configuration
18044 (kill-buffer (current-buffer))))
18045 (org-install-agenda-files-menu)
18046 (message "New agenda file list installed"))
18047 nil 'local)
18048 (message "%s" (substitute-command-keys
18049 "Edit list and finish with \\[save-buffer]")))
18050 (customize-variable 'org-agenda-files)))
18052 (defun org-store-new-agenda-file-list (list)
18053 "Set new value for the agenda file list and save it correctly."
18054 (if (stringp org-agenda-files)
18055 (let ((fe (org-read-agenda-file-list t)) b u)
18056 (while (setq b (find-buffer-visiting org-agenda-files))
18057 (kill-buffer b))
18058 (with-temp-file org-agenda-files
18059 (insert
18060 (mapconcat
18061 (lambda (f) ;; Keep un-expanded entries.
18062 (if (setq u (assoc f fe))
18063 (cdr u)
18065 list "\n")
18066 "\n")))
18067 (let ((org-mode-hook nil) (org-inhibit-startup t)
18068 (org-insert-mode-line-in-empty-file nil))
18069 (setq org-agenda-files list)
18070 (customize-save-variable 'org-agenda-files org-agenda-files))))
18072 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18073 "Read the list of agenda files from a file.
18074 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18075 filenames, used by `org-store-new-agenda-file-list' to write back
18076 un-expanded file names."
18077 (when (file-directory-p org-agenda-files)
18078 (error "`org-agenda-files' cannot be a single directory"))
18079 (when (stringp org-agenda-files)
18080 (with-temp-buffer
18081 (insert-file-contents org-agenda-files)
18082 (mapcar
18083 (lambda (f)
18084 (let ((e (expand-file-name (substitute-in-file-name f)
18085 org-directory)))
18086 (if pair-with-expansion
18087 (cons e f)
18088 e)))
18089 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18091 ;;;###autoload
18092 (defun org-cycle-agenda-files ()
18093 "Cycle through the files in `org-agenda-files'.
18094 If the current buffer visits an agenda file, find the next one in the list.
18095 If the current buffer does not, find the first agenda file."
18096 (interactive)
18097 (let* ((fs (org-agenda-files t))
18098 (files (append fs (list (car fs))))
18099 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18100 file)
18101 (unless files (user-error "No agenda files"))
18102 (catch 'exit
18103 (while (setq file (pop files))
18104 (if (equal (file-truename file) tcf)
18105 (when (car files)
18106 (find-file (car files))
18107 (throw 'exit t))))
18108 (find-file (car fs)))
18109 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18111 (defun org-agenda-file-to-front (&optional to-end)
18112 "Move/add the current file to the top of the agenda file list.
18113 If the file is not present in the list, it is added to the front. If it is
18114 present, it is moved there. With optional argument TO-END, add/move to the
18115 end of the list."
18116 (interactive "P")
18117 (let ((org-agenda-skip-unavailable-files nil)
18118 (file-alist (mapcar (lambda (x)
18119 (cons (file-truename x) x))
18120 (org-agenda-files t)))
18121 (ctf (file-truename
18122 (or buffer-file-name
18123 (user-error "Please save the current buffer to a file"))))
18124 x had)
18125 (setq x (assoc ctf file-alist) had x)
18127 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18128 (if to-end
18129 (setq file-alist (append (delq x file-alist) (list x)))
18130 (setq file-alist (cons x (delq x file-alist))))
18131 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18132 (org-install-agenda-files-menu)
18133 (message "File %s to %s of agenda file list"
18134 (if had "moved" "added") (if to-end "end" "front"))))
18136 (defun org-remove-file (&optional file)
18137 "Remove current file from the list of files in variable `org-agenda-files'.
18138 These are the files which are being checked for agenda entries.
18139 Optional argument FILE means use this file instead of the current."
18140 (interactive)
18141 (let* ((org-agenda-skip-unavailable-files nil)
18142 (file (or file buffer-file-name
18143 (user-error "Current buffer does not visit a file")))
18144 (true-file (file-truename file))
18145 (afile (abbreviate-file-name file))
18146 (files (delq nil (mapcar
18147 (lambda (x)
18148 (if (equal true-file
18149 (file-truename x))
18150 nil x))
18151 (org-agenda-files t)))))
18152 (if (not (= (length files) (length (org-agenda-files t))))
18153 (progn
18154 (org-store-new-agenda-file-list files)
18155 (org-install-agenda-files-menu)
18156 (message "Removed file: %s" afile))
18157 (message "File was not in list: %s (not removed)" afile))))
18159 (defun org-file-menu-entry (file)
18160 (vector file (list 'find-file file) t))
18162 (defun org-check-agenda-file (file)
18163 "Make sure FILE exists. If not, ask user what to do."
18164 (when (not (file-exists-p file))
18165 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18166 (abbreviate-file-name file))
18167 (let ((r (downcase (read-char-exclusive))))
18168 (cond
18169 ((equal r ?r)
18170 (org-remove-file file)
18171 (throw 'nextfile t))
18172 (t (user-error "Abort"))))))
18174 (defun org-get-agenda-file-buffer (file)
18175 "Get an agenda buffer visiting FILE.
18176 If the buffer needs to be created, add it to the list of buffers
18177 which might be released later."
18178 (let ((buf (org-find-base-buffer-visiting file)))
18179 (if buf
18180 buf ; just return it
18181 ;; Make a new buffer and remember it
18182 (setq buf (find-file-noselect file))
18183 (if buf (push buf org-agenda-new-buffers))
18184 buf)))
18186 (defun org-release-buffers (blist)
18187 "Release all buffers in list, asking the user for confirmation when needed.
18188 When a buffer is unmodified, it is just killed. When modified, it is saved
18189 \(if the user agrees) and then killed."
18190 (let (buf file)
18191 (while (setq buf (pop blist))
18192 (setq file (buffer-file-name buf))
18193 (when (and (buffer-modified-p buf)
18194 file
18195 (y-or-n-p (format "Save file %s? " file)))
18196 (with-current-buffer buf (save-buffer)))
18197 (kill-buffer buf))))
18199 (defun org-agenda-prepare-buffers (files)
18200 "Create buffers for all agenda files, protect archived trees and comments."
18201 (interactive)
18202 (let ((pa '(:org-archived t))
18203 (pc '(:org-comment t))
18204 (pall '(:org-archived t :org-comment t))
18205 (inhibit-read-only t)
18206 (org-inhibit-startup org-agenda-inhibit-startup)
18207 (rea (concat ":" org-archive-tag ":"))
18208 file re pos)
18209 (setq org-tag-alist-for-agenda nil
18210 org-tag-groups-alist-for-agenda nil)
18211 (save-excursion
18212 (save-restriction
18213 (while (setq file (pop files))
18214 (catch 'nextfile
18215 (if (bufferp file)
18216 (set-buffer file)
18217 (org-check-agenda-file file)
18218 (set-buffer (org-get-agenda-file-buffer file)))
18219 (widen)
18220 (org-set-regexps-and-options-for-tags)
18221 (setq pos (point))
18222 (goto-char (point-min))
18223 (let ((case-fold-search t))
18224 (when (search-forward "#+setupfile" nil t)
18225 ;; Don't set all regexps and options systematically as
18226 ;; this is only run for setting agenda tags from setup
18227 ;; file
18228 (org-set-regexps-and-options)))
18229 (or (memq 'category org-agenda-ignore-drawer-properties)
18230 (org-refresh-category-properties))
18231 (or (memq 'effort org-agenda-ignore-drawer-properties)
18232 (org-refresh-properties org-effort-property 'org-effort))
18233 (or (memq 'appt org-agenda-ignore-drawer-properties)
18234 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18235 (setq org-todo-keywords-for-agenda
18236 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18237 (setq org-done-keywords-for-agenda
18238 (append org-done-keywords-for-agenda org-done-keywords))
18239 (setq org-todo-keyword-alist-for-agenda
18240 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18241 (setq org-tag-alist-for-agenda
18242 (org-uniquify
18243 (append org-tag-alist-for-agenda
18244 org-tag-alist
18245 org-tag-persistent-alist)))
18246 (if org-group-tags
18247 (setq org-tag-groups-alist-for-agenda
18248 (org-uniquify-alist
18249 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18250 (org-with-silent-modifications
18251 (save-excursion
18252 (remove-text-properties (point-min) (point-max) pall)
18253 (when org-agenda-skip-archived-trees
18254 (goto-char (point-min))
18255 (while (re-search-forward rea nil t)
18256 (if (org-at-heading-p t)
18257 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18258 (goto-char (point-min))
18259 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18260 (while (re-search-forward re nil t)
18261 (when (save-match-data (org-in-commented-heading-p t))
18262 (add-text-properties
18263 (match-beginning 0) (org-end-of-subtree t) pc)))))
18264 (goto-char pos)))))
18265 (setq org-todo-keywords-for-agenda
18266 (org-uniquify org-todo-keywords-for-agenda))
18267 (setq org-todo-keyword-alist-for-agenda
18268 (org-uniquify org-todo-keyword-alist-for-agenda))))
18271 ;;;; CDLaTeX minor mode
18273 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18274 "Keymap for the minor `org-cdlatex-mode'.")
18276 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18277 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18278 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18279 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18280 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18282 (defvar org-cdlatex-texmathp-advice-is-done nil
18283 "Flag remembering if we have applied the advice to texmathp already.")
18285 (define-minor-mode org-cdlatex-mode
18286 "Toggle the minor `org-cdlatex-mode'.
18287 This mode supports entering LaTeX environment and math in LaTeX fragments
18288 in Org-mode.
18289 \\{org-cdlatex-mode-map}"
18290 nil " OCDL" nil
18291 (when org-cdlatex-mode
18292 (require 'cdlatex)
18293 (run-hooks 'cdlatex-mode-hook)
18294 (cdlatex-compute-tables))
18295 (unless org-cdlatex-texmathp-advice-is-done
18296 (setq org-cdlatex-texmathp-advice-is-done t)
18297 (defadvice texmathp (around org-math-always-on activate)
18298 "Always return t in org-mode buffers.
18299 This is because we want to insert math symbols without dollars even outside
18300 the LaTeX math segments. If Orgmode thinks that point is actually inside
18301 an embedded LaTeX fragment, let texmathp do its job.
18302 \\[org-cdlatex-mode-map]"
18303 (interactive)
18304 (let (p)
18305 (cond
18306 ((not (derived-mode-p 'org-mode)) ad-do-it)
18307 ((eq this-command 'cdlatex-math-symbol)
18308 (setq ad-return-value t
18309 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18311 (let ((p (org-inside-LaTeX-fragment-p)))
18312 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18313 (setq ad-return-value t
18314 texmathp-why '("Org-mode embedded math" . 0))
18315 (if p ad-do-it)))))))))
18317 (defun turn-on-org-cdlatex ()
18318 "Unconditionally turn on `org-cdlatex-mode'."
18319 (org-cdlatex-mode 1))
18321 (defun org-try-cdlatex-tab ()
18322 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18323 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18324 - inside a LaTeX fragment, or
18325 - after the first word in a line, where an abbreviation expansion could
18326 insert a LaTeX environment."
18327 (when org-cdlatex-mode
18328 (cond
18329 ;; Before any word on the line: No expansion possible.
18330 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18331 ;; Just after first word on the line: Expand it. Make sure it
18332 ;; cannot happen on headlines, though.
18333 ((save-excursion
18334 (skip-chars-backward "a-zA-Z0-9*")
18335 (skip-chars-backward " \t")
18336 (and (bolp) (not (org-at-heading-p))))
18337 (cdlatex-tab) t)
18338 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18340 (defun org-cdlatex-underscore-caret (&optional arg)
18341 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18342 Revert to the normal definition outside of these fragments."
18343 (interactive "P")
18344 (if (org-inside-LaTeX-fragment-p)
18345 (call-interactively 'cdlatex-sub-superscript)
18346 (let (org-cdlatex-mode)
18347 (call-interactively (key-binding (vector last-input-event))))))
18349 (defun org-cdlatex-math-modify (&optional arg)
18350 "Execute `cdlatex-math-modify' in LaTeX fragments.
18351 Revert to the normal definition outside of these fragments."
18352 (interactive "P")
18353 (if (org-inside-LaTeX-fragment-p)
18354 (call-interactively 'cdlatex-math-modify)
18355 (let (org-cdlatex-mode)
18356 (call-interactively (key-binding (vector last-input-event))))))
18360 ;;;; LaTeX fragments
18362 (defun org-inside-LaTeX-fragment-p ()
18363 "Test if point is inside a LaTeX fragment.
18364 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18365 sequence appearing also before point.
18366 Even though the matchers for math are configurable, this function assumes
18367 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18368 delimiters are skipped when they have been removed by customization.
18369 The return value is nil, or a cons cell with the delimiter and the
18370 position of this delimiter.
18372 This function does a reasonably good job, but can locally be fooled by
18373 for example currency specifications. For example it will assume being in
18374 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18375 fragments that are properly closed, but during editing, we have to live
18376 with the uncertainty caused by missing closing delimiters. This function
18377 looks only before point, not after."
18378 (catch 'exit
18379 (let ((pos (point))
18380 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18381 (lim (progn
18382 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18383 (point)))
18384 dd-on str (start 0) m re)
18385 (goto-char pos)
18386 (when dodollar
18387 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18388 re (nth 1 (assoc "$" org-latex-regexps)))
18389 (while (string-match re str start)
18390 (cond
18391 ((= (match-end 0) (length str))
18392 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18393 ((= (match-end 0) (- (length str) 5))
18394 (throw 'exit nil))
18395 (t (setq start (match-end 0))))))
18396 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18397 (goto-char pos)
18398 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18399 (and (match-beginning 2) (throw 'exit nil))
18400 ;; count $$
18401 (while (re-search-backward "\\$\\$" lim t)
18402 (setq dd-on (not dd-on)))
18403 (goto-char pos)
18404 (if dd-on (cons "$$" m))))))
18406 (defun org-inside-latex-macro-p ()
18407 "Is point inside a LaTeX macro or its arguments?"
18408 (save-match-data
18409 (org-in-regexp
18410 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18412 (defvar org-latex-fragment-image-overlays nil
18413 "List of overlays carrying the images of latex fragments.")
18414 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18416 (defun org-remove-latex-fragment-image-overlays ()
18417 "Remove all overlays with LaTeX fragment images in current buffer."
18418 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18419 (setq org-latex-fragment-image-overlays nil))
18421 (defun org-preview-latex-fragment (&optional subtree)
18422 "Preview the LaTeX fragment at point, or all locally or globally.
18423 If the cursor is in a LaTeX fragment, create the image and overlay
18424 it over the source code. If there is no fragment at point, display
18425 all fragments in the current text, from one headline to the next. With
18426 prefix SUBTREE, display all fragments in the current subtree. With a
18427 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18428 the cursor is before the first headline,
18429 display all fragments in the buffer.
18430 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18431 (interactive "P")
18432 (unless buffer-file-name
18433 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18434 (when (display-graphic-p)
18435 (org-remove-latex-fragment-image-overlays)
18436 (save-excursion
18437 (save-restriction
18438 (let (beg end at msg)
18439 (cond
18440 ((or (equal subtree '(16))
18441 (not (save-excursion
18442 (re-search-backward org-outline-regexp-bol nil t))))
18443 (setq beg (point-min) end (point-max)
18444 msg "Creating images for buffer...%s"))
18445 ((equal subtree '(4))
18446 (org-back-to-heading)
18447 (setq beg (point) end (org-end-of-subtree t)
18448 msg "Creating images for subtree...%s"))
18450 (if (setq at (org-inside-LaTeX-fragment-p))
18451 (goto-char (max (point-min) (- (cdr at) 2)))
18452 (org-back-to-heading))
18453 (setq beg (point) end (progn (outline-next-heading) (point))
18454 msg (if at "Creating image...%s"
18455 "Creating images for entry...%s"))))
18456 (message msg "")
18457 (narrow-to-region beg end)
18458 (goto-char beg)
18459 (org-format-latex
18460 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18461 (file-name-nondirectory
18462 buffer-file-name)))
18463 default-directory 'overlays msg at 'forbuffer
18464 org-latex-create-formula-image-program)
18465 (message msg "done. Use `C-c C-c' to remove images."))))))
18467 (defun org-format-latex (prefix &optional dir overlays msg at
18468 forbuffer processing-type)
18469 "Replace LaTeX fragments with links to an image, and produce images.
18470 Some of the options can be changed using the variable
18471 `org-format-latex-options'."
18472 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18473 (let* ((prefixnodir (file-name-nondirectory prefix))
18474 (absprefix (expand-file-name prefix dir))
18475 (todir (file-name-directory absprefix))
18476 (opt org-format-latex-options)
18477 (optnew org-format-latex-options)
18478 (matchers (plist-get opt :matchers))
18479 (re-list org-latex-regexps)
18480 (cnt 0) txt hash link beg end re e checkdir
18481 string
18482 m n block-type block linkfile movefile ov)
18483 ;; Check the different regular expressions
18484 (while (setq e (pop re-list))
18485 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18486 block (if block-type "\n\n" ""))
18487 (when (member m matchers)
18488 (goto-char (point-min))
18489 (while (re-search-forward re nil t)
18490 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18491 (or (not overlays)
18492 (not (eq (get-char-property (match-beginning n)
18493 'org-overlay-type)
18494 'org-latex-overlay))))
18495 (cond
18496 ((eq processing-type 'verbatim))
18497 ((eq processing-type 'mathjax)
18498 ;; Prepare for MathJax processing.
18499 (setq string (match-string n))
18500 (when (member m '("$" "$1"))
18501 (save-excursion
18502 (delete-region (match-beginning n) (match-end n))
18503 (goto-char (match-beginning n))
18504 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18505 ((or (eq processing-type 'dvipng)
18506 (eq processing-type 'imagemagick))
18507 ;; Process to an image.
18508 (setq txt (match-string n)
18509 beg (match-beginning n) end (match-end n)
18510 cnt (1+ cnt))
18511 (let ((face (face-at-point))
18512 (fg (plist-get opt :foreground))
18513 (bg (plist-get opt :background))
18514 ;; Ensure full list is printed.
18515 print-length print-level)
18516 (when forbuffer
18517 ;; Get the colors from the face at point.
18518 (goto-char beg)
18519 (when (eq fg 'auto)
18520 (setq fg (face-attribute face :foreground nil 'default)))
18521 (when (eq bg 'auto)
18522 (setq bg (face-attribute face :background nil 'default)))
18523 (setq optnew (copy-sequence opt))
18524 (plist-put optnew :foreground fg)
18525 (plist-put optnew :background bg))
18526 (setq hash (sha1 (prin1-to-string
18527 (list org-format-latex-header
18528 org-latex-default-packages-alist
18529 org-latex-packages-alist
18530 org-format-latex-options
18531 forbuffer txt fg bg)))
18532 linkfile (format "%s_%s.png" prefix hash)
18533 movefile (format "%s_%s.png" absprefix hash)))
18534 (setq link (concat block "[[file:" linkfile "]]" block))
18535 (if msg (message msg cnt))
18536 (goto-char beg)
18537 (unless checkdir ; Ensure the directory exists.
18538 (setq checkdir t)
18539 (or (file-directory-p todir) (make-directory todir t)))
18540 (unless (file-exists-p movefile)
18541 (org-create-formula-image
18542 txt movefile optnew forbuffer processing-type))
18543 (if overlays
18544 (progn
18545 (mapc (lambda (o)
18546 (if (eq (overlay-get o 'org-overlay-type)
18547 'org-latex-overlay)
18548 (delete-overlay o)))
18549 (overlays-in beg end))
18550 (setq ov (make-overlay beg end))
18551 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18552 (if (featurep 'xemacs)
18553 (progn
18554 (overlay-put ov 'invisible t)
18555 (overlay-put
18556 ov 'end-glyph
18557 (make-glyph (vector 'png :file movefile))))
18558 (overlay-put
18559 ov 'display
18560 (list 'image :type 'png :file movefile :ascent 'center)))
18561 (push ov org-latex-fragment-image-overlays)
18562 (goto-char end))
18563 (delete-region beg end)
18564 (insert (org-add-props link
18565 (list 'org-latex-src
18566 (replace-regexp-in-string
18567 "\"" "" txt)
18568 'org-latex-src-embed-type
18569 (if block-type 'paragraph 'character))))))
18570 ((eq processing-type 'mathml)
18571 ;; Process to MathML
18572 (unless (save-match-data (org-format-latex-mathml-available-p))
18573 (user-error "LaTeX to MathML converter not configured"))
18574 (setq txt (match-string n)
18575 beg (match-beginning n) end (match-end n)
18576 cnt (1+ cnt))
18577 (if msg (message msg cnt))
18578 (goto-char beg)
18579 (delete-region beg end)
18580 (insert (org-format-latex-as-mathml
18581 txt block-type prefix dir)))
18583 (error "Unknown conversion type %s for LaTeX fragments"
18584 processing-type)))))))))
18586 (defun org-create-math-formula (latex-frag &optional mathml-file)
18587 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18588 Use `org-latex-to-mathml-convert-command'. If the conversion is
18589 sucessful, return the portion between \"<math...> </math>\"
18590 elements otherwise return nil. When MATHML-FILE is specified,
18591 write the results in to that file. When invoked as an
18592 interactive command, prompt for LATEX-FRAG, with initial value
18593 set to the current active region and echo the results for user
18594 inspection."
18595 (interactive (list (let ((frag (when (org-region-active-p)
18596 (buffer-substring-no-properties
18597 (region-beginning) (region-end)))))
18598 (read-string "LaTeX Fragment: " frag nil frag))))
18599 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18600 (let* ((tmp-in-file (file-relative-name
18601 (make-temp-name (expand-file-name "ltxmathml-in"))))
18602 (ignore (write-region latex-frag nil tmp-in-file))
18603 (tmp-out-file (file-relative-name
18604 (make-temp-name (expand-file-name "ltxmathml-out"))))
18605 (cmd (format-spec
18606 org-latex-to-mathml-convert-command
18607 `((?j . ,(shell-quote-argument
18608 (expand-file-name org-latex-to-mathml-jar-file)))
18609 (?I . ,(shell-quote-argument tmp-in-file))
18610 (?o . ,(shell-quote-argument tmp-out-file)))))
18611 mathml shell-command-output)
18612 (when (org-called-interactively-p 'any)
18613 (unless (org-format-latex-mathml-available-p)
18614 (user-error "LaTeX to MathML converter not configured")))
18615 (message "Running %s" cmd)
18616 (setq shell-command-output (shell-command-to-string cmd))
18617 (setq mathml
18618 (when (file-readable-p tmp-out-file)
18619 (with-current-buffer (find-file-noselect tmp-out-file t)
18620 (goto-char (point-min))
18621 (when (re-search-forward
18622 (concat
18623 (regexp-quote
18624 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18625 "\\(.\\|\n\\)*"
18626 (regexp-quote "</math>")) nil t)
18627 (prog1 (match-string 0) (kill-buffer))))))
18628 (cond
18629 (mathml
18630 (setq mathml
18631 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18632 (when mathml-file
18633 (write-region mathml nil mathml-file))
18634 (when (org-called-interactively-p 'any)
18635 (message mathml)))
18636 ((message "LaTeX to MathML conversion failed")
18637 (message shell-command-output)))
18638 (delete-file tmp-in-file)
18639 (when (file-exists-p tmp-out-file)
18640 (delete-file tmp-out-file))
18641 mathml))
18643 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18644 prefix &optional dir)
18645 "Use `org-create-math-formula' but check local cache first."
18646 (let* ((absprefix (expand-file-name prefix dir))
18647 (print-length nil) (print-level nil)
18648 (formula-id (concat
18649 "formula-"
18650 (sha1
18651 (prin1-to-string
18652 (list latex-frag
18653 org-latex-to-mathml-convert-command)))))
18654 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18655 (formula-cache-dir (file-name-directory formula-cache)))
18657 (unless (file-directory-p formula-cache-dir)
18658 (make-directory formula-cache-dir t))
18660 (unless (file-exists-p formula-cache)
18661 (org-create-math-formula latex-frag formula-cache))
18663 (if (file-exists-p formula-cache)
18664 ;; Successful conversion. Return the link to MathML file.
18665 (org-add-props
18666 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18667 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18668 'org-latex-src-embed-type (if latex-frag-type
18669 'paragraph 'character)))
18670 ;; Failed conversion. Return the LaTeX fragment verbatim
18671 latex-frag)))
18673 (defun org-create-formula-image (string tofile options buffer &optional type)
18674 "Create an image from LaTeX source using dvipng or convert.
18675 This function calls either `org-create-formula-image-with-dvipng'
18676 or `org-create-formula-image-with-imagemagick' depending on the
18677 value of `org-latex-create-formula-image-program' or on the value
18678 of the optional TYPE variable.
18680 Note: ultimately these two function should be combined as they
18681 share a good deal of logic."
18682 (org-check-external-command
18683 "latex" "needed to convert LaTeX fragments to images")
18684 (funcall
18685 (case (or type org-latex-create-formula-image-program)
18686 ('dvipng
18687 (org-check-external-command
18688 "dvipng" "needed to convert LaTeX fragments to images")
18689 #'org-create-formula-image-with-dvipng)
18690 ('imagemagick
18691 (org-check-external-command
18692 "convert" "you need to install imagemagick")
18693 #'org-create-formula-image-with-imagemagick)
18694 (t (error
18695 "Invalid value of `org-latex-create-formula-image-program'")))
18696 string tofile options buffer))
18698 (declare-function org-export-get-backend "ox" (name))
18699 (declare-function org-export--get-global-options "ox" (&optional backend))
18700 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18701 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18702 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18703 (defun org-create-formula--latex-header ()
18704 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18705 (let ((info (org-combine-plists (org-export--get-global-options
18706 (org-export-get-backend 'latex))
18707 (org-export--get-inbuffer-options
18708 (org-export-get-backend 'latex)))))
18709 (org-latex-guess-babel-language
18710 (org-latex-guess-inputenc
18711 (org-splice-latex-header
18712 org-format-latex-header
18713 org-latex-default-packages-alist
18714 org-latex-packages-alist t
18715 (plist-get info :latex-header)))
18716 info)))
18718 ;; This function borrows from Ganesh Swami's latex2png.el
18719 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18720 "This calls dvipng."
18721 (require 'ox-latex)
18722 (let* ((tmpdir (if (featurep 'xemacs)
18723 (temp-directory)
18724 temporary-file-directory))
18725 (texfilebase (make-temp-name
18726 (expand-file-name "orgtex" tmpdir)))
18727 (texfile (concat texfilebase ".tex"))
18728 (dvifile (concat texfilebase ".dvi"))
18729 (pngfile (concat texfilebase ".png"))
18730 (fnh (if (featurep 'xemacs)
18731 (font-height (face-font 'default))
18732 (face-attribute 'default :height nil)))
18733 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18734 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18735 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18736 "Black"))
18737 (bg (or (plist-get options (if buffer :background :html-background))
18738 "Transparent")))
18739 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18740 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18741 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18742 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18743 (let ((latex-header (org-create-formula--latex-header)))
18744 (with-temp-file texfile
18745 (insert latex-header)
18746 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18747 (let ((dir default-directory))
18748 (condition-case nil
18749 (progn
18750 (cd tmpdir)
18751 (call-process "latex" nil nil nil texfile))
18752 (error nil))
18753 (cd dir))
18754 (if (not (file-exists-p dvifile))
18755 (progn (message "Failed to create dvi file from %s" texfile) nil)
18756 (condition-case nil
18757 (if (featurep 'xemacs)
18758 (call-process "dvipng" nil nil nil
18759 "-fg" fg "-bg" bg
18760 "-T" "tight"
18761 "-o" pngfile
18762 dvifile)
18763 (call-process "dvipng" nil nil nil
18764 "-fg" fg "-bg" bg
18765 "-D" dpi
18766 ;;"-x" scale "-y" scale
18767 "-T" "tight"
18768 "-o" pngfile
18769 dvifile))
18770 (error nil))
18771 (if (not (file-exists-p pngfile))
18772 (if org-format-latex-signal-error
18773 (error "Failed to create png file from %s" texfile)
18774 (message "Failed to create png file from %s" texfile)
18775 nil)
18776 ;; Use the requested file name and clean up
18777 (copy-file pngfile tofile 'replace)
18778 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18779 (if (file-exists-p (concat texfilebase e))
18780 (delete-file (concat texfilebase e))))
18781 pngfile))))
18783 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18784 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18785 "This calls convert, which is included into imagemagick."
18786 (require 'ox-latex)
18787 (let* ((tmpdir (if (featurep 'xemacs)
18788 (temp-directory)
18789 temporary-file-directory))
18790 (texfilebase (make-temp-name
18791 (expand-file-name "orgtex" tmpdir)))
18792 (texfile (concat texfilebase ".tex"))
18793 (pdffile (concat texfilebase ".pdf"))
18794 (pngfile (concat texfilebase ".png"))
18795 (fnh (if (featurep 'xemacs)
18796 (font-height (face-font 'default))
18797 (face-attribute 'default :height nil)))
18798 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18799 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18800 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18801 "black"))
18802 (bg (or (plist-get options (if buffer :background :html-background))
18803 "white")))
18804 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18805 (setq fg (org-latex-color-format fg)))
18806 (if (eq bg 'default) (setq bg (org-latex-color :background))
18807 (setq bg (org-latex-color-format
18808 (if (string= bg "Transparent") "white" bg))))
18809 (let ((latex-header (org-create-formula--latex-header)))
18810 (with-temp-file texfile
18811 (insert latex-header)
18812 (insert "\n\\begin{document}\n"
18813 "\\definecolor{fg}{rgb}{" fg "}\n"
18814 "\\definecolor{bg}{rgb}{" bg "}\n"
18815 "\n\\pagecolor{bg}\n"
18816 "\n{\\color{fg}\n"
18817 string
18818 "\n}\n"
18819 "\n\\end{document}\n")))
18820 (org-latex-compile texfile t)
18821 (if (not (file-exists-p pdffile))
18822 (progn (message "Failed to create pdf file from %s" texfile) nil)
18823 (condition-case nil
18824 (if (featurep 'xemacs)
18825 (call-process "convert" nil nil nil
18826 "-density" "96"
18827 "-trim"
18828 "-antialias"
18829 pdffile
18830 "-quality" "100"
18831 ;; "-sharpen" "0x1.0"
18832 pngfile)
18833 (call-process "convert" nil nil nil
18834 "-density" dpi
18835 "-trim"
18836 "-antialias"
18837 pdffile
18838 "-quality" "100"
18839 ;; "-sharpen" "0x1.0"
18840 pngfile))
18841 (error nil))
18842 (if (not (file-exists-p pngfile))
18843 (if org-format-latex-signal-error
18844 (error "Failed to create png file from %s" texfile)
18845 (message "Failed to create png file from %s" texfile)
18846 nil)
18847 ;; Use the requested file name and clean up
18848 (copy-file pngfile tofile 'replace)
18849 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18850 (if (file-exists-p (concat texfilebase e))
18851 (delete-file (concat texfilebase e))))
18852 pngfile))))
18854 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18855 "Fill a LaTeX header template TPL.
18856 In the template, the following place holders will be recognized:
18858 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18859 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18860 [PACKAGES] \\usepackage statements for PKG
18861 [NO-PACKAGES] do not include PKG
18862 [EXTRA] the string EXTRA
18863 [NO-EXTRA] do not include EXTRA
18865 For backward compatibility, if both the positive and the negative place
18866 holder is missing, the positive one (without the \"NO-\") will be
18867 assumed to be present at the end of the template.
18868 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18869 EXTRA is a string.
18870 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18871 (let (rpl (end ""))
18872 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18873 (setq rpl (if (or (match-end 1) (not def-pkg))
18874 "" (org-latex-packages-to-string def-pkg snippets-p t))
18875 tpl (replace-match rpl t t tpl))
18876 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18878 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18879 (setq rpl (if (or (match-end 1) (not pkg))
18880 "" (org-latex-packages-to-string pkg snippets-p t))
18881 tpl (replace-match rpl t t tpl))
18882 (if pkg (setq end
18883 (concat end "\n"
18884 (org-latex-packages-to-string pkg snippets-p)))))
18886 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18887 (setq rpl (if (or (match-end 1) (not extra))
18888 "" (concat extra "\n"))
18889 tpl (replace-match rpl t t tpl))
18890 (if (and extra (string-match "\\S-" extra))
18891 (setq end (concat end "\n" extra))))
18893 (if (string-match "\\S-" end)
18894 (concat tpl "\n" end)
18895 tpl)))
18897 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18898 "Turn an alist of packages into a string with the \\usepackage macros."
18899 (setq pkg (mapconcat (lambda(p)
18900 (cond
18901 ((stringp p) p)
18902 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18903 (format "%% Package %s omitted" (cadr p)))
18904 ((equal "" (car p))
18905 (format "\\usepackage{%s}" (cadr p)))
18907 (format "\\usepackage[%s]{%s}"
18908 (car p) (cadr p)))))
18910 "\n"))
18911 (if newline (concat pkg "\n") pkg))
18913 (defun org-dvipng-color (attr)
18914 "Return a RGB color specification for dvipng."
18915 (apply 'format "rgb %s %s %s"
18916 (mapcar 'org-normalize-color
18917 (if (featurep 'xemacs)
18918 (color-rgb-components
18919 (face-property 'default
18920 (cond ((eq attr :foreground) 'foreground)
18921 ((eq attr :background) 'background))))
18922 (color-values (face-attribute 'default attr nil))))))
18924 (defun org-dvipng-color-format (color-name)
18925 "Convert COLOR-NAME to a RGB color value for dvipng."
18926 (apply 'format "rgb %s %s %s"
18927 (mapcar 'org-normalize-color
18928 (color-values color-name))))
18930 (defun org-latex-color (attr)
18931 "Return a RGB color for the LaTeX color package."
18932 (apply 'format "%s,%s,%s"
18933 (mapcar 'org-normalize-color
18934 (if (featurep 'xemacs)
18935 (color-rgb-components
18936 (face-property 'default
18937 (cond ((eq attr :foreground) 'foreground)
18938 ((eq attr :background) 'background))))
18939 (color-values (face-attribute 'default attr nil))))))
18941 (defun org-latex-color-format (color-name)
18942 "Convert COLOR-NAME to a RGB color value."
18943 (apply 'format "%s,%s,%s"
18944 (mapcar 'org-normalize-color
18945 (color-values color-name))))
18947 (defun org-normalize-color (value)
18948 "Return string to be used as color value for an RGB component."
18949 (format "%g" (/ value 65535.0)))
18953 ;; Image display
18955 (defvar org-inline-image-overlays nil)
18956 (make-variable-buffer-local 'org-inline-image-overlays)
18958 (defun org-toggle-inline-images (&optional include-linked)
18959 "Toggle the display of inline images.
18960 INCLUDE-LINKED is passed to `org-display-inline-images'."
18961 (interactive "P")
18962 (if org-inline-image-overlays
18963 (progn
18964 (org-remove-inline-images)
18965 (message "Inline image display turned off"))
18966 (org-display-inline-images include-linked)
18967 (if (and (org-called-interactively-p)
18968 org-inline-image-overlays)
18969 (message "%d images displayed inline"
18970 (length org-inline-image-overlays))
18971 (message "No images to display inline"))))
18973 (defun org-redisplay-inline-images ()
18974 "Refresh the display of inline images."
18975 (interactive)
18976 (if (not org-inline-image-overlays)
18977 (org-toggle-inline-images)
18978 (org-toggle-inline-images)
18979 (org-toggle-inline-images)))
18981 (defun org-display-inline-images (&optional include-linked refresh beg end)
18982 "Display inline images.
18984 An inline image is a link which follows either of these
18985 conventions:
18987 1. Its path is a file with an extension matching return value
18988 from `image-file-name-regexp' and it has no contents.
18990 2. Its description consists in a single link of the previous
18991 type.
18993 When optional argument INCLUDE-LINKED is non-nil, also links with
18994 a text description part will be inlined. This can be nice for
18995 a quick look at those images, but it does not reflect what
18996 exported files will look like.
18998 When optional argument REFRESH is non-nil, refresh existing
18999 images between BEG and END. This will create new image displays
19000 only if necessary. BEG and END default to the buffer
19001 boundaries."
19002 (interactive "P")
19003 (when (display-graphic-p)
19004 (unless refresh
19005 (org-remove-inline-images)
19006 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19007 (org-with-wide-buffer
19008 (goto-char (or beg (point-min)))
19009 (let ((case-fold-search t)
19010 (file-extension-re (org-image-file-name-regexp)))
19011 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19012 (let ((link (save-match-data (org-element-context))))
19013 ;; Check if we're at an inline image.
19014 (when (and (equal (org-element-property :type link) "file")
19015 (or include-linked
19016 (not (org-element-property :contents-begin link)))
19017 (let ((parent (org-element-property :parent link)))
19018 (or (not (eq (org-element-type parent) 'link))
19019 (not (cdr (org-element-contents parent)))))
19020 (org-string-match-p file-extension-re
19021 (org-element-property :path link)))
19022 (let ((file (expand-file-name (org-element-property :path link))))
19023 (when (file-exists-p file)
19024 (let ((width
19025 ;; Apply `org-image-actual-width' specifications.
19026 (cond
19027 ((not (image-type-available-p 'imagemagick)) nil)
19028 ((eq org-image-actual-width t) nil)
19029 ((listp org-image-actual-width)
19031 ;; First try to find a width among
19032 ;; attributes associated to the paragraph
19033 ;; containing link.
19034 (let ((paragraph
19035 (let ((e link))
19036 (while (and (setq e (org-element-property
19037 :parent e))
19038 (not (eq (org-element-type e)
19039 'paragraph))))
19040 e)))
19041 (when paragraph
19042 (save-excursion
19043 (goto-char (org-element-property :begin paragraph))
19044 (when (save-match-data
19045 (re-search-forward
19046 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19047 (org-element-property
19048 :post-affiliated paragraph)
19050 (string-to-number (match-string 1))))))
19051 ;; Otherwise, fall-back to provided number.
19052 (car org-image-actual-width)))
19053 ((numberp org-image-actual-width)
19054 org-image-actual-width)))
19055 (old (get-char-property-and-overlay
19056 (org-element-property :begin link)
19057 'org-image-overlay)))
19058 (if (and (car-safe old) refresh)
19059 (image-refresh (overlay-get (cdr old) 'display))
19060 (let ((image (save-match-data
19061 (create-image file
19062 (and width 'imagemagick)
19064 :width width))))
19065 (when image
19066 (let* ((link
19067 ;; If inline image is the description
19068 ;; of another link, be sure to
19069 ;; consider the latter as the one to
19070 ;; apply the overlay on.
19071 (let ((parent
19072 (org-element-property :parent link)))
19073 (if (eq (org-element-type parent) 'link)
19074 parent
19075 link)))
19076 (ov (make-overlay
19077 (org-element-property :begin link)
19078 (progn
19079 (goto-char
19080 (org-element-property :end link))
19081 (skip-chars-backward " \t")
19082 (point)))))
19083 (overlay-put ov 'display image)
19084 (overlay-put ov 'face 'default)
19085 (overlay-put ov 'org-image-overlay t)
19086 (overlay-put
19087 ov 'modification-hooks
19088 (list 'org-display-inline-remove-overlay))
19089 (push ov org-inline-image-overlays)))))))))))))))
19091 (define-obsolete-function-alias
19092 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19094 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19095 "Remove inline-display overlay if a corresponding region is modified."
19096 (let ((inhibit-modification-hooks t))
19097 (when (and ov after)
19098 (delete ov org-inline-image-overlays)
19099 (delete-overlay ov))))
19101 (defun org-remove-inline-images ()
19102 "Remove inline display of images."
19103 (interactive)
19104 (mapc 'delete-overlay org-inline-image-overlays)
19105 (setq org-inline-image-overlays nil))
19107 ;;;; Key bindings
19109 ;; Outline functions from `outline-mode-prefix-map'
19110 ;; that can be remapped in Org:
19111 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19112 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19113 (define-key org-mode-map [remap outline-forward-same-level]
19114 'org-forward-heading-same-level)
19115 (define-key org-mode-map [remap outline-backward-same-level]
19116 'org-backward-heading-same-level)
19117 (define-key org-mode-map [remap show-branches]
19118 'org-kill-note-or-show-branches)
19119 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19120 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19121 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19123 ;; Outline functions from `outline-mode-prefix-map' that can not
19124 ;; be remapped in Org:
19126 ;; - the column "key binding" shows whether the Outline function is still
19127 ;; available in Org mode on the same key that it has been bound to in
19128 ;; Outline mode:
19129 ;; - "overridden": key used for a different functionality in Org mode
19130 ;; - else: key still bound to the same Outline function in Org mode
19132 ;; | Outline function | key binding | Org replacement |
19133 ;; |------------------------------------+-------------+-----------------------|
19134 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19135 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19136 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19137 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19138 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19139 ;; | `show-entry' | overridden | no replacement |
19140 ;; | `show-children' | `C-c C-i' | visibility cycling |
19141 ;; | `show-branches' | `C-c C-k' | still same function |
19142 ;; | `show-subtree' | overridden | visibility cycling |
19143 ;; | `show-all' | overridden | no replacement |
19144 ;; | `hide-subtree' | overridden | visibility cycling |
19145 ;; | `hide-body' | overridden | no replacement |
19146 ;; | `hide-entry' | overridden | visibility cycling |
19147 ;; | `hide-leaves' | overridden | no replacement |
19148 ;; | `hide-sublevels' | overridden | no replacement |
19149 ;; | `hide-other' | overridden | no replacement |
19151 ;; Make `C-c C-x' a prefix key
19152 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19154 ;; TAB key with modifiers
19155 (org-defkey org-mode-map "\C-i" 'org-cycle)
19156 (org-defkey org-mode-map [(tab)] 'org-cycle)
19157 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19158 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19159 ;; The following line is necessary under Suse GNU/Linux
19160 (unless (featurep 'xemacs)
19161 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19162 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19163 (define-key org-mode-map [backtab] 'org-shifttab)
19165 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19166 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19167 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19169 ;; Cursor keys with modifiers
19170 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19171 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19172 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19173 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19175 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19176 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19177 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19178 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19180 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19181 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19182 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19183 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19185 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19186 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19187 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19188 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19190 ;; Babel keys
19191 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19192 (mapc (lambda (pair)
19193 (define-key org-babel-map (car pair) (cdr pair)))
19194 org-babel-key-bindings)
19196 ;;; Extra keys for tty access.
19197 ;; We only set them when really needed because otherwise the
19198 ;; menus don't show the simple keys
19200 (when (or org-use-extra-keys
19201 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19202 (not window-system))
19203 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19204 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19205 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19206 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19207 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19208 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19209 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19210 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19211 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19212 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19213 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19214 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19215 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19216 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19217 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19218 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19219 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19220 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19221 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19222 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19223 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19224 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19225 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19226 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19227 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19228 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19229 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19230 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19232 ;; All the other keys
19234 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19235 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19236 (if (boundp 'narrow-map)
19237 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19238 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19239 (if (boundp 'narrow-map)
19240 (org-defkey narrow-map "b" 'org-narrow-to-block)
19241 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19242 (if (boundp 'narrow-map)
19243 (org-defkey narrow-map "e" 'org-narrow-to-element)
19244 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19245 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19246 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19247 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19248 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19249 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19250 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19251 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19252 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19253 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19254 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19255 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19256 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19257 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19258 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19259 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19260 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19261 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19262 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19263 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19264 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19265 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19266 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19267 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19268 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19269 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19270 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19271 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19272 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19273 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19274 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19275 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19276 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19277 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19278 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19279 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19280 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19281 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19282 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19283 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19284 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19285 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19286 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19287 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19288 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19289 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19290 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19291 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19292 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19293 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19294 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19295 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19296 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19297 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19298 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19299 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19300 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19301 (org-defkey org-mode-map "\C-c^" 'org-sort)
19302 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19303 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19304 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19305 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19306 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19307 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19308 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19309 (org-defkey org-mode-map "\C-m" 'org-return)
19310 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19311 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19312 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19313 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19314 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19315 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19316 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19317 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19318 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19319 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19320 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19321 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19322 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19323 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19324 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19325 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19326 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19327 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19328 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19329 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19330 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19331 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19332 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19334 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19335 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19336 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19338 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19339 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19340 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19341 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19342 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19343 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19344 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19345 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19346 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19347 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19348 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19349 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19350 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19351 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19352 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19353 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19354 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19355 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19356 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19357 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19358 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19359 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19360 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19362 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19363 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19364 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19365 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19366 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19368 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19370 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19372 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19373 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19375 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19378 (when (featurep 'xemacs)
19379 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19382 (defconst org-speed-commands-default
19384 ("Outline Navigation")
19385 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19386 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19387 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19388 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19389 ("F" . org-next-block)
19390 ("B" . org-previous-block)
19391 ("u" . (org-speed-move-safe 'outline-up-heading))
19392 ("j" . org-goto)
19393 ("g" . (org-refile t))
19394 ("Outline Visibility")
19395 ("c" . org-cycle)
19396 ("C" . org-shifttab)
19397 (" " . org-display-outline-path)
19398 ("s" . org-narrow-to-subtree)
19399 ("=" . org-columns)
19400 ("Outline Structure Editing")
19401 ("U" . org-shiftmetaup)
19402 ("D" . org-shiftmetadown)
19403 ("r" . org-metaright)
19404 ("l" . org-metaleft)
19405 ("R" . org-shiftmetaright)
19406 ("L" . org-shiftmetaleft)
19407 ("i" . (progn (forward-char 1) (call-interactively
19408 'org-insert-heading-respect-content)))
19409 ("^" . org-sort)
19410 ("w" . org-refile)
19411 ("a" . org-archive-subtree-default-with-confirmation)
19412 ("@" . org-mark-subtree)
19413 ("#" . org-toggle-comment)
19414 ("Clock Commands")
19415 ("I" . org-clock-in)
19416 ("O" . org-clock-out)
19417 ("Meta Data Editing")
19418 ("t" . org-todo)
19419 ("," . (org-priority))
19420 ("0" . (org-priority ?\ ))
19421 ("1" . (org-priority ?A))
19422 ("2" . (org-priority ?B))
19423 ("3" . (org-priority ?C))
19424 (":" . org-set-tags-command)
19425 ("e" . org-set-effort)
19426 ("E" . org-inc-effort)
19427 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19428 (org-entry-put (point) "APPT_WARNTIME" m)))
19429 ("Agenda Views etc")
19430 ("v" . org-agenda)
19431 ("/" . org-sparse-tree)
19432 ("Misc")
19433 ("o" . org-open-at-point)
19434 ("?" . org-speed-command-help)
19435 ("<" . (org-agenda-set-restriction-lock 'subtree))
19436 (">" . (org-agenda-remove-restriction-lock))
19438 "The default speed commands.")
19440 (defun org-print-speed-command (e)
19441 (if (> (length (car e)) 1)
19442 (progn
19443 (princ "\n")
19444 (princ (car e))
19445 (princ "\n")
19446 (princ (make-string (length (car e)) ?-))
19447 (princ "\n"))
19448 (princ (car e))
19449 (princ " ")
19450 (if (symbolp (cdr e))
19451 (princ (symbol-name (cdr e)))
19452 (prin1 (cdr e)))
19453 (princ "\n")))
19455 (defun org-speed-command-help ()
19456 "Show the available speed commands."
19457 (interactive)
19458 (if (not org-use-speed-commands)
19459 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19460 (with-output-to-temp-buffer "*Help*"
19461 (princ "User-defined Speed commands\n===========================\n")
19462 (mapc 'org-print-speed-command org-speed-commands-user)
19463 (princ "\n")
19464 (princ "Built-in Speed commands\n=======================\n")
19465 (mapc 'org-print-speed-command org-speed-commands-default))
19466 (with-current-buffer "*Help*"
19467 (setq truncate-lines t))))
19469 (defun org-speed-move-safe (cmd)
19470 "Execute CMD, but make sure that the cursor always ends up in a headline.
19471 If not, return to the original position and throw an error."
19472 (interactive)
19473 (let ((pos (point)))
19474 (call-interactively cmd)
19475 (unless (and (bolp) (org-at-heading-p))
19476 (goto-char pos)
19477 (error "Boundary reached while executing %s" cmd))))
19479 (defvar org-self-insert-command-undo-counter 0)
19481 (defvar org-table-auto-blank-field) ; defined in org-table.el
19482 (defvar org-speed-command nil)
19484 (define-obsolete-function-alias
19485 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19487 (defun org-speed-command-activate (keys)
19488 "Hook for activating single-letter speed commands.
19489 `org-speed-commands-default' specifies a minimal command set.
19490 Use `org-speed-commands-user' for further customization."
19491 (when (or (and (bolp) (looking-at org-outline-regexp))
19492 (and (functionp org-use-speed-commands)
19493 (funcall org-use-speed-commands)))
19494 (cdr (assoc keys (append org-speed-commands-user
19495 org-speed-commands-default)))))
19497 (define-obsolete-function-alias
19498 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19500 (defun org-babel-speed-command-activate (keys)
19501 "Hook for activating single-letter code block commands."
19502 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19503 (cdr (assoc keys org-babel-key-bindings))))
19505 (defcustom org-speed-command-hook
19506 '(org-speed-command-default-hook org-babel-speed-command-hook)
19507 "Hook for activating speed commands at strategic locations.
19508 Hook functions are called in sequence until a valid handler is
19509 found.
19511 Each hook takes a single argument, a user-pressed command key
19512 which is also a `self-insert-command' from the global map.
19514 Within the hook, examine the cursor position and the command key
19515 and return nil or a valid handler as appropriate. Handler could
19516 be one of an interactive command, a function, or a form.
19518 Set `org-use-speed-commands' to non-nil value to enable this
19519 hook. The default setting is `org-speed-command-activate'."
19520 :group 'org-structure
19521 :version "24.1"
19522 :type 'hook)
19524 (defun org-self-insert-command (N)
19525 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19526 If the cursor is in a table looking at whitespace, the whitespace is
19527 overwritten, and the table is not marked as requiring realignment."
19528 (interactive "p")
19529 (org-check-before-invisible-edit 'insert)
19530 (cond
19531 ((and org-use-speed-commands
19532 (setq org-speed-command
19533 (run-hook-with-args-until-success
19534 'org-speed-command-hook (this-command-keys))))
19535 (cond
19536 ((commandp org-speed-command)
19537 (setq this-command org-speed-command)
19538 (call-interactively org-speed-command))
19539 ((functionp org-speed-command)
19540 (funcall org-speed-command))
19541 ((and org-speed-command (listp org-speed-command))
19542 (eval org-speed-command))
19543 (t (let (org-use-speed-commands)
19544 (call-interactively 'org-self-insert-command)))))
19545 ((and
19546 (org-table-p)
19547 (progn
19548 ;; check if we blank the field, and if that triggers align
19549 (and (featurep 'org-table) org-table-auto-blank-field
19550 (member last-command
19551 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19552 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19553 ;; got extra space, this field does not determine column width
19554 (let (org-table-may-need-update) (org-table-blank-field))
19555 ;; no extra space, this field may determine column width
19556 (org-table-blank-field)))
19558 (eq N 1)
19559 (looking-at "[^|\n]* |"))
19560 (let (org-table-may-need-update)
19561 (goto-char (1- (match-end 0)))
19562 (backward-delete-char 1)
19563 (goto-char (match-beginning 0))
19564 (self-insert-command N)))
19566 (setq org-table-may-need-update t)
19567 (self-insert-command N)
19568 (org-fix-tags-on-the-fly)
19569 (if org-self-insert-cluster-for-undo
19570 (if (not (eq last-command 'org-self-insert-command))
19571 (setq org-self-insert-command-undo-counter 1)
19572 (if (>= org-self-insert-command-undo-counter 20)
19573 (setq org-self-insert-command-undo-counter 1)
19574 (and (> org-self-insert-command-undo-counter 0)
19575 buffer-undo-list (listp buffer-undo-list)
19576 (not (cadr buffer-undo-list)) ; remove nil entry
19577 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19578 (setq org-self-insert-command-undo-counter
19579 (1+ org-self-insert-command-undo-counter))))))))
19581 (defun org-check-before-invisible-edit (kind)
19582 "Check is editing if kind KIND would be dangerous with invisible text around.
19583 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19584 ;; First, try to get out of here as quickly as possible, to reduce overhead
19585 (if (and org-catch-invisible-edits
19586 (or (not (boundp 'visible-mode)) (not visible-mode))
19587 (or (get-char-property (point) 'invisible)
19588 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19589 ;; OK, we need to take a closer look
19590 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19591 (invisible-before-point (if (bobp) nil (get-char-property
19592 (1- (point)) 'invisible)))
19593 (border-and-ok-direction
19595 ;; Check if we are acting predictably before invisible text
19596 (and invisible-at-point (not invisible-before-point)
19597 (memq kind '(insert delete-backward)))
19598 ;; Check if we are acting predictably after invisible text
19599 ;; This works not well, and I have turned it off. It seems
19600 ;; better to always show and stop after invisible text.
19601 ;; (and (not invisible-at-point) invisible-before-point
19602 ;; (memq kind '(insert delete)))
19604 (when (or (memq invisible-at-point '(outline org-hide-block t))
19605 (memq invisible-before-point '(outline org-hide-block t)))
19606 (if (eq org-catch-invisible-edits 'error)
19607 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19608 (if (and org-custom-properties-overlays
19609 (y-or-n-p "Display invisible properties in this buffer? "))
19610 (org-toggle-custom-properties-visibility)
19611 ;; Make the area visible
19612 (save-excursion
19613 (if invisible-before-point
19614 (goto-char (previous-single-char-property-change
19615 (point) 'invisible)))
19616 (show-subtree))
19617 (cond
19618 ((eq org-catch-invisible-edits 'show)
19619 ;; That's it, we do the edit after showing
19620 (message
19621 "Unfolding invisible region around point before editing")
19622 (sit-for 1))
19623 ((and (eq org-catch-invisible-edits 'smart)
19624 border-and-ok-direction)
19625 (message "Unfolding invisible region around point before editing"))
19627 ;; Don't do the edit, make the user repeat it in full visibility
19628 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19630 (defun org-fix-tags-on-the-fly ()
19631 (when (and (equal (char-after (point-at-bol)) ?*)
19632 (org-at-heading-p))
19633 (org-align-tags-here org-tags-column)))
19635 (defun org-delete-backward-char (N)
19636 "Like `delete-backward-char', insert whitespace at field end in tables.
19637 When deleting backwards, in tables this function will insert whitespace in
19638 front of the next \"|\" separator, to keep the table aligned. The table will
19639 still be marked for re-alignment if the field did fill the entire column,
19640 because, in this case the deletion might narrow the column."
19641 (interactive "p")
19642 (save-match-data
19643 (org-check-before-invisible-edit 'delete-backward)
19644 (if (and (org-table-p)
19645 (eq N 1)
19646 (string-match "|" (buffer-substring (point-at-bol) (point)))
19647 (looking-at ".*?|"))
19648 (let ((pos (point))
19649 (noalign (looking-at "[^|\n\r]* |"))
19650 (c org-table-may-need-update))
19651 (backward-delete-char N)
19652 (if (not overwrite-mode)
19653 (progn
19654 (skip-chars-forward "^|")
19655 (insert " ")
19656 (goto-char (1- pos))))
19657 ;; noalign: if there were two spaces at the end, this field
19658 ;; does not determine the width of the column.
19659 (if noalign (setq org-table-may-need-update c)))
19660 (backward-delete-char N)
19661 (org-fix-tags-on-the-fly))))
19663 (defun org-delete-char (N)
19664 "Like `delete-char', but insert whitespace at field end in tables.
19665 When deleting characters, in tables this function will insert whitespace in
19666 front of the next \"|\" separator, to keep the table aligned. The table will
19667 still be marked for re-alignment if the field did fill the entire column,
19668 because, in this case the deletion might narrow the column."
19669 (interactive "p")
19670 (save-match-data
19671 (org-check-before-invisible-edit 'delete)
19672 (if (and (org-table-p)
19673 (not (bolp))
19674 (not (= (char-after) ?|))
19675 (eq N 1))
19676 (if (looking-at ".*?|")
19677 (let ((pos (point))
19678 (noalign (looking-at "[^|\n\r]* |"))
19679 (c org-table-may-need-update))
19680 (replace-match
19681 (concat (substring (match-string 0) 1 -1) " |") nil t)
19682 (goto-char pos)
19683 ;; noalign: if there were two spaces at the end, this field
19684 ;; does not determine the width of the column.
19685 (if noalign (setq org-table-may-need-update c)))
19686 (delete-char N))
19687 (delete-char N)
19688 (org-fix-tags-on-the-fly))))
19690 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19691 (put 'org-self-insert-command 'delete-selection
19692 (lambda ()
19693 (not (run-hook-with-args-until-success
19694 'self-insert-uses-region-functions))))
19695 (put 'orgtbl-self-insert-command 'delete-selection
19696 (lambda ()
19697 (not (run-hook-with-args-until-success
19698 'self-insert-uses-region-functions))))
19699 (put 'org-delete-char 'delete-selection 'supersede)
19700 (put 'org-delete-backward-char 'delete-selection 'supersede)
19701 (put 'org-yank 'delete-selection 'yank)
19703 ;; Make `flyspell-mode' delay after some commands
19704 (put 'org-self-insert-command 'flyspell-delayed t)
19705 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19706 (put 'org-delete-char 'flyspell-delayed t)
19707 (put 'org-delete-backward-char 'flyspell-delayed t)
19709 ;; Make pabbrev-mode expand after org-mode commands
19710 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19711 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19713 (defun org-remap (map &rest commands)
19714 "In MAP, remap the functions given in COMMANDS.
19715 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19716 (let (new old)
19717 (while commands
19718 (setq old (pop commands) new (pop commands))
19719 (if (fboundp 'command-remapping)
19720 (org-defkey map (vector 'remap old) new)
19721 (substitute-key-definition old new map global-map)))))
19723 (defun org-transpose-words ()
19724 "Transpose words for Org.
19725 This uses the `org-mode-transpose-word-syntax-table' syntax
19726 table, which interprets characters in `org-emphasis-alist' as
19727 word constituents."
19728 (interactive)
19729 (with-syntax-table org-mode-transpose-word-syntax-table
19730 (call-interactively 'transpose-words)))
19731 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19733 (when (eq org-enable-table-editor 'optimized)
19734 ;; If the user wants maximum table support, we need to hijack
19735 ;; some standard editing functions
19736 (org-remap org-mode-map
19737 'self-insert-command 'org-self-insert-command
19738 'delete-char 'org-delete-char
19739 'delete-backward-char 'org-delete-backward-char)
19740 (org-defkey org-mode-map "|" 'org-force-self-insert))
19742 (defvar org-ctrl-c-ctrl-c-hook nil
19743 "Hook for functions attaching themselves to `C-c C-c'.
19745 This can be used to add additional functionality to the C-c C-c
19746 key which executes context-dependent commands. This hook is run
19747 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19748 run after the last test.
19750 Each function will be called with no arguments. The function
19751 must check if the context is appropriate for it to act. If yes,
19752 it should do its thing and then return a non-nil value. If the
19753 context is wrong, just do nothing and return nil.")
19755 (defvar org-ctrl-c-ctrl-c-final-hook nil
19756 "Hook for functions attaching themselves to `C-c C-c'.
19758 This can be used to add additional functionality to the C-c C-c
19759 key which executes context-dependent commands. This hook is run
19760 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19761 before the first test.
19763 Each function will be called with no arguments. The function
19764 must check if the context is appropriate for it to act. If yes,
19765 it should do its thing and then return a non-nil value. If the
19766 context is wrong, just do nothing and return nil.")
19768 (defvar org-tab-first-hook nil
19769 "Hook for functions to attach themselves to TAB.
19770 See `org-ctrl-c-ctrl-c-hook' for more information.
19771 This hook runs as the first action when TAB is pressed, even before
19772 `org-cycle' messes around with the `outline-regexp' to cater for
19773 inline tasks and plain list item folding.
19774 If any function in this hook returns t, any other actions that
19775 would have been caused by TAB (such as table field motion or visibility
19776 cycling) will not occur.")
19778 (defvar org-tab-after-check-for-table-hook nil
19779 "Hook for functions to attach themselves to TAB.
19780 See `org-ctrl-c-ctrl-c-hook' for more information.
19781 This hook runs after it has been established that the cursor is not in a
19782 table, but before checking if the cursor is in a headline or if global cycling
19783 should be done.
19784 If any function in this hook returns t, not other actions like visibility
19785 cycling will be done.")
19787 (defvar org-tab-after-check-for-cycling-hook nil
19788 "Hook for functions to attach themselves to TAB.
19789 See `org-ctrl-c-ctrl-c-hook' for more information.
19790 This hook runs after it has been established that not table field motion and
19791 not visibility should be done because of current context. This is probably
19792 the place where a package like yasnippets can hook in.")
19794 (defvar org-tab-before-tab-emulation-hook nil
19795 "Hook for functions to attach themselves to TAB.
19796 See `org-ctrl-c-ctrl-c-hook' for more information.
19797 This hook runs after every other options for TAB have been exhausted, but
19798 before indentation and \t insertion takes place.")
19800 (defvar org-metaleft-hook nil
19801 "Hook for functions attaching themselves to `M-left'.
19802 See `org-ctrl-c-ctrl-c-hook' for more information.")
19803 (defvar org-metaright-hook nil
19804 "Hook for functions attaching themselves to `M-right'.
19805 See `org-ctrl-c-ctrl-c-hook' for more information.")
19806 (defvar org-metaup-hook nil
19807 "Hook for functions attaching themselves to `M-up'.
19808 See `org-ctrl-c-ctrl-c-hook' for more information.")
19809 (defvar org-metadown-hook nil
19810 "Hook for functions attaching themselves to `M-down'.
19811 See `org-ctrl-c-ctrl-c-hook' for more information.")
19812 (defvar org-shiftmetaleft-hook nil
19813 "Hook for functions attaching themselves to `M-S-left'.
19814 See `org-ctrl-c-ctrl-c-hook' for more information.")
19815 (defvar org-shiftmetaright-hook nil
19816 "Hook for functions attaching themselves to `M-S-right'.
19817 See `org-ctrl-c-ctrl-c-hook' for more information.")
19818 (defvar org-shiftmetaup-hook nil
19819 "Hook for functions attaching themselves to `M-S-up'.
19820 See `org-ctrl-c-ctrl-c-hook' for more information.")
19821 (defvar org-shiftmetadown-hook nil
19822 "Hook for functions attaching themselves to `M-S-down'.
19823 See `org-ctrl-c-ctrl-c-hook' for more information.")
19824 (defvar org-metareturn-hook nil
19825 "Hook for functions attaching themselves to `M-RET'.
19826 See `org-ctrl-c-ctrl-c-hook' for more information.")
19827 (defvar org-shiftup-hook nil
19828 "Hook for functions attaching themselves to `S-up'.
19829 See `org-ctrl-c-ctrl-c-hook' for more information.")
19830 (defvar org-shiftup-final-hook nil
19831 "Hook for functions attaching themselves to `S-up'.
19832 This one runs after all other options except shift-select have been excluded.
19833 See `org-ctrl-c-ctrl-c-hook' for more information.")
19834 (defvar org-shiftdown-hook nil
19835 "Hook for functions attaching themselves to `S-down'.
19836 See `org-ctrl-c-ctrl-c-hook' for more information.")
19837 (defvar org-shiftdown-final-hook nil
19838 "Hook for functions attaching themselves to `S-down'.
19839 This one runs after all other options except shift-select have been excluded.
19840 See `org-ctrl-c-ctrl-c-hook' for more information.")
19841 (defvar org-shiftleft-hook nil
19842 "Hook for functions attaching themselves to `S-left'.
19843 See `org-ctrl-c-ctrl-c-hook' for more information.")
19844 (defvar org-shiftleft-final-hook nil
19845 "Hook for functions attaching themselves to `S-left'.
19846 This one runs after all other options except shift-select have been excluded.
19847 See `org-ctrl-c-ctrl-c-hook' for more information.")
19848 (defvar org-shiftright-hook nil
19849 "Hook for functions attaching themselves to `S-right'.
19850 See `org-ctrl-c-ctrl-c-hook' for more information.")
19851 (defvar org-shiftright-final-hook nil
19852 "Hook for functions attaching themselves to `S-right'.
19853 This one runs after all other options except shift-select have been excluded.
19854 See `org-ctrl-c-ctrl-c-hook' for more information.")
19856 (defun org-modifier-cursor-error ()
19857 "Throw an error, a modified cursor command was applied in wrong context."
19858 (user-error "This command is active in special context like tables, headlines or items"))
19860 (defun org-shiftselect-error ()
19861 "Throw an error because Shift-Cursor command was applied in wrong context."
19862 (if (and (boundp 'shift-select-mode) shift-select-mode)
19863 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19864 (user-error "This command works only in special context like headlines or timestamps")))
19866 (defun org-call-for-shift-select (cmd)
19867 (let ((this-command-keys-shift-translated t))
19868 (call-interactively cmd)))
19870 (defun org-shifttab (&optional arg)
19871 "Global visibility cycling or move to previous table field.
19872 Call `org-table-previous-field' within a table.
19873 When ARG is nil, cycle globally through visibility states.
19874 When ARG is a numeric prefix, show contents of this level."
19875 (interactive "P")
19876 (cond
19877 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19878 ((integerp arg)
19879 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19880 (message "Content view to level: %d" arg)
19881 (org-content (prefix-numeric-value arg2))
19882 (org-cycle-show-empty-lines t)
19883 (setq org-cycle-global-status 'overview)))
19884 (t (call-interactively 'org-global-cycle))))
19886 (defun org-shiftmetaleft ()
19887 "Promote subtree or delete table column.
19888 Calls `org-promote-subtree', `org-outdent-item-tree', or
19889 `org-table-delete-column', depending on context. See the
19890 individual commands for more information."
19891 (interactive)
19892 (cond
19893 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19894 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19895 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19896 ((if (not (org-region-active-p)) (org-at-item-p)
19897 (save-excursion (goto-char (region-beginning))
19898 (org-at-item-p)))
19899 (call-interactively 'org-outdent-item-tree))
19900 (t (org-modifier-cursor-error))))
19902 (defun org-shiftmetaright ()
19903 "Demote subtree or insert table column.
19904 Calls `org-demote-subtree', `org-indent-item-tree', or
19905 `org-table-insert-column', depending on context. See the
19906 individual commands for more information."
19907 (interactive)
19908 (cond
19909 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19910 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19911 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19912 ((if (not (org-region-active-p)) (org-at-item-p)
19913 (save-excursion (goto-char (region-beginning))
19914 (org-at-item-p)))
19915 (call-interactively 'org-indent-item-tree))
19916 (t (org-modifier-cursor-error))))
19918 (defun org-shiftmetaup (&optional arg)
19919 "Move subtree up or kill table row.
19920 Calls `org-move-subtree-up' or `org-table-kill-row' or
19921 `org-move-item-up' or `org-timestamp-up', depending on context.
19922 See the individual commands for more information."
19923 (interactive "P")
19924 (cond
19925 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19926 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19927 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19928 ((org-at-item-p) (call-interactively 'org-move-item-up))
19929 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19930 (call-interactively 'org-timestamp-up)))
19931 (t (call-interactively 'org-drag-line-backward))))
19933 (defun org-shiftmetadown (&optional arg)
19934 "Move subtree down or insert table row.
19935 Calls `org-move-subtree-down' or `org-table-insert-row' or
19936 `org-move-item-down' or `org-timestamp-up', depending on context.
19937 See the individual commands for more information."
19938 (interactive "P")
19939 (cond
19940 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19941 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19942 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19943 ((org-at-item-p) (call-interactively 'org-move-item-down))
19944 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19945 (call-interactively 'org-timestamp-down)))
19946 (t (call-interactively 'org-drag-line-forward))))
19948 (defsubst org-hidden-tree-error ()
19949 (user-error
19950 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19952 (defun org-metaleft (&optional arg)
19953 "Promote heading or move table column to left.
19954 Calls `org-do-promote' or `org-table-move-column', depending on context.
19955 With no specific context, calls the Emacs default `backward-word'.
19956 See the individual commands for more information."
19957 (interactive "P")
19958 (cond
19959 ((run-hook-with-args-until-success 'org-metaleft-hook))
19960 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19961 ((org-with-limited-levels
19962 (or (org-at-heading-p)
19963 (and (org-region-active-p)
19964 (save-excursion
19965 (goto-char (region-beginning))
19966 (org-at-heading-p)))))
19967 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19968 (call-interactively 'org-do-promote))
19969 ;; At an inline task.
19970 ((org-at-heading-p)
19971 (call-interactively 'org-inlinetask-promote))
19972 ((or (org-at-item-p)
19973 (and (org-region-active-p)
19974 (save-excursion
19975 (goto-char (region-beginning))
19976 (org-at-item-p))))
19977 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19978 (call-interactively 'org-outdent-item))
19979 (t (call-interactively 'backward-word))))
19981 (defun org-metaright (&optional arg)
19982 "Demote a subtree, a list item or move table column to right.
19983 In front of a drawer or a block keyword, indent it correctly.
19984 With no specific context, calls the Emacs default `forward-word'.
19985 See the individual commands for more information."
19986 (interactive "P")
19987 (cond
19988 ((run-hook-with-args-until-success 'org-metaright-hook))
19989 ((org-at-table-p) (call-interactively 'org-table-move-column))
19990 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19991 ((org-at-block-p) (call-interactively 'org-indent-block))
19992 ((org-with-limited-levels
19993 (or (org-at-heading-p)
19994 (and (org-region-active-p)
19995 (save-excursion
19996 (goto-char (region-beginning))
19997 (org-at-heading-p)))))
19998 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19999 (call-interactively 'org-do-demote))
20000 ;; At an inline task.
20001 ((org-at-heading-p)
20002 (call-interactively 'org-inlinetask-demote))
20003 ((or (org-at-item-p)
20004 (and (org-region-active-p)
20005 (save-excursion
20006 (goto-char (region-beginning))
20007 (org-at-item-p))))
20008 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20009 (call-interactively 'org-indent-item))
20010 (t (call-interactively 'forward-word))))
20012 (defun org-check-for-hidden (what)
20013 "Check if there are hidden headlines/items in the current visual line.
20014 WHAT can be either `headlines' or `items'. If the current line is
20015 an outline or item heading and it has a folded subtree below it,
20016 this function returns t, nil otherwise."
20017 (let ((re (cond
20018 ((eq what 'headlines) org-outline-regexp-bol)
20019 ((eq what 'items) (org-item-beginning-re))
20020 (t (error "This should not happen"))))
20021 beg end)
20022 (save-excursion
20023 (catch 'exit
20024 (unless (org-region-active-p)
20025 (setq beg (point-at-bol))
20026 (beginning-of-line 2)
20027 (while (and (not (eobp)) ;; this is like `next-line'
20028 (get-char-property (1- (point)) 'invisible))
20029 (beginning-of-line 2))
20030 (setq end (point))
20031 (goto-char beg)
20032 (goto-char (point-at-eol))
20033 (setq end (max end (point)))
20034 (while (re-search-forward re end t)
20035 (if (get-char-property (match-beginning 0) 'invisible)
20036 (throw 'exit t))))
20037 nil))))
20039 (defun org-metaup (&optional arg)
20040 "Move subtree up or move table row up.
20041 Calls `org-move-subtree-up' or `org-table-move-row' or
20042 `org-move-item-up', depending on context. See the individual commands
20043 for more information."
20044 (interactive "P")
20045 (cond
20046 ((run-hook-with-args-until-success 'org-metaup-hook))
20047 ((org-region-active-p)
20048 (let* ((a (min (region-beginning) (region-end)))
20049 (b (1- (max (region-beginning) (region-end))))
20050 (c (save-excursion (goto-char a)
20051 (move-beginning-of-line 0)))
20052 (d (save-excursion (goto-char a)
20053 (move-end-of-line 0) (point))))
20054 (transpose-regions a b c d)
20055 (goto-char c)))
20056 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20057 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20058 ((org-at-item-p) (call-interactively 'org-move-item-up))
20059 (t (org-drag-element-backward))))
20061 (defun org-metadown (&optional arg)
20062 "Move subtree down or move table row down.
20063 Calls `org-move-subtree-down' or `org-table-move-row' or
20064 `org-move-item-down', depending on context. See the individual
20065 commands for more information."
20066 (interactive "P")
20067 (cond
20068 ((run-hook-with-args-until-success 'org-metadown-hook))
20069 ((org-region-active-p)
20070 (let* ((a (min (region-beginning) (region-end)))
20071 (b (max (region-beginning) (region-end)))
20072 (c (save-excursion (goto-char b)
20073 (move-beginning-of-line 1)))
20074 (d (save-excursion (goto-char b)
20075 (move-end-of-line 1) (1+ (point)))))
20076 (transpose-regions a b c d)
20077 (goto-char d)))
20078 ((org-at-table-p) (call-interactively 'org-table-move-row))
20079 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20080 ((org-at-item-p) (call-interactively 'org-move-item-down))
20081 (t (org-drag-element-forward))))
20083 (defun org-shiftup (&optional arg)
20084 "Increase item in timestamp or increase priority of current headline.
20085 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20086 depending on context. See the individual commands for more information."
20087 (interactive "P")
20088 (cond
20089 ((run-hook-with-args-until-success 'org-shiftup-hook))
20090 ((and org-support-shift-select (org-region-active-p))
20091 (org-call-for-shift-select 'previous-line))
20092 ((org-at-timestamp-p t)
20093 (call-interactively (if org-edit-timestamp-down-means-later
20094 'org-timestamp-down 'org-timestamp-up)))
20095 ((and (not (eq org-support-shift-select 'always))
20096 org-enable-priority-commands
20097 (org-at-heading-p))
20098 (call-interactively 'org-priority-up))
20099 ((and (not org-support-shift-select) (org-at-item-p))
20100 (call-interactively 'org-previous-item))
20101 ((org-clocktable-try-shift 'up arg))
20102 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20103 (org-support-shift-select
20104 (org-call-for-shift-select 'previous-line))
20105 (t (org-shiftselect-error))))
20107 (defun org-shiftdown (&optional arg)
20108 "Decrease item in timestamp or decrease priority of current headline.
20109 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20110 depending on context. See the individual commands for more information."
20111 (interactive "P")
20112 (cond
20113 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20114 ((and org-support-shift-select (org-region-active-p))
20115 (org-call-for-shift-select 'next-line))
20116 ((org-at-timestamp-p t)
20117 (call-interactively (if org-edit-timestamp-down-means-later
20118 'org-timestamp-up 'org-timestamp-down)))
20119 ((and (not (eq org-support-shift-select 'always))
20120 org-enable-priority-commands
20121 (org-at-heading-p))
20122 (call-interactively 'org-priority-down))
20123 ((and (not org-support-shift-select) (org-at-item-p))
20124 (call-interactively 'org-next-item))
20125 ((org-clocktable-try-shift 'down arg))
20126 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20127 (org-support-shift-select
20128 (org-call-for-shift-select 'next-line))
20129 (t (org-shiftselect-error))))
20131 (defun org-shiftright (&optional arg)
20132 "Cycle the thing at point or in the current line, depending on context.
20133 Depending on context, this does one of the following:
20135 - switch a timestamp at point one day into the future
20136 - on a headline, switch to the next TODO keyword.
20137 - on an item, switch entire list to the next bullet type
20138 - on a property line, switch to the next allowed value
20139 - on a clocktable definition line, move time block into the future"
20140 (interactive "P")
20141 (cond
20142 ((run-hook-with-args-until-success 'org-shiftright-hook))
20143 ((and org-support-shift-select (org-region-active-p))
20144 (org-call-for-shift-select 'forward-char))
20145 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20146 ((and (not (eq org-support-shift-select 'always))
20147 (org-at-heading-p))
20148 (let ((org-inhibit-logging
20149 (not org-treat-S-cursor-todo-selection-as-state-change))
20150 (org-inhibit-blocking
20151 (not org-treat-S-cursor-todo-selection-as-state-change)))
20152 (org-call-with-arg 'org-todo 'right)))
20153 ((or (and org-support-shift-select
20154 (not (eq org-support-shift-select 'always))
20155 (org-at-item-bullet-p))
20156 (and (not org-support-shift-select) (org-at-item-p)))
20157 (org-call-with-arg 'org-cycle-list-bullet nil))
20158 ((and (not (eq org-support-shift-select 'always))
20159 (org-at-property-p))
20160 (call-interactively 'org-property-next-allowed-value))
20161 ((org-clocktable-try-shift 'right arg))
20162 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20163 (org-support-shift-select
20164 (org-call-for-shift-select 'forward-char))
20165 (t (org-shiftselect-error))))
20167 (defun org-shiftleft (&optional arg)
20168 "Cycle the thing at point or in the current line, depending on context.
20169 Depending on context, this does one of the following:
20171 - switch a timestamp at point one day into the past
20172 - on a headline, switch to the previous TODO keyword.
20173 - on an item, switch entire list to the previous bullet type
20174 - on a property line, switch to the previous allowed value
20175 - on a clocktable definition line, move time block into the past"
20176 (interactive "P")
20177 (cond
20178 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20179 ((and org-support-shift-select (org-region-active-p))
20180 (org-call-for-shift-select 'backward-char))
20181 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20182 ((and (not (eq org-support-shift-select 'always))
20183 (org-at-heading-p))
20184 (let ((org-inhibit-logging
20185 (not org-treat-S-cursor-todo-selection-as-state-change))
20186 (org-inhibit-blocking
20187 (not org-treat-S-cursor-todo-selection-as-state-change)))
20188 (org-call-with-arg 'org-todo 'left)))
20189 ((or (and org-support-shift-select
20190 (not (eq org-support-shift-select 'always))
20191 (org-at-item-bullet-p))
20192 (and (not org-support-shift-select) (org-at-item-p)))
20193 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20194 ((and (not (eq org-support-shift-select 'always))
20195 (org-at-property-p))
20196 (call-interactively 'org-property-previous-allowed-value))
20197 ((org-clocktable-try-shift 'left arg))
20198 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20199 (org-support-shift-select
20200 (org-call-for-shift-select 'backward-char))
20201 (t (org-shiftselect-error))))
20203 (defun org-shiftcontrolright ()
20204 "Switch to next TODO set."
20205 (interactive)
20206 (cond
20207 ((and org-support-shift-select (org-region-active-p))
20208 (org-call-for-shift-select 'forward-word))
20209 ((and (not (eq org-support-shift-select 'always))
20210 (org-at-heading-p))
20211 (org-call-with-arg 'org-todo 'nextset))
20212 (org-support-shift-select
20213 (org-call-for-shift-select 'forward-word))
20214 (t (org-shiftselect-error))))
20216 (defun org-shiftcontrolleft ()
20217 "Switch to previous TODO set."
20218 (interactive)
20219 (cond
20220 ((and org-support-shift-select (org-region-active-p))
20221 (org-call-for-shift-select 'backward-word))
20222 ((and (not (eq org-support-shift-select 'always))
20223 (org-at-heading-p))
20224 (org-call-with-arg 'org-todo 'previousset))
20225 (org-support-shift-select
20226 (org-call-for-shift-select 'backward-word))
20227 (t (org-shiftselect-error))))
20229 (defun org-shiftcontrolup (&optional n)
20230 "Change timestamps synchronously up in CLOCK log lines.
20231 Optional argument N tells to change by that many units."
20232 (interactive "P")
20233 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20234 (let (org-support-shift-select)
20235 (org-clock-timestamps-up n))
20236 (user-error "Not at a clock log")))
20238 (defun org-shiftcontroldown (&optional n)
20239 "Change timestamps synchronously down in CLOCK log lines.
20240 Optional argument N tells to change by that many units."
20241 (interactive "P")
20242 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20243 (let (org-support-shift-select)
20244 (org-clock-timestamps-down n))
20245 (user-error "Not at a clock log")))
20247 (defun org-ctrl-c-ret ()
20248 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20249 (interactive)
20250 (cond
20251 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20252 (t (call-interactively 'org-insert-heading))))
20254 (defun org-find-visible ()
20255 (let ((s (point)))
20256 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20257 (get-char-property s 'invisible)))
20259 (defun org-find-invisible ()
20260 (let ((s (point)))
20261 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20262 (not (get-char-property s 'invisible))))
20265 (defun org-copy-visible (beg end)
20266 "Copy the visible parts of the region."
20267 (interactive "r")
20268 (let (snippets s)
20269 (save-excursion
20270 (save-restriction
20271 (narrow-to-region beg end)
20272 (setq s (goto-char (point-min)))
20273 (while (not (= (point) (point-max)))
20274 (goto-char (org-find-invisible))
20275 (push (buffer-substring s (point)) snippets)
20276 (setq s (goto-char (org-find-visible))))))
20277 (kill-new (apply 'concat (nreverse snippets)))))
20279 (defun org-copy-special ()
20280 "Copy region in table or copy current subtree.
20281 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20282 See the individual commands for more information."
20283 (interactive)
20284 (call-interactively
20285 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20287 (defun org-cut-special ()
20288 "Cut region in table or cut current subtree.
20289 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20290 See the individual commands for more information."
20291 (interactive)
20292 (call-interactively
20293 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20295 (defun org-paste-special (arg)
20296 "Paste rectangular region into table, or past subtree relative to level.
20297 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20298 See the individual commands for more information."
20299 (interactive "P")
20300 (if (org-at-table-p)
20301 (org-table-paste-rectangle)
20302 (org-paste-subtree arg)))
20304 (defsubst org-in-fixed-width-region-p ()
20305 "Is point in a fixed-width region?"
20306 (save-match-data
20307 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20309 (defun org-edit-special (&optional arg)
20310 "Call a special editor for the element at point.
20311 When at a table, call the formula editor with `org-table-edit-formulas'.
20312 When in a source code block, call `org-edit-src-code'.
20313 When in a fixed-width region, call `org-edit-fixed-width-region'.
20314 When at an #+INCLUDE keyword, visit the included file.
20315 On a link, call `ffap' to visit the link at point.
20316 Otherwise, return a user error."
20317 (interactive "P")
20318 (let ((element (org-element-at-point)))
20319 (assert (not buffer-read-only) nil
20320 "Buffer is read-only: %s" (buffer-name))
20321 (case (org-element-type element)
20322 (src-block
20323 (if (not arg) (org-edit-src-code)
20324 (let* ((info (org-babel-get-src-block-info))
20325 (lang (nth 0 info))
20326 (params (nth 2 info))
20327 (session (cdr (assq :session params))))
20328 (if (not session) (org-edit-src-code)
20329 ;; At a src-block with a session and function called with
20330 ;; an ARG: switch to the buffer related to the inferior
20331 ;; process.
20332 (switch-to-buffer
20333 (funcall (intern (concat "org-babel-prep-session:" lang))
20334 session params))))))
20335 (keyword
20336 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20337 (find-file-other-window
20338 (org-remove-double-quotes
20339 (car (org-split-string (org-element-property :value element)))))
20340 (user-error "No special environment to edit here")))
20341 (table
20342 (if (eq (org-element-property :type element) 'table.el)
20343 (org-edit-src-code)
20344 (call-interactively 'org-table-edit-formulas)))
20345 ;; Only Org tables contain `table-row' type elements.
20346 (table-row (call-interactively 'org-table-edit-formulas))
20347 ((example-block export-block) (org-edit-src-code))
20348 (fixed-width (org-edit-fixed-width-region))
20349 (otherwise
20350 ;; No notable element at point. Though, we may be at a link,
20351 ;; which is an object. Thus, scan deeper.
20352 (if (eq (org-element-type (org-element-context element)) 'link)
20353 (call-interactively 'ffap)
20354 (user-error "No special environment to edit here"))))))
20356 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20357 (defun org-ctrl-c-ctrl-c (&optional arg)
20358 "Set tags in headline, or update according to changed information at point.
20360 This command does many different things, depending on context:
20362 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20363 this is what we do.
20365 - If the cursor is on a statistics cookie, update it.
20367 - If the cursor is in a headline, prompt for tags and insert them
20368 into the current line, aligned to `org-tags-column'. When called
20369 with prefix arg, realign all tags in the current buffer.
20371 - If the cursor is in one of the special #+KEYWORD lines, this
20372 triggers scanning the buffer for these lines and updating the
20373 information.
20375 - If the cursor is inside a table, realign the table. This command
20376 works even if the automatic table editor has been turned off.
20378 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20379 the entire table.
20381 - If the cursor is at a footnote reference or definition, jump to
20382 the corresponding definition or references, respectively.
20384 - If the cursor is a the beginning of a dynamic block, update it.
20386 - If the current buffer is a capture buffer, close note and file it.
20388 - If the cursor is on a <<<target>>>, update radio targets and
20389 corresponding links in this buffer.
20391 - If the cursor is on a numbered item in a plain list, renumber the
20392 ordered list.
20394 - If the cursor is on a checkbox, toggle it.
20396 - If the cursor is on a code block, evaluate it. The variable
20397 `org-confirm-babel-evaluate' can be used to control prompting
20398 before code block evaluation, by default every code block
20399 evaluation requires confirmation. Code block evaluation can be
20400 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20401 (interactive "P")
20402 (cond
20403 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20404 org-occur-highlights
20405 org-latex-fragment-image-overlays)
20406 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20407 (org-remove-occur-highlights)
20408 (org-remove-latex-fragment-image-overlays)
20409 (message "Temporary highlights/overlays removed from current buffer"))
20410 ((and (local-variable-p 'org-finish-function (current-buffer))
20411 (fboundp org-finish-function))
20412 (funcall org-finish-function))
20413 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20415 (let* ((context (org-element-context)) (type (org-element-type context)))
20416 ;; Test if point is within a blank line.
20417 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20418 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20419 (user-error "C-c C-c can do nothing useful at this location"))
20420 (case type
20421 ;; When at a link, act according to the parent instead.
20422 (link (setq context (org-element-property :parent context))
20423 (setq type (org-element-type context)))
20424 ;; Unsupported object types: refer to the first supported
20425 ;; element or object containing it.
20426 ((bold code entity export-snippet inline-babel-call inline-src-block
20427 italic latex-fragment line-break macro strike-through subscript
20428 superscript underline verbatim)
20429 (while (and (setq context (org-element-property :parent context))
20430 (not (memq (setq type (org-element-type context))
20431 '(radio-target paragraph verse-block
20432 table-cell)))))))
20433 ;; For convenience: at the first line of a paragraph on the
20434 ;; same line as an item, apply function on that item instead.
20435 (when (eq type 'paragraph)
20436 (let ((parent (org-element-property :parent context)))
20437 (when (and (eq (org-element-type parent) 'item)
20438 (= (point-at-bol) (org-element-property :begin parent)))
20439 (setq context parent type 'item))))
20440 ;; Act according to type of element or object at point.
20441 (case type
20442 (clock (org-clock-update-time-maybe))
20443 (dynamic-block
20444 (save-excursion
20445 (goto-char (org-element-property :post-affiliated context))
20446 (org-update-dblock)))
20447 (footnote-definition
20448 (goto-char (org-element-property :post-affiliated context))
20449 (call-interactively 'org-footnote-action))
20450 (footnote-reference (call-interactively 'org-footnote-action))
20451 ((headline inlinetask)
20452 (save-excursion (goto-char (org-element-property :begin context))
20453 (call-interactively 'org-set-tags)))
20454 (item
20455 ;; At an item: a double C-u set checkbox to "[-]"
20456 ;; unconditionally, whereas a single one will toggle its
20457 ;; presence. Without an universal argument, if the item
20458 ;; has a checkbox, toggle it. Otherwise repair the list.
20459 (let* ((box (org-element-property :checkbox context))
20460 (struct (org-element-property :structure context))
20461 (old-struct (copy-tree struct))
20462 (parents (org-list-parents-alist struct))
20463 (prevs (org-list-prevs-alist struct))
20464 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20465 (org-list-set-checkbox
20466 (org-element-property :begin context) struct
20467 (cond ((equal arg '(16)) "[-]")
20468 ((and (not box) (equal arg '(4))) "[ ]")
20469 ((or (not box) (equal arg '(4))) nil)
20470 ((eq box 'on) "[ ]")
20471 (t "[X]")))
20472 ;; Mimic `org-list-write-struct' but with grabbing
20473 ;; a return value from `org-list-struct-fix-box'.
20474 (org-list-struct-fix-ind struct parents 2)
20475 (org-list-struct-fix-item-end struct)
20476 (org-list-struct-fix-bul struct prevs)
20477 (org-list-struct-fix-ind struct parents)
20478 (let ((block-item
20479 (org-list-struct-fix-box struct parents prevs orderedp)))
20480 (if (and box (equal struct old-struct))
20481 (if (equal arg '(16))
20482 (message "Checkboxes already reset")
20483 (user-error "Cannot toggle this checkbox: %s"
20484 (if (eq box 'on)
20485 "all subitems checked"
20486 "unchecked subitems")))
20487 (org-list-struct-apply-struct struct old-struct)
20488 (org-update-checkbox-count-maybe))
20489 (when block-item
20490 (message "Checkboxes were removed due to empty box at line %d"
20491 (org-current-line block-item))))))
20492 (keyword
20493 (let ((org-inhibit-startup-visibility-stuff t)
20494 (org-startup-align-all-tables nil))
20495 (when (boundp 'org-table-coordinate-overlays)
20496 (mapc 'delete-overlay org-table-coordinate-overlays)
20497 (setq org-table-coordinate-overlays nil))
20498 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20499 (message "Local setup has been refreshed"))
20500 (plain-list
20501 ;; At a plain list, with a double C-u argument, set
20502 ;; checkboxes of each item to "[-]", whereas a single one
20503 ;; will toggle their presence according to the state of the
20504 ;; first item in the list. Without an argument, repair the
20505 ;; list.
20506 (let* ((begin (org-element-property :contents-begin context))
20507 (beginm (move-marker (make-marker) begin))
20508 (struct (org-element-property :structure context))
20509 (old-struct (copy-tree struct))
20510 (first-box (save-excursion
20511 (goto-char begin)
20512 (looking-at org-list-full-item-re)
20513 (match-string-no-properties 3)))
20514 (new-box (cond ((equal arg '(16)) "[-]")
20515 ((equal arg '(4)) (unless first-box "[ ]"))
20516 ((equal first-box "[X]") "[ ]")
20517 (t "[X]"))))
20518 (cond
20519 (arg
20520 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20521 (org-list-get-all-items
20522 begin struct (org-list-prevs-alist struct))))
20523 ((and first-box (eq (point) begin))
20524 ;; For convenience, when point is at bol on the first
20525 ;; item of the list and no argument is provided, simply
20526 ;; toggle checkbox of that item, if any.
20527 (org-list-set-checkbox begin struct new-box)))
20528 (org-list-write-struct
20529 struct (org-list-parents-alist struct) old-struct)
20530 (org-update-checkbox-count-maybe)
20531 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20532 ((property-drawer node-property)
20533 (call-interactively 'org-property-action))
20534 ((radio-target target)
20535 (call-interactively 'org-update-radio-target-regexp))
20536 (statistics-cookie
20537 (call-interactively 'org-update-statistics-cookies))
20538 ((table table-cell table-row)
20539 ;; At a table, recalculate every field and align it. Also
20540 ;; send the table if necessary. If the table has
20541 ;; a `table.el' type, just give up. At a table row or
20542 ;; cell, maybe recalculate line but always align table.
20543 (if (eq (org-element-property :type context) 'table.el)
20544 (message "Use C-c ' to edit table.el tables")
20545 (let ((org-enable-table-editor t))
20546 (if (or (eq type 'table)
20547 ;; Check if point is at a TBLFM line.
20548 (and (eq type 'table-row)
20549 (= (point) (org-element-property :end context))))
20550 (save-excursion
20551 (if (org-at-TBLFM-p)
20552 (progn (require 'org-table)
20553 (org-table-calc-current-TBLFM))
20554 (goto-char (org-element-property :contents-begin context))
20555 (org-call-with-arg 'org-table-recalculate (or arg t))
20556 (orgtbl-send-table 'maybe)))
20557 (org-table-maybe-eval-formula)
20558 (cond (arg (call-interactively 'org-table-recalculate))
20559 ((org-table-maybe-recalculate-line))
20560 (t (org-table-align)))))))
20561 (timestamp (org-timestamp-change 0 'day))
20562 (otherwise
20563 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20564 (user-error
20565 "C-c C-c can do nothing useful at this location")))))))))
20567 (defun org-mode-restart ()
20568 (interactive)
20569 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20570 (funcall major-mode)
20571 (hack-local-variables)
20572 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20573 (org-indent-mode -1)))
20574 (message "%s restarted" major-mode))
20576 (defun org-kill-note-or-show-branches ()
20577 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20578 (interactive)
20579 (if (not org-finish-function)
20580 (progn
20581 (hide-subtree)
20582 (call-interactively 'show-branches))
20583 (let ((org-note-abort t))
20584 (funcall org-finish-function))))
20586 (defun org-open-line (n)
20587 "Insert a new row in tables, call `open-line' elsewhere.
20588 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20589 (interactive "*p")
20590 (cond
20591 ((not org-special-ctrl-o)
20592 (open-line n))
20593 ((org-at-table-p)
20594 (org-table-insert-row))
20596 (open-line n))))
20598 (defun org-return (&optional indent)
20599 "Goto next table row or insert a newline.
20600 Calls `org-table-next-row' or `newline', depending on context.
20601 See the individual commands for more information."
20602 (interactive)
20603 (let (org-ts-what)
20604 (cond
20605 ((or (bobp) (org-in-src-block-p))
20606 (if indent (newline-and-indent) (newline)))
20607 ((org-at-table-p)
20608 (org-table-justify-field-maybe)
20609 (call-interactively 'org-table-next-row))
20610 ;; when `newline-and-indent' is called within a list, make sure
20611 ;; text moved stays inside the item.
20612 ((and (org-in-item-p) indent)
20613 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20614 (progn
20615 (save-match-data (newline))
20616 (org-indent-line-to (length (match-string 0))))
20617 (let ((ind (org-get-indentation)))
20618 (newline)
20619 (if (org-looking-back org-list-end-re)
20620 (org-indent-line)
20621 (org-indent-line-to ind)))))
20622 ((and org-return-follows-link
20623 (org-at-timestamp-p t)
20624 (not (eq org-ts-what 'after)))
20625 (org-follow-timestamp-link))
20626 ((and org-return-follows-link
20627 (let ((tprop (get-text-property (point) 'face)))
20628 (or (eq tprop 'org-link)
20629 (and (listp tprop) (memq 'org-link tprop)))))
20630 (call-interactively 'org-open-at-point))
20631 ((and (org-at-heading-p)
20632 (looking-at
20633 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20634 (org-show-entry)
20635 (end-of-line 1)
20636 (newline))
20637 (t (if indent (newline-and-indent) (newline))))))
20639 (defun org-return-indent ()
20640 "Goto next table row or insert a newline and indent.
20641 Calls `org-table-next-row' or `newline-and-indent', depending on
20642 context. See the individual commands for more information."
20643 (interactive)
20644 (org-return t))
20646 (defun org-ctrl-c-star ()
20647 "Compute table, or change heading status of lines.
20648 Calls `org-table-recalculate' or `org-toggle-heading',
20649 depending on context."
20650 (interactive)
20651 (cond
20652 ((org-at-table-p)
20653 (call-interactively 'org-table-recalculate))
20655 ;; Convert all lines in region to list items
20656 (call-interactively 'org-toggle-heading))))
20658 (defun org-ctrl-c-minus ()
20659 "Insert separator line in table or modify bullet status of line.
20660 Also turns a plain line or a region of lines into list items.
20661 Calls `org-table-insert-hline', `org-toggle-item', or
20662 `org-cycle-list-bullet', depending on context."
20663 (interactive)
20664 (cond
20665 ((org-at-table-p)
20666 (call-interactively 'org-table-insert-hline))
20667 ((org-region-active-p)
20668 (call-interactively 'org-toggle-item))
20669 ((org-in-item-p)
20670 (call-interactively 'org-cycle-list-bullet))
20672 (call-interactively 'org-toggle-item))))
20674 (defun org-toggle-item (arg)
20675 "Convert headings or normal lines to items, items to normal lines.
20676 If there is no active region, only the current line is considered.
20678 If the first non blank line in the region is a headline, convert
20679 all headlines to items, shifting text accordingly.
20681 If it is an item, convert all items to normal lines.
20683 If it is normal text, change region into a list of items.
20684 With a prefix argument ARG, change the region in a single item."
20685 (interactive "P")
20686 (let ((shift-text
20687 (function
20688 ;; Shift text in current section to IND, from point to END.
20689 ;; The function leaves point to END line.
20690 (lambda (ind end)
20691 (let ((min-i 1000) (end (copy-marker end)))
20692 ;; First determine the minimum indentation (MIN-I) of
20693 ;; the text.
20694 (save-excursion
20695 (catch 'exit
20696 (while (< (point) end)
20697 (let ((i (org-get-indentation)))
20698 (cond
20699 ;; Skip blank lines and inline tasks.
20700 ((looking-at "^[ \t]*$"))
20701 ((looking-at org-outline-regexp-bol))
20702 ;; We can't find less than 0 indentation.
20703 ((zerop i) (throw 'exit (setq min-i 0)))
20704 ((< i min-i) (setq min-i i))))
20705 (forward-line))))
20706 ;; Then indent each line so that a line indented to
20707 ;; MIN-I becomes indented to IND. Ignore blank lines
20708 ;; and inline tasks in the process.
20709 (let ((delta (- ind min-i)))
20710 (while (< (point) end)
20711 (unless (or (looking-at "^[ \t]*$")
20712 (looking-at org-outline-regexp-bol))
20713 (org-indent-line-to (+ (org-get-indentation) delta)))
20714 (forward-line)))))))
20715 (skip-blanks
20716 (function
20717 ;; Return beginning of first non-blank line, starting from
20718 ;; line at POS.
20719 (lambda (pos)
20720 (save-excursion
20721 (goto-char pos)
20722 (skip-chars-forward " \r\t\n")
20723 (point-at-bol)))))
20724 beg end)
20725 ;; Determine boundaries of changes.
20726 (if (org-region-active-p)
20727 (setq beg (funcall skip-blanks (region-beginning))
20728 end (copy-marker (region-end)))
20729 (setq beg (funcall skip-blanks (point-at-bol))
20730 end (copy-marker (point-at-eol))))
20731 ;; Depending on the starting line, choose an action on the text
20732 ;; between BEG and END.
20733 (org-with-limited-levels
20734 (save-excursion
20735 (goto-char beg)
20736 (cond
20737 ;; Case 1. Start at an item: de-itemize. Note that it only
20738 ;; happens when a region is active: `org-ctrl-c-minus'
20739 ;; would call `org-cycle-list-bullet' otherwise.
20740 ((org-at-item-p)
20741 (while (< (point) end)
20742 (when (org-at-item-p)
20743 (skip-chars-forward " \t")
20744 (delete-region (point) (match-end 0)))
20745 (forward-line)))
20746 ;; Case 2. Start at an heading: convert to items.
20747 ((org-at-heading-p)
20748 (let* ((bul (org-list-bullet-string "-"))
20749 (bul-len (length bul))
20750 (done (org-entry-is-done-p))
20751 (todo (org-entry-is-todo-p))
20752 ;; Indentation of the first heading. It should be
20753 ;; relative to the indentation of its parent, if any.
20754 (start-ind (save-excursion
20755 (cond
20756 ((not org-adapt-indentation) 0)
20757 ((not (outline-previous-heading)) 0)
20758 (t (length (match-string 0))))))
20759 ;; Level of first heading. Further headings will be
20760 ;; compared to it to determine hierarchy in the list.
20761 (ref-level (org-reduced-level (org-outline-level))))
20762 (when (or done todo) (org-todo ""))
20763 (while (< (point) end)
20764 (let* ((level (org-reduced-level (org-outline-level)))
20765 (delta (max 0 (- level ref-level))))
20766 ;; If current headline is less indented than the first
20767 ;; one, set it as reference, in order to preserve
20768 ;; subtrees.
20769 (when (< level ref-level) (setq ref-level level))
20770 (replace-match bul t t)
20771 (org-indent-line-to (+ start-ind (* delta bul-len)))
20772 (when (or done todo)
20773 (let* ((struct (org-list-struct))
20774 (old (copy-tree struct)))
20775 (org-list-set-checkbox (line-beginning-position)
20776 struct
20777 (if done "[X]" "[ ]"))
20778 (org-list-write-struct struct
20779 (org-list-parents-alist struct)
20780 old)))
20781 ;; Ensure all text down to END (or SECTION-END) belongs
20782 ;; to the newly created item.
20783 (let ((section-end (save-excursion
20784 (or (outline-next-heading) (point)))))
20785 (forward-line)
20786 (funcall shift-text
20787 (+ start-ind (* (1+ delta) bul-len))
20788 (min end section-end)))))))
20789 ;; Case 3. Normal line with ARG: make the first line of region
20790 ;; an item, and shift indentation of others lines to
20791 ;; set them as item's body.
20792 (arg (let* ((bul (org-list-bullet-string "-"))
20793 (bul-len (length bul))
20794 (ref-ind (org-get-indentation)))
20795 (skip-chars-forward " \t")
20796 (insert bul)
20797 (forward-line)
20798 (while (< (point) end)
20799 ;; Ensure that lines less indented than first one
20800 ;; still get included in item body.
20801 (funcall shift-text
20802 (+ ref-ind bul-len)
20803 (min end (save-excursion (or (outline-next-heading)
20804 (point)))))
20805 (forward-line))))
20806 ;; Case 4. Normal line without ARG: turn each non-item line
20807 ;; into an item.
20809 (while (< (point) end)
20810 (unless (or (org-at-heading-p) (org-at-item-p))
20811 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20812 (replace-match
20813 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20814 (forward-line))))))))
20816 (defun org-toggle-heading (&optional nstars)
20817 "Convert headings to normal text, or items or text to headings.
20818 If there is no active region, only convert the current line.
20820 With a \\[universal-argument] prefix, convert the whole list at
20821 point into heading.
20823 In a region:
20825 - If the first non blank line is a headline, remove the stars
20826 from all headlines in the region.
20828 - If it is a normal line, turn each and every normal line (i.e.,
20829 not an heading or an item) in the region into headings. If you
20830 want to convert only the first line of this region, use one
20831 universal prefix argument.
20833 - If it is a plain list item, turn all plain list items into headings.
20835 When converting a line into a heading, the number of stars is chosen
20836 such that the lines become children of the current entry. However,
20837 when a numeric prefix argument is given, its value determines the
20838 number of stars to add."
20839 (interactive "P")
20840 (let ((skip-blanks
20841 (function
20842 ;; Return beginning of first non-blank line, starting from
20843 ;; line at POS.
20844 (lambda (pos)
20845 (save-excursion
20846 (goto-char pos)
20847 (while (org-at-comment-p) (forward-line))
20848 (skip-chars-forward " \r\t\n")
20849 (point-at-bol)))))
20850 beg end toggled)
20851 ;; Determine boundaries of changes. If a universal prefix has
20852 ;; been given, put the list in a region. If region ends at a bol,
20853 ;; do not consider the last line to be in the region.
20855 (when (and current-prefix-arg (org-at-item-p))
20856 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20857 (org-mark-element))
20859 (if (org-region-active-p)
20860 (setq beg (funcall skip-blanks (region-beginning))
20861 end (copy-marker (save-excursion
20862 (goto-char (region-end))
20863 (if (bolp) (point) (point-at-eol)))))
20864 (setq beg (funcall skip-blanks (point-at-bol))
20865 end (copy-marker (point-at-eol))))
20866 ;; Ensure inline tasks don't count as headings.
20867 (org-with-limited-levels
20868 (save-excursion
20869 (goto-char beg)
20870 (cond
20871 ;; Case 1. Started at an heading: de-star headings.
20872 ((org-at-heading-p)
20873 (while (< (point) end)
20874 (when (org-at-heading-p t)
20875 (looking-at org-outline-regexp) (replace-match "")
20876 (setq toggled t))
20877 (forward-line)))
20878 ;; Case 2. Started at an item: change items into headlines.
20879 ;; One star will be added by `org-list-to-subtree'.
20880 ((org-at-item-p)
20881 (let* ((stars (make-string
20882 ;; subtract the star that will be added again by
20883 ;; `org-list-to-subtree'
20884 (if (numberp nstars) (1- nstars)
20885 (or (org-current-level) 0))
20886 ?*))
20887 (add-stars
20888 (cond (nstars "") ; stars from prefix only
20889 ((equal stars "") "") ; before first heading
20890 (org-odd-levels-only "*") ; inside heading, odd
20891 (t "")))) ; inside heading, oddeven
20892 (while (< (point) end)
20893 (when (org-at-item-p)
20894 ;; Pay attention to cases when region ends before list.
20895 (let* ((struct (org-list-struct))
20896 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20897 (save-restriction
20898 (narrow-to-region (point) list-end)
20899 (insert
20900 (org-list-to-subtree
20901 (org-list-parse-list t)
20902 '(:istart (concat stars add-stars (funcall get-stars depth))
20903 :icount (concat stars add-stars (funcall get-stars depth)))))))
20904 (setq toggled t))
20905 (forward-line))))
20906 ;; Case 3. Started at normal text: make every line an heading,
20907 ;; skipping headlines and items.
20908 (t (let* ((stars
20909 (make-string
20910 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20911 (add-stars
20912 (cond (nstars "") ; stars from prefix only
20913 ((equal stars "") "*") ; before first heading
20914 (org-odd-levels-only "**") ; inside heading, odd
20915 (t "*"))) ; inside heading, oddeven
20916 (rpl (concat stars add-stars " "))
20917 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20918 (while (< (point) (if (equal nstars '(4)) lend end))
20919 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20920 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20921 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20922 (forward-line)))))))
20923 (unless toggled (message "Cannot toggle heading from here"))))
20925 (defun org-meta-return (&optional arg)
20926 "Insert a new heading or wrap a region in a table.
20927 Calls `org-insert-heading' or `org-table-wrap-region', depending
20928 on context. See the individual commands for more information."
20929 (interactive "P")
20930 (org-check-before-invisible-edit 'insert)
20931 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20932 (let* ((element (org-element-at-point))
20933 (type (org-element-type element)))
20934 (when (eq type 'table-row)
20935 (setq element (org-element-property :parent element))
20936 (setq type 'table))
20937 (if (and (eq type 'table)
20938 (eq (org-element-property :type element) 'org)
20939 (>= (point) (org-element-property :contents-begin element))
20940 (< (point) (org-element-property :contents-end element)))
20941 (call-interactively 'org-table-wrap-region)
20942 (call-interactively 'org-insert-heading)))))
20944 ;;; Menu entries
20946 (defsubst org-in-subtree-not-table-p ()
20947 "Are we in a subtree and not in a table?"
20948 (and (not (org-before-first-heading-p))
20949 (not (org-at-table-p))))
20951 ;; Define the Org-mode menus
20952 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20953 '("Tbl"
20954 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20955 ["Next Field" org-cycle (org-at-table-p)]
20956 ["Previous Field" org-shifttab (org-at-table-p)]
20957 ["Next Row" org-return (org-at-table-p)]
20958 "--"
20959 ["Blank Field" org-table-blank-field (org-at-table-p)]
20960 ["Edit Field" org-table-edit-field (org-at-table-p)]
20961 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20962 "--"
20963 ("Column"
20964 ["Move Column Left" org-metaleft (org-at-table-p)]
20965 ["Move Column Right" org-metaright (org-at-table-p)]
20966 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20967 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20968 ("Row"
20969 ["Move Row Up" org-metaup (org-at-table-p)]
20970 ["Move Row Down" org-metadown (org-at-table-p)]
20971 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20972 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20973 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20974 "--"
20975 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20976 ("Rectangle"
20977 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20978 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20979 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20980 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20981 "--"
20982 ("Calculate"
20983 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20984 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20985 ["Edit Formulas" org-edit-special (org-at-table-p)]
20986 "--"
20987 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20988 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20989 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20990 "--"
20991 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20992 "--"
20993 ["Sum Column/Rectangle" org-table-sum
20994 (or (org-at-table-p) (org-region-active-p))]
20995 ["Which Column?" org-table-current-column (org-at-table-p)])
20996 ["Debug Formulas"
20997 org-table-toggle-formula-debugger
20998 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20999 ["Show Col/Row Numbers"
21000 org-table-toggle-coordinate-overlays
21001 :style toggle
21002 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21003 "--"
21004 ["Create" org-table-create (and (not (org-at-table-p))
21005 org-enable-table-editor)]
21006 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21007 ["Import from File" org-table-import (not (org-at-table-p))]
21008 ["Export to File" org-table-export (org-at-table-p)]
21009 "--"
21010 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
21012 (easy-menu-define org-org-menu org-mode-map "Org menu"
21013 '("Org"
21014 ("Show/Hide"
21015 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21016 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21017 ["Sparse Tree..." org-sparse-tree t]
21018 ["Reveal Context" org-reveal t]
21019 ["Show All" show-all t]
21020 "--"
21021 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21022 "--"
21023 ["New Heading" org-insert-heading t]
21024 ("Navigate Headings"
21025 ["Up" outline-up-heading t]
21026 ["Next" outline-next-visible-heading t]
21027 ["Previous" outline-previous-visible-heading t]
21028 ["Next Same Level" outline-forward-same-level t]
21029 ["Previous Same Level" outline-backward-same-level t]
21030 "--"
21031 ["Jump" org-goto t])
21032 ("Edit Structure"
21033 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21034 "--"
21035 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21036 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21037 "--"
21038 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21039 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21040 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21041 "--"
21042 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21043 "--"
21044 ["Copy visible text" org-copy-visible t]
21045 "--"
21046 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21047 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21048 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21049 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21050 "--"
21051 ["Sort Region/Children" org-sort t]
21052 "--"
21053 ["Convert to odd levels" org-convert-to-odd-levels t]
21054 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21055 ("Editing"
21056 ["Emphasis..." org-emphasize t]
21057 ["Edit Source Example" org-edit-special t]
21058 "--"
21059 ["Footnote new/jump" org-footnote-action t]
21060 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21061 ("Archive"
21062 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21063 "--"
21064 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21065 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21066 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21068 "--"
21069 ("Hyperlinks"
21070 ["Store Link (Global)" org-store-link t]
21071 ["Find existing link to here" org-occur-link-in-agenda-files t]
21072 ["Insert Link" org-insert-link t]
21073 ["Follow Link" org-open-at-point t]
21074 "--"
21075 ["Next link" org-next-link t]
21076 ["Previous link" org-previous-link t]
21077 "--"
21078 ["Descriptive Links"
21079 org-toggle-link-display
21080 :style radio
21081 :selected org-descriptive-links
21083 ["Literal Links"
21084 org-toggle-link-display
21085 :style radio
21086 :selected (not org-descriptive-links)])
21087 "--"
21088 ("TODO Lists"
21089 ["TODO/DONE/-" org-todo t]
21090 ("Select keyword"
21091 ["Next keyword" org-shiftright (org-at-heading-p)]
21092 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21093 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21094 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21095 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21096 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21097 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21098 "--"
21099 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21100 :selected org-enforce-todo-dependencies :style toggle :active t]
21101 "Settings for tree at point"
21102 ["Do Children sequentially" org-toggle-ordered-property :style radio
21103 :selected (org-entry-get nil "ORDERED")
21104 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21105 ["Do Children parallel" org-toggle-ordered-property :style radio
21106 :selected (not (org-entry-get nil "ORDERED"))
21107 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21108 "--"
21109 ["Set Priority" org-priority t]
21110 ["Priority Up" org-shiftup t]
21111 ["Priority Down" org-shiftdown t]
21112 "--"
21113 ["Get news from all feeds" org-feed-update-all t]
21114 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21115 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21116 ("TAGS and Properties"
21117 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21118 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21119 "--"
21120 ["Set property" org-set-property (not (org-before-first-heading-p))]
21121 ["Column view of properties" org-columns t]
21122 ["Insert Column View DBlock" org-insert-columns-dblock t])
21123 ("Dates and Scheduling"
21124 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21125 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21126 ("Change Date"
21127 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21128 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21129 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21130 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21131 ["Compute Time Range" org-evaluate-time-range t]
21132 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21133 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21134 "--"
21135 ["Custom time format" org-toggle-time-stamp-overlays
21136 :style radio :selected org-display-custom-times]
21137 "--"
21138 ["Goto Calendar" org-goto-calendar t]
21139 ["Date from Calendar" org-date-from-calendar t]
21140 "--"
21141 ["Start/Restart Timer" org-timer-start t]
21142 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21143 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21144 ["Insert Timer String" org-timer t]
21145 ["Insert Timer Item" org-timer-item t])
21146 ("Logging work"
21147 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21148 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21149 ["Clock out" org-clock-out t]
21150 ["Clock cancel" org-clock-cancel t]
21151 "--"
21152 ["Mark as default task" org-clock-mark-default-task t]
21153 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21154 ["Goto running clock" org-clock-goto t]
21155 "--"
21156 ["Display times" org-clock-display t]
21157 ["Create clock table" org-clock-report t]
21158 "--"
21159 ["Record DONE time"
21160 (progn (setq org-log-done (not org-log-done))
21161 (message "Switching to %s will %s record a timestamp"
21162 (car org-done-keywords)
21163 (if org-log-done "automatically" "not")))
21164 :style toggle :selected org-log-done])
21165 "--"
21166 ["Agenda Command..." org-agenda t]
21167 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21168 ("File List for Agenda")
21169 ("Special views current file"
21170 ["TODO Tree" org-show-todo-tree t]
21171 ["Check Deadlines" org-check-deadlines t]
21172 ["Timeline" org-timeline t]
21173 ["Tags/Property tree" org-match-sparse-tree t])
21174 "--"
21175 ["Export/Publish..." org-export-dispatch t]
21176 ("LaTeX"
21177 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21178 :selected org-cdlatex-mode]
21179 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21180 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21181 ["Modify math symbol" org-cdlatex-math-modify
21182 (org-inside-LaTeX-fragment-p)]
21183 ["Insert citation" org-reftex-citation t]
21184 "--"
21185 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21186 "--"
21187 ("MobileOrg"
21188 ["Push Files and Views" org-mobile-push t]
21189 ["Get Captured and Flagged" org-mobile-pull t]
21190 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21191 "--"
21192 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21193 "--"
21194 ("Documentation"
21195 ["Show Version" org-version t]
21196 ["Info Documentation" org-info t])
21197 ("Customize"
21198 ["Browse Org Group" org-customize t]
21199 "--"
21200 ["Expand This Menu" org-create-customize-menu
21201 (fboundp 'customize-menu-create)])
21202 ["Send bug report" org-submit-bug-report t]
21203 "--"
21204 ("Refresh/Reload"
21205 ["Refresh setup current buffer" org-mode-restart t]
21206 ["Reload Org (after update)" org-reload t]
21207 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21210 (defun org-info (&optional node)
21211 "Read documentation for Org-mode in the info system.
21212 With optional NODE, go directly to that node."
21213 (interactive)
21214 (info (format "(org)%s" (or node ""))))
21216 ;;;###autoload
21217 (defun org-submit-bug-report ()
21218 "Submit a bug report on Org-mode via mail.
21220 Don't hesitate to report any problems or inaccurate documentation.
21222 If you don't have setup sending mail from (X)Emacs, please copy the
21223 output buffer into your mail program, as it gives us important
21224 information about your Org-mode version and configuration."
21225 (interactive)
21226 (require 'reporter)
21227 (org-load-modules-maybe)
21228 (org-require-autoloaded-modules)
21229 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21230 (reporter-submit-bug-report
21231 "emacs-orgmode@gnu.org"
21232 (org-version nil 'full)
21233 (let (list)
21234 (save-window-excursion
21235 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21236 (delete-other-windows)
21237 (erase-buffer)
21238 (insert "You are about to submit a bug report to the Org-mode mailing list.
21240 We would like to add your full Org-mode and Outline configuration to the
21241 bug report. This greatly simplifies the work of the maintainer and
21242 other experts on the mailing list.
21244 HOWEVER, some variables you have customized may contain private
21245 information. The names of customers, colleagues, or friends, might
21246 appear in the form of file names, tags, todo states, or search strings.
21247 If you answer yes to the prompt, you might want to check and remove
21248 such private information before sending the email.")
21249 (add-text-properties (point-min) (point-max) '(face org-warning))
21250 (when (yes-or-no-p "Include your Org-mode configuration ")
21251 (mapatoms
21252 (lambda (v)
21253 (and (boundp v)
21254 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21255 (or (and (symbol-value v)
21256 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21257 (and
21258 (get v 'custom-type) (get v 'standard-value)
21259 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21260 (push v list)))))
21261 (kill-buffer (get-buffer "*Warn about privacy*"))
21262 list))
21263 nil nil
21264 "Remember to cover the basics, that is, what you expected to happen and
21265 what in fact did happen. You don't know how to make a good report? See
21267 http://orgmode.org/manual/Feedback.html#Feedback
21269 Your bug report will be posted to the Org-mode mailing list.
21270 ------------------------------------------------------------------------")
21271 (save-excursion
21272 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21273 (replace-match "\\1Bug: \\3 [\\2]")))))
21276 (defun org-install-agenda-files-menu ()
21277 (let ((bl (buffer-list)))
21278 (save-excursion
21279 (while bl
21280 (set-buffer (pop bl))
21281 (if (derived-mode-p 'org-mode) (setq bl nil)))
21282 (when (derived-mode-p 'org-mode)
21283 (easy-menu-change
21284 '("Org") "File List for Agenda"
21285 (append
21286 (list
21287 ["Edit File List" (org-edit-agenda-file-list) t]
21288 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21289 ["Remove Current File from List" org-remove-file t]
21290 ["Cycle through agenda files" org-cycle-agenda-files t]
21291 ["Occur in all agenda files" org-occur-in-agenda-files t]
21292 "--")
21293 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21295 ;;;; Documentation
21297 (defun org-require-autoloaded-modules ()
21298 (interactive)
21299 (mapc 'require
21300 '(org-agenda org-archive org-attach org-clock org-colview org-id
21301 org-table org-timer)))
21303 ;;;###autoload
21304 (defun org-reload (&optional uncompiled)
21305 "Reload all org lisp files.
21306 With prefix arg UNCOMPILED, load the uncompiled versions."
21307 (interactive "P")
21308 (require 'loadhist)
21309 (let* ((org-dir (org-find-library-dir "org"))
21310 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21311 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21312 (remove-re (mapconcat 'identity
21313 (mapcar (lambda (f) (concat "^" f "$"))
21314 (list (if (featurep 'xemacs)
21315 "org-colview"
21316 "org-colview-xemacs")
21317 "org" "org-loaddefs" "org-version"))
21318 "\\|"))
21319 (feats (delete-dups
21320 (mapcar 'file-name-sans-extension
21321 (mapcar 'file-name-nondirectory
21322 (delq nil
21323 (mapcar 'feature-file
21324 features))))))
21325 (lfeat (append
21326 (sort
21327 (setq feats
21328 (delq nil (mapcar
21329 (lambda (f)
21330 (if (and (string-match feature-re f)
21331 (not (string-match remove-re f)))
21332 f nil))
21333 feats)))
21334 'string-lessp)
21335 (list "org-version" "org")))
21336 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21337 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21338 load-uncore load-misses)
21339 (setq load-misses
21340 (delq 't
21341 (mapcar (lambda (f)
21342 (or (org-load-noerror-mustsuffix (concat org-dir f))
21343 (and (string= org-dir contrib-dir)
21344 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21345 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21346 (add-to-list 'load-uncore f 'append)
21349 lfeat)))
21350 (if load-uncore
21351 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21352 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21353 (if load-misses
21354 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21355 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21356 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21358 ;;;###autoload
21359 (defun org-customize ()
21360 "Call the customize function with org as argument."
21361 (interactive)
21362 (org-load-modules-maybe)
21363 (org-require-autoloaded-modules)
21364 (customize-browse 'org))
21366 (defun org-create-customize-menu ()
21367 "Create a full customization menu for Org-mode, insert it into the menu."
21368 (interactive)
21369 (org-load-modules-maybe)
21370 (org-require-autoloaded-modules)
21371 (if (fboundp 'customize-menu-create)
21372 (progn
21373 (easy-menu-change
21374 '("Org") "Customize"
21375 `(["Browse Org group" org-customize t]
21376 "--"
21377 ,(customize-menu-create 'org)
21378 ["Set" Custom-set t]
21379 ["Save" Custom-save t]
21380 ["Reset to Current" Custom-reset-current t]
21381 ["Reset to Saved" Custom-reset-saved t]
21382 ["Reset to Standard Settings" Custom-reset-standard t]))
21383 (message "\"Org\"-menu now contains full customization menu"))
21384 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21386 ;;;; Miscellaneous stuff
21388 ;;; Generally useful functions
21390 (defun org-get-at-bol (property)
21391 "Get text property PROPERTY at beginning of line."
21392 (get-text-property (point-at-bol) property))
21394 (defun org-find-text-property-in-string (prop s)
21395 "Return the first non-nil value of property PROP in string S."
21396 (or (get-text-property 0 prop s)
21397 (get-text-property (or (next-single-property-change 0 prop s) 0)
21398 prop s)))
21400 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21401 "Display the given MESSAGE as a warning."
21402 (if (fboundp 'display-warning)
21403 (display-warning 'org message
21404 (if (featurep 'xemacs) 'warning :warning))
21405 (let ((buf (get-buffer-create "*Org warnings*")))
21406 (with-current-buffer buf
21407 (goto-char (point-max))
21408 (insert "Warning (Org): " message)
21409 (unless (bolp)
21410 (newline)))
21411 (display-buffer buf)
21412 (sit-for 0))))
21414 (defun org-eval (form)
21415 "Eval FORM and return result."
21416 (condition-case error
21417 (eval form)
21418 (error (format "%%![Error: %s]" error))))
21420 (defun org-in-clocktable-p ()
21421 "Check if the cursor is in a clocktable."
21422 (let ((pos (point)) start)
21423 (save-excursion
21424 (end-of-line 1)
21425 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21426 (setq start (match-beginning 0))
21427 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21428 (>= (match-end 0) pos)
21429 start))))
21431 (defun org-in-commented-line ()
21432 "Is point in a line starting with `#'?"
21433 (equal (char-after (point-at-bol)) ?#))
21435 (defun org-in-indented-comment-line ()
21436 "Is point in a line starting with `#' after some white space?"
21437 (save-excursion
21438 (save-match-data
21439 (goto-char (point-at-bol))
21440 (looking-at "[ \t]*#"))))
21442 (defun org-in-verbatim-emphasis ()
21443 (save-match-data
21444 (and (org-in-regexp org-emph-re 2)
21445 (>= (point) (match-beginning 3))
21446 (<= (point) (match-end 4))
21447 (member (match-string 3) '("=" "~")))))
21449 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21450 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21451 (if (and marker (marker-buffer marker)
21452 (buffer-live-p (marker-buffer marker)))
21453 (progn
21454 (org-pop-to-buffer-same-window (marker-buffer marker))
21455 (if (or (> marker (point-max)) (< marker (point-min)))
21456 (widen))
21457 (goto-char marker)
21458 (org-show-context 'org-goto))
21459 (if bookmark
21460 (bookmark-jump bookmark)
21461 (error "Cannot find location"))))
21463 (defun org-quote-csv-field (s)
21464 "Quote field for inclusion in CSV material."
21465 (if (string-match "[\",]" s)
21466 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21469 (defun org-force-self-insert (N)
21470 "Needed to enforce self-insert under remapping."
21471 (interactive "p")
21472 (self-insert-command N))
21474 (defun org-string-width (s)
21475 "Compute width of string, ignoring invisible characters.
21476 This ignores character with invisibility property `org-link', and also
21477 characters with property `org-cwidth', because these will become invisible
21478 upon the next fontification round."
21479 (let (b l)
21480 (when (or (eq t buffer-invisibility-spec)
21481 (assq 'org-link buffer-invisibility-spec))
21482 (while (setq b (text-property-any 0 (length s)
21483 'invisible 'org-link s))
21484 (setq s (concat (substring s 0 b)
21485 (substring s (or (next-single-property-change
21486 b 'invisible s) (length s)))))))
21487 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21488 (setq s (concat (substring s 0 b)
21489 (substring s (or (next-single-property-change
21490 b 'org-cwidth s) (length s))))))
21491 (setq l (string-width s) b -1)
21492 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21493 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21496 (defun org-shorten-string (s maxlength)
21497 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21498 If the string is shorter or has length MAXLENGTH, just return the
21499 original string. If it is longer, the functions finds a space in the
21500 string, breaks this string off at that locations and adds three dots
21501 as ellipsis. Including the ellipsis, the string will not be longer
21502 than MAXLENGTH. If finding a good breaking point in the string does
21503 not work, the string is just chopped off in the middle of a word
21504 if necessary."
21505 (if (<= (length s) maxlength)
21507 (let* ((n (max (- maxlength 4) 1))
21508 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21509 (if (string-match re s)
21510 (concat (match-string 1 s) "...")
21511 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21513 (defun org-get-indentation (&optional line)
21514 "Get the indentation of the current line, interpreting tabs.
21515 When LINE is given, assume it represents a line and compute its indentation."
21516 (if line
21517 (if (string-match "^ *" (org-remove-tabs line))
21518 (match-end 0))
21519 (save-excursion
21520 (beginning-of-line 1)
21521 (skip-chars-forward " \t")
21522 (current-column))))
21524 (defun org-get-string-indentation (s)
21525 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21526 (let ((n -1) (i 0) (w tab-width) c)
21527 (catch 'exit
21528 (while (< (setq n (1+ n)) (length s))
21529 (setq c (aref s n))
21530 (cond ((= c ?\ ) (setq i (1+ i)))
21531 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21532 (t (throw 'exit t)))))
21535 (defun org-remove-tabs (s &optional width)
21536 "Replace tabulators in S with spaces.
21537 Assumes that s is a single line, starting in column 0."
21538 (setq width (or width tab-width))
21539 (while (string-match "\t" s)
21540 (setq s (replace-match
21541 (make-string
21542 (- (* width (/ (+ (match-beginning 0) width) width))
21543 (match-beginning 0)) ?\ )
21544 t t s)))
21547 (defun org-fix-indentation (line ind)
21548 "Fix indentation in LINE.
21549 IND is a cons cell with target and minimum indentation.
21550 If the current indentation in LINE is smaller than the minimum,
21551 leave it alone. If it is larger than ind, set it to the target."
21552 (let* ((l (org-remove-tabs line))
21553 (i (org-get-indentation l))
21554 (i1 (car ind)) (i2 (cdr ind)))
21555 (if (>= i i2) (setq l (substring line i2)))
21556 (if (> i1 0)
21557 (concat (make-string i1 ?\ ) l)
21558 l)))
21560 (defun org-remove-indentation (code &optional n)
21561 "Remove the maximum common indentation from the lines in CODE.
21562 N may optionally be the number of spaces to remove."
21563 (with-temp-buffer
21564 (insert code)
21565 (org-do-remove-indentation n)
21566 (buffer-string)))
21568 (defun org-do-remove-indentation (&optional n)
21569 "Remove the maximum common indentation from the buffer."
21570 (untabify (point-min) (point-max))
21571 (let ((min 10000) re)
21572 (if n
21573 (setq min n)
21574 (goto-char (point-min))
21575 (while (re-search-forward "^ *[^ \n]" nil t)
21576 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21577 (unless (or (= min 0) (= min 10000))
21578 (setq re (format "^ \\{%d\\}" min))
21579 (goto-char (point-min))
21580 (while (re-search-forward re nil t)
21581 (replace-match "")
21582 (end-of-line 1))
21583 min)))
21585 (defun org-fill-template (template alist)
21586 "Find each %key of ALIST in TEMPLATE and replace it."
21587 (let ((case-fold-search nil)
21588 entry key value)
21589 (setq alist (sort (copy-sequence alist)
21590 (lambda (a b) (< (length (car a)) (length (car b))))))
21591 (while (setq entry (pop alist))
21592 (setq template
21593 (replace-regexp-in-string
21594 (concat "%" (regexp-quote (car entry)))
21595 (or (cdr entry) "") template t t)))
21596 template))
21598 (defun org-base-buffer (buffer)
21599 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21600 (if (not buffer)
21601 buffer
21602 (or (buffer-base-buffer buffer)
21603 buffer)))
21605 (defsubst org-trim (s)
21606 "Remove whitespace at the beginning and the end of string S."
21607 (replace-regexp-in-string
21608 "\\`[ \t\n\r]+" ""
21609 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
21611 (defun org-wrap (string &optional width lines)
21612 "Wrap string to either a number of lines, or a width in characters.
21613 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21614 that costs. If there is a word longer than WIDTH, the text is actually
21615 wrapped to the length of that word.
21616 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21617 many lines, whatever width that takes.
21618 The return value is a list of lines, without newlines at the end."
21619 (let* ((words (org-split-string string "[ \t\n]+"))
21620 (maxword (apply 'max (mapcar 'org-string-width words)))
21621 w ll)
21622 (cond (width
21623 (org-do-wrap words (max maxword width)))
21624 (lines
21625 (setq w maxword)
21626 (setq ll (org-do-wrap words maxword))
21627 (if (<= (length ll) lines)
21629 (setq ll words)
21630 (while (> (length ll) lines)
21631 (setq w (1+ w))
21632 (setq ll (org-do-wrap words w)))
21633 ll))
21634 (t (error "Cannot wrap this")))))
21636 (defun org-do-wrap (words width)
21637 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21638 (let (lines line)
21639 (while words
21640 (setq line (pop words))
21641 (while (and words (< (+ (length line) (length (car words))) width))
21642 (setq line (concat line " " (pop words))))
21643 (setq lines (push line lines)))
21644 (nreverse lines)))
21646 (defun org-split-string (string &optional separators)
21647 "Splits STRING into substrings at SEPARATORS.
21648 No empty strings are returned if there are matches at the beginning
21649 and end of string."
21650 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21651 (start 0)
21652 notfirst
21653 (list nil))
21654 (while (and (string-match rexp string
21655 (if (and notfirst
21656 (= start (match-beginning 0))
21657 (< start (length string)))
21658 (1+ start) start))
21659 (< (match-beginning 0) (length string)))
21660 (setq notfirst t)
21661 (or (eq (match-beginning 0) 0)
21662 (and (eq (match-beginning 0) (match-end 0))
21663 (eq (match-beginning 0) start))
21664 (setq list
21665 (cons (substring string start (match-beginning 0))
21666 list)))
21667 (setq start (match-end 0)))
21668 (or (eq start (length string))
21669 (setq list
21670 (cons (substring string start)
21671 list)))
21672 (nreverse list)))
21674 (defun org-quote-vert (s)
21675 "Replace \"|\" with \"\\vert\"."
21676 (while (string-match "|" s)
21677 (setq s (replace-match "\\vert" t t s)))
21680 (defun org-uuidgen-p (s)
21681 "Is S an ID created by UUIDGEN?"
21682 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21684 (defun org-in-src-block-p (&optional inside)
21685 "Whether point is in a code source block.
21686 When INSIDE is non-nil, don't consider we are within a src block
21687 when point is at #+BEGIN_SRC or #+END_SRC."
21688 (let ((case-fold-search t) ov)
21689 (or (and (setq ov (overlays-at (point)))
21690 (memq 'org-block-background
21691 (overlay-properties (car ov))))
21692 (and (not inside)
21693 (save-match-data
21694 (save-excursion
21695 (beginning-of-line)
21696 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21698 (defun org-context ()
21699 "Return a list of contexts of the current cursor position.
21700 If several contexts apply, all are returned.
21701 Each context entry is a list with a symbol naming the context, and
21702 two positions indicating start and end of the context. Possible
21703 contexts are:
21705 :headline anywhere in a headline
21706 :headline-stars on the leading stars in a headline
21707 :todo-keyword on a TODO keyword (including DONE) in a headline
21708 :tags on the TAGS in a headline
21709 :priority on the priority cookie in a headline
21710 :item on the first line of a plain list item
21711 :item-bullet on the bullet/number of a plain list item
21712 :checkbox on the checkbox in a plain list item
21713 :table in an org-mode table
21714 :table-special on a special filed in a table
21715 :table-table in a table.el table
21716 :clocktable in a clocktable
21717 :src-block in a source block
21718 :link on a hyperlink
21719 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21720 :target on a <<target>>
21721 :radio-target on a <<<radio-target>>>
21722 :latex-fragment on a LaTeX fragment
21723 :latex-preview on a LaTeX fragment with overlaid preview image
21725 This function expects the position to be visible because it uses font-lock
21726 faces as a help to recognize the following contexts: :table-special, :link,
21727 and :keyword."
21728 (let* ((f (get-text-property (point) 'face))
21729 (faces (if (listp f) f (list f)))
21730 (case-fold-search t)
21731 (p (point)) clist o)
21732 ;; First the large context
21733 (cond
21734 ((org-at-heading-p t)
21735 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21736 (when (progn
21737 (beginning-of-line 1)
21738 (looking-at org-todo-line-tags-regexp))
21739 (push (org-point-in-group p 1 :headline-stars) clist)
21740 (push (org-point-in-group p 2 :todo-keyword) clist)
21741 (push (org-point-in-group p 4 :tags) clist))
21742 (goto-char p)
21743 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21744 (if (looking-at "\\[#[A-Z0-9]\\]")
21745 (push (org-point-in-group p 0 :priority) clist)))
21747 ((org-at-item-p)
21748 (push (org-point-in-group p 2 :item-bullet) clist)
21749 (push (list :item (point-at-bol)
21750 (save-excursion (org-end-of-item) (point)))
21751 clist)
21752 (and (org-at-item-checkbox-p)
21753 (push (org-point-in-group p 0 :checkbox) clist)))
21755 ((org-at-table-p)
21756 (push (list :table (org-table-begin) (org-table-end)) clist)
21757 (if (memq 'org-formula faces)
21758 (push (list :table-special
21759 (previous-single-property-change p 'face)
21760 (next-single-property-change p 'face)) clist)))
21761 ((org-at-table-p 'any)
21762 (push (list :table-table) clist)))
21763 (goto-char p)
21765 (let ((case-fold-search t))
21766 ;; New the "medium" contexts: clocktables, source blocks
21767 (cond ((org-in-clocktable-p)
21768 (push (list :clocktable
21769 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21770 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21771 (match-beginning 1))
21772 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21773 (match-end 0))) clist))
21774 ((org-in-src-block-p)
21775 (push (list :src-block
21776 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21777 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21778 (match-beginning 1))
21779 (and (search-forward "#+END_SRC" nil t)
21780 (match-beginning 0))) clist))))
21781 (goto-char p)
21783 ;; Now the small context
21784 (cond
21785 ((org-at-timestamp-p)
21786 (push (org-point-in-group p 0 :timestamp) clist))
21787 ((memq 'org-link faces)
21788 (push (list :link
21789 (previous-single-property-change p 'face)
21790 (next-single-property-change p 'face)) clist))
21791 ((memq 'org-special-keyword faces)
21792 (push (list :keyword
21793 (previous-single-property-change p 'face)
21794 (next-single-property-change p 'face)) clist))
21795 ((org-at-target-p)
21796 (push (org-point-in-group p 0 :target) clist)
21797 (goto-char (1- (match-beginning 0)))
21798 (if (looking-at org-radio-target-regexp)
21799 (push (org-point-in-group p 0 :radio-target) clist))
21800 (goto-char p))
21801 ((setq o (car (delq nil
21802 (mapcar
21803 (lambda (x)
21804 (if (memq x org-latex-fragment-image-overlays) x))
21805 (overlays-at (point))))))
21806 (push (list :latex-fragment
21807 (overlay-start o) (overlay-end o)) clist)
21808 (push (list :latex-preview
21809 (overlay-start o) (overlay-end o)) clist))
21810 ((org-inside-LaTeX-fragment-p)
21811 ;; FIXME: positions wrong.
21812 (push (list :latex-fragment (point) (point)) clist)))
21814 (setq clist (nreverse (delq nil clist)))
21815 clist))
21817 ;; FIXME: Compare with at-regexp-p Do we need both?
21818 (defun org-in-regexp (re &optional nlines visually)
21819 "Check if point is inside a match of regexp.
21820 Normally only the current line is checked, but you can include NLINES extra
21821 lines both before and after point into the search.
21822 If VISUALLY is set, require that the cursor is not after the match but
21823 really on, so that the block visually is on the match."
21824 (catch 'exit
21825 (let ((pos (point))
21826 (eol (point-at-eol (+ 1 (or nlines 0))))
21827 (inc (if visually 1 0)))
21828 (save-excursion
21829 (beginning-of-line (- 1 (or nlines 0)))
21830 (while (re-search-forward re eol t)
21831 (if (and (<= (match-beginning 0) pos)
21832 (>= (+ inc (match-end 0)) pos))
21833 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21835 (defun org-at-regexp-p (regexp)
21836 "Is point inside a match of REGEXP in the current line?"
21837 (catch 'exit
21838 (save-excursion
21839 (let ((pos (point)) (end (point-at-eol)))
21840 (beginning-of-line 1)
21841 (while (re-search-forward regexp end t)
21842 (if (and (<= (match-beginning 0) pos)
21843 (>= (match-end 0) pos))
21844 (throw 'exit t)))
21845 nil))))
21847 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21848 "Non-nil when point is between matches of START-RE and END-RE.
21850 Also return a non-nil value when point is on one of the matches.
21852 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21853 buffer positions. Default values are the positions of headlines
21854 surrounding the point.
21856 The functions returns a cons cell whose car (resp. cdr) is the
21857 position before START-RE (resp. after END-RE)."
21858 (save-match-data
21859 (let ((pos (point))
21860 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21861 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21862 beg end)
21863 (save-excursion
21864 ;; Point is on a block when on START-RE or if START-RE can be
21865 ;; found before it...
21866 (and (or (org-at-regexp-p start-re)
21867 (re-search-backward start-re limit-up t))
21868 (setq beg (match-beginning 0))
21869 ;; ... and END-RE after it...
21870 (goto-char (match-end 0))
21871 (re-search-forward end-re limit-down t)
21872 (> (setq end (match-end 0)) pos)
21873 ;; ... without another START-RE in-between.
21874 (goto-char (match-beginning 0))
21875 (not (re-search-backward start-re (1+ beg) t))
21876 ;; Return value.
21877 (cons beg end))))))
21879 (defun org-in-block-p (names)
21880 "Non-nil when point belongs to a block whose name belongs to NAMES.
21882 NAMES is a list of strings containing names of blocks.
21884 Return first block name matched, or nil. Beware that in case of
21885 nested blocks, the returned name may not belong to the closest
21886 block from point."
21887 (save-match-data
21888 (catch 'exit
21889 (let ((case-fold-search t)
21890 (lim-up (save-excursion (outline-previous-heading)))
21891 (lim-down (save-excursion (outline-next-heading))))
21892 (mapc (lambda (name)
21893 (let ((n (regexp-quote name)))
21894 (when (org-between-regexps-p
21895 (concat "^[ \t]*#\\+begin_" n)
21896 (concat "^[ \t]*#\\+end_" n)
21897 lim-up lim-down)
21898 (throw 'exit n))))
21899 names))
21900 nil)))
21902 (defun org-in-drawer-p ()
21903 "Non-nil if point is within a drawer.
21904 If point is within a drawer, return it, as parsed data."
21905 (let ((element (save-match-data (org-element-at-point))))
21906 (while (and element (not (memq (org-element-type element)
21907 '(drawer property-drawer))))
21908 (setq element (org-element-property :parent element)))
21909 element))
21911 (defun org-occur-in-agenda-files (regexp &optional nlines)
21912 "Call `multi-occur' with buffers for all agenda files."
21913 (interactive "sOrg-files matching: \np")
21914 (let* ((files (org-agenda-files))
21915 (tnames (mapcar 'file-truename files))
21916 (extra org-agenda-text-search-extra-files)
21918 (when (eq (car extra) 'agenda-archives)
21919 (setq extra (cdr extra))
21920 (setq files (org-add-archive-files files)))
21921 (while (setq f (pop extra))
21922 (unless (member (file-truename f) tnames)
21923 (add-to-list 'files f 'append)
21924 (add-to-list 'tnames (file-truename f) 'append)))
21925 (multi-occur
21926 (mapcar (lambda (x)
21927 (with-current-buffer
21928 (or (get-file-buffer x) (find-file-noselect x))
21929 (widen)
21930 (current-buffer)))
21931 files)
21932 regexp)))
21934 (if (boundp 'occur-mode-find-occurrence-hook)
21935 ;; Emacs 23
21936 (add-hook 'occur-mode-find-occurrence-hook
21937 (lambda ()
21938 (when (derived-mode-p 'org-mode)
21939 (org-reveal))))
21940 ;; Emacs 22
21941 (defadvice occur-mode-goto-occurrence
21942 (after org-occur-reveal activate)
21943 (and (derived-mode-p 'org-mode) (org-reveal)))
21944 (defadvice occur-mode-goto-occurrence-other-window
21945 (after org-occur-reveal activate)
21946 (and (derived-mode-p 'org-mode) (org-reveal)))
21947 (defadvice occur-mode-display-occurrence
21948 (after org-occur-reveal activate)
21949 (when (derived-mode-p 'org-mode)
21950 (let ((pos (occur-mode-find-occurrence)))
21951 (with-current-buffer (marker-buffer pos)
21952 (save-excursion
21953 (goto-char pos)
21954 (org-reveal)))))))
21956 (defun org-occur-link-in-agenda-files ()
21957 "Create a link and search for it in the agendas.
21958 The link is not stored in `org-stored-links', it is just created
21959 for the search purpose."
21960 (interactive)
21961 (let ((link (condition-case nil
21962 (org-store-link nil)
21963 (error "Unable to create a link to here"))))
21964 (org-occur-in-agenda-files (regexp-quote link))))
21966 (defun org-reverse-string (string)
21967 "Return the reverse of STRING."
21968 (apply 'string (reverse (string-to-list string))))
21970 (defun org-uniquify-alist (alist)
21971 "Merge elements of ALIST with the same key.
21973 For example, in this alist:
21975 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21976 => '((a 1 3) (b 2))
21978 merge (a 1) and (a 3) into (a 1 3).
21980 The function returns the new ALIST."
21981 (let (rtn)
21982 (mapc
21983 (lambda (e)
21984 (let (n)
21985 (if (not (assoc (car e) rtn))
21986 (push e rtn)
21987 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21988 (setq rtn (assq-delete-all (car e) rtn))
21989 (push n rtn))))
21990 alist)
21991 rtn))
21993 (defun org-delete-all (elts list)
21994 "Remove all elements in ELTS from LIST."
21995 (while elts
21996 (setq list (delete (pop elts) list)))
21997 list)
21999 (defun org-count (cl-item cl-seq)
22000 "Count the number of occurrences of ITEM in SEQ.
22001 Taken from `count' in cl-seq.el with all keyword arguments removed."
22002 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22003 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22004 (while (< cl-start cl-end)
22005 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22006 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22007 (setq cl-start (1+ cl-start)))
22008 cl-count))
22010 (defun org-remove-if (predicate seq)
22011 "Remove everything from SEQ that fulfills PREDICATE."
22012 (let (res e)
22013 (while seq
22014 (setq e (pop seq))
22015 (if (not (funcall predicate e)) (push e res)))
22016 (nreverse res)))
22018 (defun org-remove-if-not (predicate seq)
22019 "Remove everything from SEQ that does not fulfill PREDICATE."
22020 (let (res e)
22021 (while seq
22022 (setq e (pop seq))
22023 (if (funcall predicate e) (push e res)))
22024 (nreverse res)))
22026 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22027 "Reduce two-argument FUNCTION across SEQ.
22028 Taken from `reduce' in cl-seq.el with all keyword arguments but
22029 \":initial-value\" removed."
22030 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22031 (cadr (memq :initial-value cl-keys)))
22032 (cl-seq (pop cl-seq))
22033 (t (funcall cl-func)))))
22034 (while cl-seq
22035 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22036 cl-accum))
22038 (defun org-every (pred seq)
22039 "Return true if PREDICATE is true of every element of SEQ.
22040 Adapted from `every' in cl.el."
22041 (catch 'org-every
22042 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22045 (defun org-some (pred seq)
22046 "Return true if PREDICATE is true of any element of SEQ.
22047 Adapted from `some' in cl.el."
22048 (catch 'org-some
22049 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22050 nil))
22052 (defun org-back-over-empty-lines ()
22053 "Move backwards over whitespace, to the beginning of the first empty line.
22054 Returns the number of empty lines passed."
22055 (let ((pos (point)))
22056 (if (cdr (assoc 'heading org-blank-before-new-entry))
22057 (skip-chars-backward " \t\n\r")
22058 (unless (eobp)
22059 (forward-line -1)))
22060 (beginning-of-line 2)
22061 (goto-char (min (point) pos))
22062 (count-lines (point) pos)))
22064 (defun org-skip-whitespace ()
22065 (skip-chars-forward " \t\n\r"))
22067 (defun org-point-in-group (point group &optional context)
22068 "Check if POINT is in match-group GROUP.
22069 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22070 match. If the match group does not exist or point is not inside it,
22071 return nil."
22072 (and (match-beginning group)
22073 (>= point (match-beginning group))
22074 (<= point (match-end group))
22075 (if context
22076 (list context (match-beginning group) (match-end group))
22077 t)))
22079 (defun org-switch-to-buffer-other-window (&rest args)
22080 "Switch to buffer in a second window on the current frame.
22081 In particular, do not allow pop-up frames.
22082 Returns the newly created buffer."
22083 (org-no-popups
22084 (apply 'switch-to-buffer-other-window args)))
22086 (defun org-combine-plists (&rest plists)
22087 "Create a single property list from all plists in PLISTS.
22088 The process starts by copying the first list, and then setting properties
22089 from the other lists. Settings in the last list are the most significant
22090 ones and overrule settings in the other lists."
22091 (let ((rtn (copy-sequence (pop plists)))
22092 p v ls)
22093 (while plists
22094 (setq ls (pop plists))
22095 (while ls
22096 (setq p (pop ls) v (pop ls))
22097 (setq rtn (plist-put rtn p v))))
22098 rtn))
22100 (defun org-replace-escapes (string table)
22101 "Replace %-escapes in STRING with values in TABLE.
22102 TABLE is an association list with keys like \"%a\" and string values.
22103 The sequences in STRING may contain normal field width and padding information,
22104 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22105 so values can contain further %-escapes if they are define later in TABLE."
22106 (let ((tbl (copy-alist table))
22107 (case-fold-search nil)
22108 (pchg 0)
22109 e re rpl)
22110 (while (setq e (pop tbl))
22111 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22112 (when (and (cdr e) (string-match re (cdr e)))
22113 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22114 (safe "SREF"))
22115 (add-text-properties 0 3 (list 'sref sref) safe)
22116 (setcdr e (replace-match safe t t (cdr e)))))
22117 (while (string-match re string)
22118 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22119 (cdr e)))
22120 (setq string (replace-match rpl t t string))))
22121 (while (setq pchg (next-property-change pchg string))
22122 (let ((sref (get-text-property pchg 'sref string)))
22123 (when (and sref (string-match "SREF" string pchg))
22124 (setq string (replace-match sref t t string)))))
22125 string))
22127 (defun org-sublist (list start end)
22128 "Return a section of LIST, from START to END.
22129 Counting starts at 1."
22130 (let (rtn (c start))
22131 (setq list (nthcdr (1- start) list))
22132 (while (and list (<= c end))
22133 (push (pop list) rtn)
22134 (setq c (1+ c)))
22135 (nreverse rtn)))
22137 (defun org-find-base-buffer-visiting (file)
22138 "Like `find-buffer-visiting' but always return the base buffer and
22139 not an indirect buffer."
22140 (let ((buf (or (get-file-buffer file)
22141 (find-buffer-visiting file))))
22142 (if buf
22143 (or (buffer-base-buffer buf) buf)
22144 nil)))
22146 (defun org-image-file-name-regexp (&optional extensions)
22147 "Return regexp matching the file names of images.
22148 If EXTENSIONS is given, only match these."
22149 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22150 (image-file-name-regexp)
22151 (let ((image-file-name-extensions
22152 (or extensions
22153 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22154 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22155 (concat "\\."
22156 (regexp-opt (nconc (mapcar 'upcase
22157 image-file-name-extensions)
22158 image-file-name-extensions)
22160 "\\'"))))
22162 (defun org-file-image-p (file &optional extensions)
22163 "Return non-nil if FILE is an image."
22164 (save-match-data
22165 (string-match (org-image-file-name-regexp extensions) file)))
22167 (defun org-get-cursor-date (&optional with-time)
22168 "Return the date at cursor in as a time.
22169 This works in the calendar and in the agenda, anywhere else it just
22170 returns the current time.
22171 If WITH-TIME is non-nil, returns the time of the event at point (in
22172 the agenda) or the current time of the day."
22173 (let (date day defd tp tm hod mod)
22174 (when with-time
22175 (setq tp (get-text-property (point) 'time))
22176 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22177 (setq hod (string-to-number (match-string 1 tp))
22178 mod (string-to-number (match-string 2 tp))))
22179 (or tp (setq hod (nth 2 (decode-time (current-time)))
22180 mod (nth 1 (decode-time (current-time))))))
22181 (cond
22182 ((eq major-mode 'calendar-mode)
22183 (setq date (calendar-cursor-to-date)
22184 defd (encode-time 0 (or mod 0) (or hod 0)
22185 (nth 1 date) (nth 0 date) (nth 2 date))))
22186 ((eq major-mode 'org-agenda-mode)
22187 (setq day (get-text-property (point) 'day))
22188 (if day
22189 (setq date (calendar-gregorian-from-absolute day)
22190 defd (encode-time 0 (or mod 0) (or hod 0)
22191 (nth 1 date) (nth 0 date) (nth 2 date))))))
22192 (or defd (current-time))))
22194 (defun org-mark-subtree (&optional up)
22195 "Mark the current subtree.
22196 This puts point at the start of the current subtree, and mark at
22197 the end. If a numeric prefix UP is given, move up into the
22198 hierarchy of headlines by UP levels before marking the subtree."
22199 (interactive "P")
22200 (org-with-limited-levels
22201 (cond ((org-at-heading-p) (beginning-of-line))
22202 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22203 (t (outline-previous-visible-heading 1))))
22204 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22205 (if (org-called-interactively-p 'any)
22206 (call-interactively 'org-mark-element)
22207 (org-mark-element)))
22210 ;;; Indentation
22212 (defun org--get-expected-indentation (element contentsp)
22213 "Expected indentation column for current line, according to ELEMENT.
22214 ELEMENT is an element containing point. CONTENTSP is non-nil
22215 when indentation is to be computed according to contents of
22216 ELEMENT."
22217 (let ((type (org-element-type element))
22218 (start (org-element-property :begin element)))
22219 (org-with-wide-buffer
22220 (cond
22221 (contentsp
22222 (case type
22223 (footnote-definition 0)
22224 ((headline inlinetask nil)
22225 (if (not org-adapt-indentation) 0
22226 (let ((level (org-current-level)))
22227 (if level (1+ level) 0))))
22228 ((item plain list)
22229 (org-list-item-body-column
22230 (or (org-element-property :post-affiliated element) start)))
22231 (otherwise
22232 (goto-char start)
22233 (org-get-indentation))))
22234 ((memq type '(headline inlinetask nil))
22235 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22236 (org--get-expected-indentation element t)
22238 ((eq type 'footnote-definition) 0)
22239 ;; First paragraph of a footnote definition or an item.
22240 ;; Indent like parent.
22241 ((< (line-beginning-position) start)
22242 (org--get-expected-indentation
22243 (org-element-property :parent element) t))
22244 ;; At first line: indent according to previous sibling, if any,
22245 ;; ignoring footnote definitions and inline tasks, or parent's
22246 ;; contents.
22247 ((= (line-beginning-position) start)
22248 (catch 'exit
22249 (while t
22250 (if (= (point-min) start) (throw 'exit 0)
22251 (goto-char (1- start))
22252 (let ((previous (org-element-at-point)))
22253 (while (let ((parent (org-element-property :parent previous)))
22254 (and parent
22255 (setq previous parent)
22256 (<= (org-element-property :end parent) start))))
22257 (cond ((or (not previous)
22258 (> (org-element-property :end previous) start))
22259 (throw 'exit (org--get-expected-indentation previous t)))
22260 ((memq (org-element-type previous)
22261 '(footnote-definition inlinetask))
22262 (setq start (org-element-property :begin previous)))
22263 (t (goto-char (org-element-property :begin previous))
22264 (throw 'exit (org-get-indentation)))))))))
22265 ;; Otherwise, move to the first non-blank line above.
22267 (beginning-of-line)
22268 (let ((pos (point)))
22269 (skip-chars-backward " \r\t\n")
22270 (cond
22271 ;; Two blank lines end a footnote definition or a plain
22272 ;; list. When we indent an empty line after them, the
22273 ;; containing list or footnote definition is over, so it
22274 ;; qualifies as a previous sibling. Therefore, we indent
22275 ;; like its first line.
22276 ((and (memq type '(footnote-definition plain-list))
22277 (> (count-lines (point) pos) 2))
22278 (goto-char start)
22279 (org-get-indentation))
22280 ;; Line above is the first one of a paragraph at the
22281 ;; beginning of an item or a footnote definition. Indent
22282 ;; like parent.
22283 ((< (line-beginning-position) start)
22284 (org--get-expected-indentation
22285 (org-element-property :parent element) t))
22286 ;; POS is after contents in a greater element. Indent like
22287 ;; the beginning of the element.
22289 ;; As a special case, if point is at the end of a footnote
22290 ;; definition or an item, indent like the very last element
22291 ;; within.
22292 ((let ((cend (org-element-property :contents-end element)))
22293 (and cend (<= cend pos)))
22294 (if (memq type '(footnote-definition item plain-list))
22295 (org--get-expected-indentation (org-element-at-point) nil)
22296 (goto-char start)
22297 (org-get-indentation)))
22298 ;; In any other case, indent like the current line.
22299 (t (org-get-indentation)))))))))
22301 (defun org--align-node-property ()
22302 "Align node property at point.
22303 Alignment is done according to `org-property-format', which see."
22304 (when (save-excursion
22305 (beginning-of-line)
22306 (looking-at org-property-re))
22307 (replace-match
22308 (concat (match-string 4)
22309 (format org-property-format (match-string 1) (match-string 3)))
22310 t t)))
22312 (defun org-indent-line ()
22313 "Indent line depending on context.
22315 Indentation is done according to the following rules:
22317 - Footnote definitions, headlines and inline tasks have to
22318 start at column 0.
22320 - On the very first line of an element, consider, in order, the
22321 next rules until one matches:
22323 1. If there's a sibling element before, ignoring footnote
22324 definitions and inline tasks, indent like its first line.
22326 2. If element has a parent, indent like its contents. More
22327 precisely, if parent is an item, indent after the
22328 description part, if any, or the bullet (see
22329 ``org-list-description-max-indent'). Else, indent like
22330 parent's first line.
22332 3. Otherwise, indent relatively to current level, if
22333 `org-adapt-indentation' is non-nil, or to left margin.
22335 - On a blank line at the end of a plain list, an item, or
22336 a footnote definition, indent like the very last element
22337 within.
22339 - In the code part of a source block, use language major mode
22340 to indent current line if `org-src-tab-acts-natively' is
22341 non-nil. If it is nil, do nothing.
22343 - Otherwise, indent like the first non-blank line above.
22345 The function doesn't indent an item as it could break the whole
22346 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22347 \\[org-shiftmetaright].
22349 Also align node properties according to `org-property-format'."
22350 (interactive)
22351 (cond
22352 (orgstruct-is-++
22353 (let ((indent-line-function
22354 (cadadr (assq 'indent-line-function org-fb-vars))))
22355 (indent-according-to-mode)))
22356 ((org-at-heading-p) 'noindent)
22358 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22359 (type (org-element-type element)))
22360 (cond ((and (memq type '(plain-list item))
22361 (= (line-beginning-position)
22362 (or (org-element-property :post-affiliated element)
22363 (org-element-property :begin element))))
22364 'noindent)
22365 ((and (eq type 'src-block)
22366 (> (line-beginning-position)
22367 (org-element-property :post-affiliated element))
22368 (< (line-beginning-position)
22369 (org-with-wide-buffer
22370 (goto-char (org-element-property :end element))
22371 (skip-chars-backward " \r\t\n")
22372 (line-beginning-position))))
22373 (if (not org-src-tab-acts-natively) 'noindent
22374 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
22375 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))))
22377 (let ((column (org--get-expected-indentation element nil)))
22378 ;; Preserve current column.
22379 (if (<= (current-column) (current-indentation))
22380 (org-indent-line-to column)
22381 (save-excursion (org-indent-line-to column))))
22382 ;; Align node property. Also preserve current column.
22383 (when (eq type 'node-property)
22384 (let ((column (current-column)))
22385 (org--align-node-property)
22386 (org-move-to-column column)))))))))
22388 (defun org-indent-region (start end)
22389 "Indent each non-blank line in the region.
22390 Called from a program, START and END specify the region to
22391 indent. The function will not indent contents of example blocks,
22392 verse blocks and export blocks as leading white spaces are
22393 assumed to be significant there."
22394 (interactive "r")
22395 (save-excursion
22396 (goto-char start)
22397 (beginning-of-line)
22398 (let ((indent-to
22399 (lambda (ind pos)
22400 ;; Set IND as indentation for all lines between point and
22401 ;; POS or END, whichever comes first. Blank lines are
22402 ;; ignored. Leave point after POS once done.
22403 (let ((limit (copy-marker (min end pos))))
22404 (while (< (point) limit)
22405 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22406 (forward-line))
22407 (set-marker limit nil))))
22408 (end (copy-marker end)))
22409 (while (< (point) end)
22410 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22411 (let* ((element (org-element-at-point))
22412 (type (org-element-type element))
22413 (element-end (copy-marker (org-element-property :end element)))
22414 (ind (org--get-expected-indentation element nil)))
22415 (if (or (memq type '(paragraph table table-row))
22416 (not (or (org-element-property :contents-begin element)
22417 (memq type
22418 '(example-block export-block src-block)))))
22419 ;; Elements here are indented as a single block. Also
22420 ;; align node properties.
22421 (progn
22422 (when (eq type 'node-property)
22423 (org--align-node-property)
22424 (beginning-of-line))
22425 (funcall indent-to ind element-end))
22426 ;; Elements in this category consist of three parts:
22427 ;; before the contents, the contents, and after the
22428 ;; contents. The contents are treated specially,
22429 ;; according to the element type, or not indented at
22430 ;; all. Other parts are indented as a single block.
22431 (let* ((post (copy-marker
22432 (or (org-element-property :post-affiliated element)
22433 (org-element-property :begin element))))
22434 (cbeg
22435 (copy-marker
22436 (cond
22437 ((not (org-element-property :contents-begin element))
22438 ;; Fake contents for source blocks.
22439 (org-with-wide-buffer
22440 (goto-char post)
22441 (forward-line)
22442 (point)))
22443 ((memq type '(footnote-definition item plain-list))
22444 ;; Contents in these elements could start on
22445 ;; the same line as the beginning of the
22446 ;; element. Make sure we start indenting
22447 ;; from the second line.
22448 (org-with-wide-buffer
22449 (goto-char post)
22450 (forward-line)
22451 (point)))
22452 (t (org-element-property :contents-begin element)))))
22453 (cend (copy-marker
22454 (or (org-element-property :contents-end element)
22455 ;; Fake contents for source blocks.
22456 (org-with-wide-buffer
22457 (goto-char element-end)
22458 (skip-chars-backward " \r\t\n")
22459 (line-beginning-position))))))
22460 (funcall indent-to ind cbeg)
22461 (when (< (point) end)
22462 (case type
22463 ((example-block export-block verse-block))
22464 (src-block
22465 ;; In a source block, indent source code according
22466 ;; to language major mode, but only if
22467 ;; `org-src-tab-acts-natively' is non-nil.
22468 (when (and (< (point) end) org-src-tab-acts-natively)
22469 (ignore-errors
22470 (let (org-src-strip-leading-and-trailing-blank-lines
22471 ;; Region boundaries in edit buffer.
22472 (start (1+ (- (point) cbeg)))
22473 (end (- (min cend end) cbeg)))
22474 (org-babel-do-in-edit-buffer
22475 (indent-region start end))))))
22476 (t (org-indent-region (point) (min cend end))))
22477 (goto-char (min cend end))
22478 (when (< (point) end) (funcall indent-to ind element-end)))
22479 (set-marker post nil)
22480 (set-marker cbeg nil)
22481 (set-marker cend nil)))
22482 (set-marker element-end nil))))
22483 (set-marker end nil))))
22485 (defun org-indent-drawer ()
22486 "Indent the drawer at point."
22487 (interactive)
22488 (unless (save-excursion
22489 (beginning-of-line)
22490 (org-looking-at-p org-drawer-regexp))
22491 (user-error "Not at a drawer"))
22492 (let ((element (org-element-at-point)))
22493 (unless (memq (org-element-type element) '(drawer property-drawer))
22494 (user-error "Not at a drawer"))
22495 (org-with-wide-buffer
22496 (org-indent-region (org-element-property :begin element)
22497 (org-element-property :end element))))
22498 (message "Drawer at point indented"))
22500 (defun org-indent-block ()
22501 "Indent the block at point."
22502 (interactive)
22503 (unless (save-excursion
22504 (beginning-of-line)
22505 (let ((case-fold-search t))
22506 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22507 (user-error "Not at a block"))
22508 (let ((element (org-element-at-point)))
22509 (unless (memq (org-element-type element)
22510 '(comment-block center-block example-block export-block
22511 quote-block special-block src-block
22512 verse-block))
22513 (user-error "Not at a block"))
22514 (org-with-wide-buffer
22515 (org-indent-region (org-element-property :begin element)
22516 (org-element-property :end element))))
22517 (message "Block at point indented"))
22520 ;;; Filling
22522 ;; We use our own fill-paragraph and auto-fill functions.
22524 ;; `org-fill-paragraph' relies on adaptive filling and context
22525 ;; checking. Appropriate `fill-prefix' is computed with
22526 ;; `org-adaptive-fill-function'.
22528 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22529 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22530 ;; `org-adaptive-fill-function' value. Internally,
22531 ;; `org-comment-line-break-function' breaks the line.
22533 ;; `org-setup-filling' installs filling and auto-filling related
22534 ;; variables during `org-mode' initialization.
22536 (defvar org-element-paragraph-separate) ; org-element.el
22537 (defun org-setup-filling ()
22538 (require 'org-element)
22539 ;; Prevent auto-fill from inserting unwanted new items.
22540 (when (boundp 'fill-nobreak-predicate)
22541 (org-set-local
22542 'fill-nobreak-predicate
22543 (org-uniquify
22544 (append fill-nobreak-predicate
22545 '(org-fill-line-break-nobreak-p
22546 org-fill-paragraph-with-timestamp-nobreak-p)))))
22547 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22548 (org-set-local 'paragraph-start paragraph-ending)
22549 (org-set-local 'paragraph-separate paragraph-ending))
22550 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22551 (org-set-local 'auto-fill-inhibit-regexp nil)
22552 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22553 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22554 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22556 (defun org-fill-line-break-nobreak-p ()
22557 "Non-nil when a new line at point would create an Org line break."
22558 (save-excursion
22559 (skip-chars-backward "[ \t]")
22560 (skip-chars-backward "\\\\")
22561 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22563 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22564 "Non-nil when a new line at point would split a timestamp."
22565 (and (org-at-timestamp-p t)
22566 (not (looking-at org-ts-regexp-both))))
22568 (declare-function message-in-body-p "message" ())
22569 (defvar orgtbl-line-start-regexp) ; From org-table.el
22570 (defun org-adaptive-fill-function ()
22571 "Compute a fill prefix for the current line.
22572 Return fill prefix, as a string, or nil if current line isn't
22573 meant to be filled. For convenience, if `adaptive-fill-regexp'
22574 matches in paragraphs or comments, use it."
22575 (catch 'exit
22576 (when (derived-mode-p 'message-mode)
22577 (save-excursion
22578 (beginning-of-line)
22579 (cond ((or (not (message-in-body-p))
22580 (looking-at orgtbl-line-start-regexp))
22581 (throw 'exit nil))
22582 ((looking-at message-cite-prefix-regexp)
22583 (throw 'exit (match-string-no-properties 0)))
22584 ((looking-at org-outline-regexp)
22585 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22586 (org-with-wide-buffer
22587 (let* ((p (line-beginning-position))
22588 (element (save-excursion
22589 (beginning-of-line)
22590 (or (ignore-errors (org-element-at-point))
22591 (user-error "An element cannot be parsed line %d"
22592 (line-number-at-pos (point))))))
22593 (type (org-element-type element))
22594 (post-affiliated (org-element-property :post-affiliated element)))
22595 (unless (and post-affiliated (< p post-affiliated))
22596 (case type
22597 (comment
22598 (save-excursion
22599 (beginning-of-line)
22600 (looking-at "[ \t]*")
22601 (concat (match-string 0) "# ")))
22602 (footnote-definition "")
22603 ((item plain-list)
22604 (make-string (org-list-item-body-column
22605 (or post-affiliated
22606 (org-element-property :begin element)))
22607 ? ))
22608 (paragraph
22609 ;; Fill prefix is usually the same as the current line,
22610 ;; unless the paragraph is at the beginning of an item.
22611 (let ((parent (org-element-property :parent element)))
22612 (save-excursion
22613 (beginning-of-line)
22614 (cond ((eq (org-element-type parent) 'item)
22615 (make-string (org-list-item-body-column
22616 (org-element-property :begin parent))
22617 ? ))
22618 ((and adaptive-fill-regexp
22619 ;; Locally disable
22620 ;; `adaptive-fill-function' to let
22621 ;; `fill-context-prefix' handle
22622 ;; `adaptive-fill-regexp' variable.
22623 (let (adaptive-fill-function)
22624 (fill-context-prefix
22625 post-affiliated
22626 (org-element-property :end element)))))
22627 ((looking-at "[ \t]+") (match-string 0))
22628 (t "")))))
22629 (comment-block
22630 ;; Only fill contents if P is within block boundaries.
22631 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22632 (forward-line)
22633 (point)))
22634 (cend (save-excursion
22635 (goto-char (org-element-property :end element))
22636 (skip-chars-backward " \r\t\n")
22637 (line-beginning-position))))
22638 (when (and (>= p cbeg) (< p cend))
22639 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22640 (match-string 0)
22641 ""))))))))))
22643 (declare-function message-goto-body "message" ())
22644 (defvar message-cite-prefix-regexp) ; From message.el
22645 (defun org-fill-paragraph (&optional justify)
22646 "Fill element at point, when applicable.
22648 This function only applies to comment blocks, comments, example
22649 blocks and paragraphs. Also, as a special case, re-align table
22650 when point is at one.
22652 If JUSTIFY is non-nil (interactively, with prefix argument),
22653 justify as well. If `sentence-end-double-space' is non-nil, then
22654 period followed by one space does not end a sentence, so don't
22655 break a line there. The variable `fill-column' controls the
22656 width for filling.
22658 For convenience, when point is at a plain list, an item or
22659 a footnote definition, try to fill the first paragraph within."
22660 (interactive)
22661 (if (and (derived-mode-p 'message-mode)
22662 (or (not (message-in-body-p))
22663 (save-excursion (move-beginning-of-line 1)
22664 (looking-at message-cite-prefix-regexp))))
22665 ;; First ensure filling is correct in message-mode.
22666 (let ((fill-paragraph-function
22667 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22668 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22669 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22670 (paragraph-separate
22671 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22672 (fill-paragraph nil))
22673 (with-syntax-table org-mode-transpose-word-syntax-table
22674 ;; Move to end of line in order to get the first paragraph
22675 ;; within a plain list or a footnote definition.
22676 (let ((element (save-excursion
22677 (end-of-line)
22678 (or (ignore-errors (org-element-at-point))
22679 (user-error "An element cannot be parsed line %d"
22680 (line-number-at-pos (point)))))))
22681 ;; First check if point is in a blank line at the beginning of
22682 ;; the buffer. In that case, ignore filling.
22683 (case (org-element-type element)
22684 ;; Use major mode filling function is src blocks.
22685 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22686 ;; Align Org tables, leave table.el tables as-is.
22687 (table-row (org-table-align) t)
22688 (table
22689 (when (eq (org-element-property :type element) 'org)
22690 (save-excursion
22691 (goto-char (org-element-property :post-affiliated element))
22692 (org-table-align)))
22694 (paragraph
22695 ;; Paragraphs may contain `line-break' type objects.
22696 (let ((beg (max (point-min)
22697 (org-element-property :contents-begin element)))
22698 (end (min (point-max)
22699 (org-element-property :contents-end element))))
22700 ;; Do nothing if point is at an affiliated keyword.
22701 (if (< (line-end-position) beg) t
22702 (when (derived-mode-p 'message-mode)
22703 ;; In `message-mode', do not fill following citation
22704 ;; in current paragraph nor text before message body.
22705 (let ((body-start (save-excursion (message-goto-body))))
22706 (when body-start (setq beg (max body-start beg))))
22707 (when (save-excursion
22708 (re-search-forward
22709 (concat "^" message-cite-prefix-regexp) end t))
22710 (setq end (match-beginning 0))))
22711 ;; Fill paragraph, taking line breaks into account.
22712 ;; For that, slice the paragraph using line breaks as
22713 ;; separators, and fill the parts in reverse order to
22714 ;; avoid messing with markers.
22715 (save-excursion
22716 (goto-char end)
22717 (mapc
22718 (lambda (pos)
22719 (fill-region-as-paragraph pos (point) justify)
22720 (goto-char pos))
22721 ;; Find the list of ending positions for line breaks
22722 ;; in the current paragraph. Add paragraph
22723 ;; beginning to include first slice.
22724 (nreverse
22725 (cons beg
22726 (org-element-map
22727 (org-element--parse-objects
22728 beg end nil (org-element-restriction 'paragraph))
22729 'line-break
22730 (lambda (lb) (org-element-property :end lb)))))))
22731 t)))
22732 ;; Contents of `comment-block' type elements should be
22733 ;; filled as plain text, but only if point is within block
22734 ;; markers.
22735 (comment-block
22736 (let* ((case-fold-search t)
22737 (beg (save-excursion
22738 (goto-char (org-element-property :begin element))
22739 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22740 (forward-line)
22741 (point)))
22742 (end (save-excursion
22743 (goto-char (org-element-property :end element))
22744 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22745 (line-beginning-position))))
22746 (if (or (< (point) beg) (> (point) end)) t
22747 (fill-region-as-paragraph
22748 (save-excursion (end-of-line)
22749 (re-search-backward "^[ \t]*$" beg 'move)
22750 (line-beginning-position))
22751 (save-excursion (beginning-of-line)
22752 (re-search-forward "^[ \t]*$" end 'move)
22753 (line-beginning-position))
22754 justify))))
22755 ;; Fill comments.
22756 (comment
22757 (let ((begin (org-element-property :post-affiliated element))
22758 (end (org-element-property :end element)))
22759 (when (and (>= (point) begin) (<= (point) end))
22760 (let ((begin (save-excursion
22761 (end-of-line)
22762 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22763 (progn (forward-line) (point))
22764 begin)))
22765 (end (save-excursion
22766 (end-of-line)
22767 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22768 (1- (line-beginning-position))
22769 (skip-chars-backward " \r\t\n")
22770 (line-end-position)))))
22771 ;; Do not fill comments when at a blank line.
22772 (when (> end begin)
22773 (let ((fill-prefix
22774 (save-excursion
22775 (beginning-of-line)
22776 (looking-at "[ \t]*#")
22777 (let ((comment-prefix (match-string 0)))
22778 (goto-char (match-end 0))
22779 (if (looking-at adaptive-fill-regexp)
22780 (concat comment-prefix (match-string 0))
22781 (concat comment-prefix " "))))))
22782 (save-excursion
22783 (fill-region-as-paragraph begin end justify))))))
22785 ;; Ignore every other element.
22786 (otherwise t))))))
22788 (defun org-auto-fill-function ()
22789 "Auto-fill function."
22790 ;; Check if auto-filling is meaningful.
22791 (let ((fc (current-fill-column)))
22792 (when (and fc (> (current-column) fc))
22793 (let* ((fill-prefix (org-adaptive-fill-function))
22794 ;; Enforce empty fill prefix, if required. Otherwise, it
22795 ;; will be computed again.
22796 (adaptive-fill-mode (not (equal fill-prefix ""))))
22797 (when fill-prefix (do-auto-fill))))))
22799 (defun org-comment-line-break-function (&optional soft)
22800 "Break line at point and indent, continuing comment if within one.
22801 The inserted newline is marked hard if variable
22802 `use-hard-newlines' is true, unless optional argument SOFT is
22803 non-nil."
22804 (if soft (insert-and-inherit ?\n) (newline 1))
22805 (save-excursion (forward-char -1) (delete-horizontal-space))
22806 (delete-horizontal-space)
22807 (indent-to-left-margin)
22808 (insert-before-markers-and-inherit fill-prefix))
22811 ;;; Fixed Width Areas
22813 (defun org-toggle-fixed-width ()
22814 "Toggle fixed-width markup.
22816 Add or remove fixed-width markup on current line, whenever it
22817 makes sense. Return an error otherwise.
22819 If a region is active and if it contains only fixed-width areas
22820 or blank lines, remove all fixed-width markup in it. If the
22821 region contains anything else, convert all non-fixed-width lines
22822 to fixed-width ones.
22824 Blank lines at the end of the region are ignored unless the
22825 region only contains such lines."
22826 (interactive)
22827 (if (not (org-region-active-p))
22828 ;; No region:
22830 ;; Remove fixed width marker only in a fixed-with element.
22832 ;; Add fixed width maker in paragraphs, in blank lines after
22833 ;; elements or at the beginning of a headline or an inlinetask,
22834 ;; and before any one-line elements (e.g., a clock).
22835 (progn
22836 (beginning-of-line)
22837 (let* ((element (org-element-at-point))
22838 (type (org-element-type element)))
22839 (cond
22840 ((and (eq type 'fixed-width)
22841 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22842 (replace-match
22843 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22844 ((and (memq type '(babel-call clock comment diary-sexp headline
22845 horizontal-rule keyword paragraph
22846 planning))
22847 (or (not (org-element-property :post-affiliated element))
22848 (<= (org-element-property :post-affiliated element)
22849 (point))))
22850 (skip-chars-forward " \t")
22851 (insert ": "))
22852 ((and (org-looking-at-p "[ \t]*$")
22853 (or (eq type 'inlinetask)
22854 (save-excursion
22855 (skip-chars-forward " \r\t\n")
22856 (<= (org-element-property :end element) (point)))))
22857 (delete-region (point) (line-end-position))
22858 (org-indent-line)
22859 (insert ": "))
22860 (t (user-error "Cannot insert a fixed-width line here")))))
22861 ;; Region active.
22862 (let* ((begin (save-excursion
22863 (goto-char (region-beginning))
22864 (line-beginning-position)))
22865 (end (copy-marker
22866 (save-excursion
22867 (goto-char (region-end))
22868 (unless (eolp) (beginning-of-line))
22869 (if (save-excursion (re-search-backward "\\S-" begin t))
22870 (progn (skip-chars-backward " \r\t\n") (point))
22871 (point)))))
22872 (all-fixed-width-p
22873 (catch 'not-all-p
22874 (save-excursion
22875 (goto-char begin)
22876 (skip-chars-forward " \r\t\n")
22877 (when (eobp) (throw 'not-all-p nil))
22878 (while (< (point) end)
22879 (let ((element (org-element-at-point)))
22880 (if (eq (org-element-type element) 'fixed-width)
22881 (goto-char (org-element-property :end element))
22882 (throw 'not-all-p nil))))
22883 t))))
22884 (if all-fixed-width-p
22885 (save-excursion
22886 (goto-char begin)
22887 (while (< (point) end)
22888 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22889 (replace-match
22890 "" nil nil nil
22891 (if (= (line-end-position) (match-end 0)) 0 1)))
22892 (forward-line)))
22893 (let ((min-ind (point-max)))
22894 ;; Find minimum indentation across all lines.
22895 (save-excursion
22896 (goto-char begin)
22897 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22898 (setq min-ind 0)
22899 (catch 'zerop
22900 (while (< (point) end)
22901 (unless (org-looking-at-p "[ \t]*$")
22902 (let ((ind (org-get-indentation)))
22903 (setq min-ind (min min-ind ind))
22904 (when (zerop ind) (throw 'zerop t))))
22905 (forward-line)))))
22906 ;; Loop over all lines and add fixed-width markup everywhere
22907 ;; but in fixed-width lines.
22908 (save-excursion
22909 (goto-char begin)
22910 (while (< (point) end)
22911 (cond
22912 ((org-at-heading-p)
22913 (insert ": ")
22914 (forward-line)
22915 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
22916 (insert ":")
22917 (forward-line)))
22918 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
22919 (let* ((element (org-element-at-point))
22920 (element-end (org-element-property :end element)))
22921 (if (eq (org-element-type element) 'fixed-width)
22922 (progn (goto-char element-end)
22923 (skip-chars-backward " \r\t\n")
22924 (forward-line))
22925 (let ((limit (min end element-end)))
22926 (while (< (point) limit)
22927 (org-move-to-column min-ind t)
22928 (insert ": ")
22929 (forward-line))))))
22931 (org-move-to-column min-ind t)
22932 (insert ": ")
22933 (forward-line)))))))
22934 (set-marker end nil))))
22937 ;;; Comments
22939 ;; Org comments syntax is quite complex. It requires the entire line
22940 ;; to be just a comment. Also, even with the right syntax at the
22941 ;; beginning of line, some some elements (i.e. verse-block or
22942 ;; example-block) don't accept comments. Usual Emacs comment commands
22943 ;; cannot cope with those requirements. Therefore, Org replaces them.
22945 ;; Org still relies on `comment-dwim', but cannot trust
22946 ;; `comment-only-p'. So, `comment-region-function' and
22947 ;; `uncomment-region-function' both point
22948 ;; to`org-comment-or-uncomment-region'. Eventually,
22949 ;; `org-insert-comment' takes care of insertion of comments at the
22950 ;; beginning of line.
22952 ;; `org-setup-comments-handling' install comments related variables
22953 ;; during `org-mode' initialization.
22955 (defun org-setup-comments-handling ()
22956 (interactive)
22957 (org-set-local 'comment-use-syntax nil)
22958 (org-set-local 'comment-start "# ")
22959 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22960 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22961 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22962 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22964 (defun org-insert-comment ()
22965 "Insert an empty comment above current line.
22966 If the line is empty, insert comment at its beginning. When
22967 point is within a source block, comment according to the related
22968 major mode."
22969 (if (let ((element (org-element-at-point)))
22970 (and (eq (org-element-type element) 'src-block)
22971 (< (save-excursion
22972 (goto-char (org-element-property :post-affiliated element))
22973 (line-end-position))
22974 (point))
22975 (> (save-excursion
22976 (goto-char (org-element-property :end element))
22977 (skip-chars-backward " \r\t\n")
22978 (line-beginning-position))
22979 (point))))
22980 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22981 (beginning-of-line)
22982 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22983 (open-line 1))
22984 (org-indent-line)
22985 (insert "# ")))
22987 (defvar comment-empty-lines) ; From newcomment.el.
22988 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22989 "Comment or uncomment each non-blank line in the region.
22990 Uncomment each non-blank line between BEG and END if it only
22991 contains commented lines. Otherwise, comment them. If region is
22992 strictly within a source block, use appropriate comment syntax."
22993 (if (let ((element (org-element-at-point)))
22994 (and (eq (org-element-type element) 'src-block)
22995 (< (save-excursion
22996 (goto-char (org-element-property :post-affiliated element))
22997 (line-end-position))
22998 beg)
22999 (>= (save-excursion
23000 (goto-char (org-element-property :end element))
23001 (skip-chars-backward " \r\t\n")
23002 (line-beginning-position))
23003 end)))
23004 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
23005 (save-restriction
23006 ;; Restrict region
23007 (narrow-to-region (save-excursion (goto-char beg)
23008 (skip-chars-forward " \r\t\n" end)
23009 (line-beginning-position))
23010 (save-excursion (goto-char end)
23011 (skip-chars-backward " \r\t\n" beg)
23012 (line-end-position)))
23013 (let ((uncommentp
23014 ;; UNCOMMENTP is non-nil when every non blank line between
23015 ;; BEG and END is a comment.
23016 (save-excursion
23017 (goto-char (point-min))
23018 (while (and (not (eobp))
23019 (let ((element (org-element-at-point)))
23020 (and (eq (org-element-type element) 'comment)
23021 (goto-char (min (point-max)
23022 (org-element-property
23023 :end element)))))))
23024 (eobp))))
23025 (if uncommentp
23026 ;; Only blank lines and comments in region: uncomment it.
23027 (save-excursion
23028 (goto-char (point-min))
23029 (while (not (eobp))
23030 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23031 (replace-match "" nil nil nil 1))
23032 (forward-line)))
23033 ;; Comment each line in region.
23034 (let ((min-indent (point-max)))
23035 ;; First find the minimum indentation across all lines.
23036 (save-excursion
23037 (goto-char (point-min))
23038 (while (and (not (eobp)) (not (zerop min-indent)))
23039 (unless (looking-at "[ \t]*$")
23040 (setq min-indent (min min-indent (current-indentation))))
23041 (forward-line)))
23042 ;; Then loop over all lines.
23043 (save-excursion
23044 (goto-char (point-min))
23045 (while (not (eobp))
23046 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23047 ;; Don't get fooled by invisible text (e.g. link path)
23048 ;; when moving to column MIN-INDENT.
23049 (let ((buffer-invisibility-spec nil))
23050 (org-move-to-column min-indent t))
23051 (insert comment-start))
23052 (forward-line)))))))))
23054 (defun org-comment-dwim (arg)
23055 (interactive "*P")
23056 "Call `comment-dwim' within a source edit buffer if needed."
23057 (if (org-in-src-block-p)
23058 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
23059 (call-interactively #'comment-dwim)))
23062 ;;; Planning
23064 ;; This section contains tools to operate on timestamp objects, as
23065 ;; returned by, e.g. `org-element-context'.
23067 (defun org-timestamp-has-time-p (timestamp)
23068 "Non-nil when TIMESTAMP has a time specified."
23069 (org-element-property :hour-start timestamp))
23071 (defun org-timestamp-format (timestamp format &optional end utc)
23072 "Format a TIMESTAMP element into a string.
23074 FORMAT is a format specifier to be passed to
23075 `format-time-string'.
23077 When optional argument END is non-nil, use end of date-range or
23078 time-range, if possible.
23080 When optional argument UTC is non-nil, time will be expressed as
23081 Universal Time."
23082 (format-time-string
23083 format
23084 (apply 'encode-time
23085 (cons 0
23086 (mapcar
23087 (lambda (prop) (or (org-element-property prop timestamp) 0))
23088 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23089 '(:minute-start :hour-start :day-start :month-start
23090 :year-start)))))
23091 utc))
23093 (defun org-timestamp-split-range (timestamp &optional end)
23094 "Extract a timestamp object from a date or time range.
23096 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23097 the end of the range. Otherwise, extract its start.
23099 Return a new timestamp object sharing the same parent as
23100 TIMESTAMP."
23101 (let ((type (org-element-property :type timestamp)))
23102 (if (memq type '(active inactive diary)) timestamp
23103 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23104 ;; Set new type.
23105 (org-element-put-property
23106 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23107 ;; Copy start properties over end properties if END is
23108 ;; non-nil. Otherwise, copy end properties over `start' ones.
23109 (let ((p-alist '((:minute-start . :minute-end)
23110 (:hour-start . :hour-end)
23111 (:day-start . :day-end)
23112 (:month-start . :month-end)
23113 (:year-start . :year-end))))
23114 (dolist (p-cell p-alist)
23115 (org-element-put-property
23116 split-ts
23117 (funcall (if end 'car 'cdr) p-cell)
23118 (org-element-property
23119 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23120 ;; Eventually refresh `:raw-value'.
23121 (org-element-put-property split-ts :raw-value nil)
23122 (org-element-put-property
23123 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23125 (defun org-timestamp-translate (timestamp &optional boundary)
23126 "Apply `org-translate-time' on a TIMESTAMP object.
23127 When optional argument BOUNDARY is non-nil, it is either the
23128 symbol `start' or `end'. In this case, only translate the
23129 starting or ending part of TIMESTAMP if it is a date or time
23130 range. Otherwise, translate both parts."
23131 (if (and (not boundary)
23132 (memq (org-element-property :type timestamp)
23133 '(active-range inactive-range)))
23134 (concat
23135 (org-translate-time
23136 (org-element-property :raw-value
23137 (org-timestamp-split-range timestamp)))
23138 "--"
23139 (org-translate-time
23140 (org-element-property :raw-value
23141 (org-timestamp-split-range timestamp t))))
23142 (org-translate-time
23143 (org-element-property
23144 :raw-value
23145 (if (not boundary) timestamp
23146 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23150 ;;; Other stuff.
23152 (defun org-reftex-citation ()
23153 "Use reftex-citation to insert a citation into the buffer.
23154 This looks for a line like
23156 #+BIBLIOGRAPHY: foo plain option:-d
23158 and derives from it that foo.bib is the bibliography file relevant
23159 for this document. It then installs the necessary environment for RefTeX
23160 to work in this buffer and calls `reftex-citation' to insert a citation
23161 into the buffer.
23163 Export of such citations to both LaTeX and HTML is handled by the contributed
23164 package ox-bibtex by Taru Karttunen."
23165 (interactive)
23166 (let ((reftex-docstruct-symbol 'rds)
23167 (reftex-cite-format "\\cite{%l}")
23168 rds bib)
23169 (save-excursion
23170 (save-restriction
23171 (widen)
23172 (let ((case-fold-search t)
23173 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23174 (if (not (save-excursion
23175 (or (re-search-forward re nil t)
23176 (re-search-backward re nil t))))
23177 (user-error "No bibliography defined in file")
23178 (setq bib (concat (match-string 1) ".bib")
23179 rds (list (list 'bib bib)))))))
23180 (call-interactively 'reftex-citation)))
23182 ;;;; Functions extending outline functionality
23184 (defun org-beginning-of-line (&optional arg)
23185 "Go to the beginning of the current line. If that is invisible, continue
23186 to a visible line beginning. This makes the function of C-a more intuitive.
23187 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23188 first attempt, and only move to after the tags when the cursor is already
23189 beyond the end of the headline."
23190 (interactive "P")
23191 (let ((pos (point))
23192 (special (if (consp org-special-ctrl-a/e)
23193 (car org-special-ctrl-a/e)
23194 org-special-ctrl-a/e))
23195 deactivate-mark refpos)
23196 (if (org-bound-and-true-p visual-line-mode)
23197 (beginning-of-visual-line 1)
23198 (beginning-of-line 1))
23199 (if (and arg (fboundp 'move-beginning-of-line))
23200 (call-interactively 'move-beginning-of-line)
23201 (if (bobp)
23203 (backward-char 1)
23204 (if (org-truely-invisible-p)
23205 (while (and (not (bobp)) (org-truely-invisible-p))
23206 (backward-char 1)
23207 (beginning-of-line 1))
23208 (forward-char 1))))
23209 (when special
23210 (cond
23211 ((and (looking-at org-complex-heading-regexp)
23212 (= (char-after (match-end 1)) ?\ ))
23213 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23214 (point-at-eol)))
23215 (goto-char
23216 (if (eq special t)
23217 (cond ((> pos refpos) refpos)
23218 ((= pos (point)) refpos)
23219 (t (point)))
23220 (cond ((> pos (point)) (point))
23221 ((not (eq last-command this-command)) (point))
23222 (t refpos)))))
23223 ((org-at-item-p)
23224 ;; Being at an item and not looking at an the item means point
23225 ;; was previously moved to beginning of a visual line, which
23226 ;; doesn't contain the item. Therefore, do nothing special,
23227 ;; just stay here.
23228 (when (looking-at org-list-full-item-re)
23229 ;; Set special position at first white space character after
23230 ;; bullet, and check-box, if any.
23231 (let ((after-bullet
23232 (let ((box (match-end 3)))
23233 (if (not box) (match-end 1)
23234 (let ((after (char-after box)))
23235 (if (and after (= after ? )) (1+ box) box))))))
23236 ;; Special case: Move point to special position when
23237 ;; currently after it or at beginning of line.
23238 (if (eq special t)
23239 (when (or (> pos after-bullet) (= (point) pos))
23240 (goto-char after-bullet))
23241 ;; Reversed case: Move point to special position when
23242 ;; point was already at beginning of line and command is
23243 ;; repeated.
23244 (when (and (= (point) pos) (eq last-command this-command))
23245 (goto-char after-bullet))))))))
23246 (org-no-warnings
23247 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23248 (setq disable-point-adjustment
23249 (or (not (invisible-p (point)))
23250 (not (invisible-p (max (point-min) (1- (point))))))))
23252 (defun org-end-of-line (&optional arg)
23253 "Go to the end of the line.
23254 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23255 tags on the first attempt, and only move to after the tags when
23256 the cursor is already beyond the end of the headline."
23257 (interactive "P")
23258 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23259 org-special-ctrl-a/e))
23260 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23261 'end-of-visual-line)
23262 ((fboundp 'move-end-of-line) 'move-end-of-line)
23263 (t 'end-of-line)))
23264 deactivate-mark)
23265 (if (or (not special) arg) (call-interactively move-fun)
23266 (let* ((element (save-excursion (beginning-of-line)
23267 (org-element-at-point)))
23268 (type (org-element-type element)))
23269 (cond
23270 ((memq type '(headline inlinetask))
23271 (let ((pos (point)))
23272 (beginning-of-line 1)
23273 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23274 (if (eq special t)
23275 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23276 (goto-char (match-beginning 1))
23277 (goto-char (match-end 0)))
23278 (if (or (< pos (match-end 0))
23279 (not (eq this-command last-command)))
23280 (goto-char (match-end 0))
23281 (goto-char (match-beginning 1))))
23282 (call-interactively move-fun))))
23283 ((outline-invisible-p (line-end-position))
23284 ;; If element is hidden, `move-end-of-line' would put point
23285 ;; after it. Use `end-of-line' to stay on current line.
23286 (call-interactively 'end-of-line))
23287 (t (call-interactively move-fun)))))
23288 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23289 (setq disable-point-adjustment
23290 (or (not (invisible-p (point)))
23291 (not (invisible-p (max (point-min) (1- (point))))))))
23293 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23294 (define-key org-mode-map "\C-e" 'org-end-of-line)
23296 (defun org-backward-sentence (&optional arg)
23297 "Go to beginning of sentence, or beginning of table field.
23298 This will call `backward-sentence' or `org-table-beginning-of-field',
23299 depending on context."
23300 (interactive "P")
23301 (cond
23302 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23303 (t (call-interactively 'backward-sentence))))
23305 (defun org-forward-sentence (&optional arg)
23306 "Go to end of sentence, or end of table field.
23307 This will call `forward-sentence' or `org-table-end-of-field',
23308 depending on context."
23309 (interactive "P")
23310 (cond
23311 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23312 (t (call-interactively 'forward-sentence))))
23314 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23315 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23317 (defun org-kill-line (&optional arg)
23318 "Kill line, to tags or end of line."
23319 (interactive "P")
23320 (cond
23321 ((or (not org-special-ctrl-k)
23322 (bolp)
23323 (not (org-at-heading-p)))
23324 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23325 org-ctrl-k-protect-subtree)
23326 (if (or (eq org-ctrl-k-protect-subtree 'error)
23327 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23328 (user-error "C-k aborted as it would kill a hidden subtree")))
23329 (call-interactively
23330 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23331 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23332 (kill-region (point) (match-beginning 1))
23333 (org-set-tags nil t))
23334 (t (kill-region (point) (point-at-eol)))))
23336 (define-key org-mode-map "\C-k" 'org-kill-line)
23338 (defun org-yank (&optional arg)
23339 "Yank. If the kill is a subtree, treat it specially.
23340 This command will look at the current kill and check if is a single
23341 subtree, or a series of subtrees[1]. If it passes the test, and if the
23342 cursor is at the beginning of a line or after the stars of a currently
23343 empty headline, then the yank is handled specially. How exactly depends
23344 on the value of the following variables, both set by default.
23346 org-yank-folded-subtrees
23347 When set, the subtree(s) will be folded after insertion, but only
23348 if doing so would now swallow text after the yanked text.
23350 org-yank-adjusted-subtrees
23351 When set, the subtree will be promoted or demoted in order to
23352 fit into the local outline tree structure, which means that the level
23353 will be adjusted so that it becomes the smaller one of the two
23354 *visible* surrounding headings.
23356 Any prefix to this command will cause `yank' to be called directly with
23357 no special treatment. In particular, a simple \\[universal-argument] prefix \
23358 will just
23359 plainly yank the text as it is.
23361 \[1] The test checks if the first non-white line is a heading
23362 and if there are no other headings with fewer stars."
23363 (interactive "P")
23364 (org-yank-generic 'yank arg))
23366 (defun org-yank-generic (command arg)
23367 "Perform some yank-like command.
23369 This function implements the behavior described in the `org-yank'
23370 documentation. However, it has been generalized to work for any
23371 interactive command with similar behavior."
23373 ;; pretend to be command COMMAND
23374 (setq this-command command)
23376 (if arg
23377 (call-interactively command)
23379 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23380 (and (org-kill-is-subtree-p)
23381 (or (bolp)
23382 (and (looking-at "[ \t]*$")
23383 (string-match
23384 "\\`\\*+\\'"
23385 (buffer-substring (point-at-bol) (point)))))))
23386 swallowp)
23387 (cond
23388 ((and subtreep org-yank-folded-subtrees)
23389 (let ((beg (point))
23390 end)
23391 (if (and subtreep org-yank-adjusted-subtrees)
23392 (org-paste-subtree nil nil 'for-yank)
23393 (call-interactively command))
23395 (setq end (point))
23396 (goto-char beg)
23397 (when (and (bolp) subtreep
23398 (not (setq swallowp
23399 (org-yank-folding-would-swallow-text beg end))))
23400 (org-with-limited-levels
23401 (or (looking-at org-outline-regexp)
23402 (re-search-forward org-outline-regexp-bol end t))
23403 (while (and (< (point) end) (looking-at org-outline-regexp))
23404 (hide-subtree)
23405 (org-cycle-show-empty-lines 'folded)
23406 (condition-case nil
23407 (outline-forward-same-level 1)
23408 (error (goto-char end))))))
23409 (when swallowp
23410 (message
23411 "Inserted text not folded because that would swallow text"))
23413 (goto-char end)
23414 (skip-chars-forward " \t\n\r")
23415 (beginning-of-line 1)
23416 (push-mark beg 'nomsg)))
23417 ((and subtreep org-yank-adjusted-subtrees)
23418 (let ((beg (point-at-bol)))
23419 (org-paste-subtree nil nil 'for-yank)
23420 (push-mark beg 'nomsg)))
23422 (call-interactively command))))))
23424 (defun org-yank-folding-would-swallow-text (beg end)
23425 "Would hide-subtree at BEG swallow any text after END?"
23426 (let (level)
23427 (org-with-limited-levels
23428 (save-excursion
23429 (goto-char beg)
23430 (when (or (looking-at org-outline-regexp)
23431 (re-search-forward org-outline-regexp-bol end t))
23432 (setq level (org-outline-level)))
23433 (goto-char end)
23434 (skip-chars-forward " \t\r\n\v\f")
23435 (if (or (eobp)
23436 (and (bolp) (looking-at org-outline-regexp)
23437 (<= (org-outline-level) level)))
23438 nil ; Nothing would be swallowed
23439 t))))) ; something would swallow
23441 (define-key org-mode-map "\C-y" 'org-yank)
23443 (defun org-truely-invisible-p ()
23444 "Check if point is at a character currently not visible.
23445 This version does not only check the character property, but also
23446 `visible-mode'."
23447 ;; Early versions of noutline don't have `outline-invisible-p'.
23448 (if (org-bound-and-true-p visible-mode)
23450 (outline-invisible-p)))
23452 (defun org-invisible-p2 ()
23453 "Check if point is at a character currently not visible."
23454 (save-excursion
23455 (if (and (eolp) (not (bobp))) (backward-char 1))
23456 ;; Early versions of noutline don't have `outline-invisible-p'.
23457 (outline-invisible-p)))
23459 (defun org-back-to-heading (&optional invisible-ok)
23460 "Call `outline-back-to-heading', but provide a better error message."
23461 (condition-case nil
23462 (outline-back-to-heading invisible-ok)
23463 (error (error "Before first headline at position %d in buffer %s"
23464 (point) (current-buffer)))))
23466 (defun org-before-first-heading-p ()
23467 "Before first heading?"
23468 (save-excursion
23469 (end-of-line)
23470 (null (re-search-backward org-outline-regexp-bol nil t))))
23472 (defun org-at-heading-p (&optional ignored)
23473 (outline-on-heading-p t))
23474 ;; Compatibility alias with Org versions < 7.8.03
23475 (defalias 'org-on-heading-p 'org-at-heading-p)
23477 (defun org-in-commented-heading-p (&optional no-inheritance)
23478 "Non-nil if point is under a commented heading.
23479 This function also checks ancestors of the current headline,
23480 unless optional argument NO-INHERITANCE is non-nil."
23481 (cond
23482 ((org-before-first-heading-p) nil)
23483 ((let ((headline (nth 4 (org-heading-components))))
23484 (and headline
23485 (let ((case-fold-search nil))
23486 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23487 headline)))))
23488 (no-inheritance nil)
23490 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23492 (defun org-at-comment-p nil
23493 "Is cursor in a line starting with a # character?"
23494 (save-excursion
23495 (beginning-of-line)
23496 (looking-at "^#")))
23498 (defun org-at-drawer-p nil
23499 "Is cursor at a drawer keyword?"
23500 (save-excursion
23501 (move-beginning-of-line 1)
23502 (looking-at org-drawer-regexp)))
23504 (defun org-at-block-p nil
23505 "Is cursor at a block keyword?"
23506 (save-excursion
23507 (move-beginning-of-line 1)
23508 (looking-at org-block-regexp)))
23510 (defun org-point-at-end-of-empty-headline ()
23511 "If point is at the end of an empty headline, return t, else nil.
23512 If the heading only contains a TODO keyword, it is still still considered
23513 empty."
23514 (and (looking-at "[ \t]*$")
23515 (when org-todo-line-regexp
23516 (save-excursion
23517 (beginning-of-line 1)
23518 (let ((case-fold-search nil))
23519 (looking-at org-todo-line-regexp)
23520 (string= (match-string 3) ""))))))
23522 (defun org-at-heading-or-item-p ()
23523 (or (org-at-heading-p) (org-at-item-p)))
23525 (defun org-at-target-p ()
23526 (or (org-in-regexp org-radio-target-regexp)
23527 (org-in-regexp org-target-regexp)))
23528 ;; Compatibility alias with Org versions < 7.8.03
23529 (defalias 'org-on-target-p 'org-at-target-p)
23531 (defun org-up-heading-all (arg)
23532 "Move to the heading line of which the present line is a subheading.
23533 This function considers both visible and invisible heading lines.
23534 With argument, move up ARG levels."
23535 (if (fboundp 'outline-up-heading-all)
23536 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23537 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23539 (defun org-up-heading-safe ()
23540 "Move to the heading line of which the present line is a subheading.
23541 This version will not throw an error. It will return the level of the
23542 headline found, or nil if no higher level is found.
23544 Also, this function will be a lot faster than `outline-up-heading',
23545 because it relies on stars being the outline starters. This can really
23546 make a significant difference in outlines with very many siblings."
23547 (let (start-level re)
23548 (org-back-to-heading t)
23549 (setq start-level (funcall outline-level))
23550 (if (equal start-level 1)
23552 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23553 (if (re-search-backward re nil t)
23554 (funcall outline-level)))))
23556 (defun org-first-sibling-p ()
23557 "Is this heading the first child of its parents?"
23558 (interactive)
23559 (let ((re org-outline-regexp-bol)
23560 level l)
23561 (unless (org-at-heading-p t)
23562 (user-error "Not at a heading"))
23563 (setq level (funcall outline-level))
23564 (save-excursion
23565 (if (not (re-search-backward re nil t))
23567 (setq l (funcall outline-level))
23568 (< l level)))))
23570 (defun org-goto-sibling (&optional previous)
23571 "Goto the next sibling, even if it is invisible.
23572 When PREVIOUS is set, go to the previous sibling instead. Returns t
23573 when a sibling was found. When none is found, return nil and don't
23574 move point."
23575 (let ((fun (if previous 're-search-backward 're-search-forward))
23576 (pos (point))
23577 (re org-outline-regexp-bol)
23578 level l)
23579 (when (condition-case nil (org-back-to-heading t) (error nil))
23580 (setq level (funcall outline-level))
23581 (catch 'exit
23582 (or previous (forward-char 1))
23583 (while (funcall fun re nil t)
23584 (setq l (funcall outline-level))
23585 (when (< l level) (goto-char pos) (throw 'exit nil))
23586 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23587 (goto-char pos)
23588 nil))))
23590 (defun org-show-siblings ()
23591 "Show all siblings of the current headline."
23592 (save-excursion
23593 (while (org-goto-sibling) (org-flag-heading nil)))
23594 (save-excursion
23595 (while (org-goto-sibling 'previous)
23596 (org-flag-heading nil))))
23598 (defun org-goto-first-child ()
23599 "Goto the first child, even if it is invisible.
23600 Return t when a child was found. Otherwise don't move point and
23601 return nil."
23602 (let (level (pos (point)) (re org-outline-regexp-bol))
23603 (when (condition-case nil (org-back-to-heading t) (error nil))
23604 (setq level (outline-level))
23605 (forward-char 1)
23606 (if (and (re-search-forward re nil t) (> (outline-level) level))
23607 (progn (goto-char (match-beginning 0)) t)
23608 (goto-char pos) nil))))
23610 (defun org-show-hidden-entry ()
23611 "Show an entry where even the heading is hidden."
23612 (save-excursion
23613 (org-show-entry)))
23615 (defun org-flag-heading (flag &optional entry)
23616 "Flag the current heading. FLAG non-nil means make invisible.
23617 When ENTRY is non-nil, show the entire entry."
23618 (save-excursion
23619 (org-back-to-heading t)
23620 ;; Check if we should show the entire entry
23621 (if entry
23622 (progn
23623 (org-show-entry)
23624 (save-excursion
23625 (and (outline-next-heading)
23626 (org-flag-heading nil))))
23627 (outline-flag-region (max (point-min) (1- (point)))
23628 (save-excursion (outline-end-of-heading) (point))
23629 flag))))
23631 (defun org-get-next-sibling ()
23632 "Move to next heading of the same level, and return point.
23633 If there is no such heading, return nil.
23634 This is like outline-next-sibling, but invisible headings are ok."
23635 (let ((level (funcall outline-level)))
23636 (outline-next-heading)
23637 (while (and (not (eobp)) (> (funcall outline-level) level))
23638 (outline-next-heading))
23639 (if (or (eobp) (< (funcall outline-level) level))
23641 (point))))
23643 (defun org-get-last-sibling ()
23644 "Move to previous heading of the same level, and return point.
23645 If there is no such heading, return nil."
23646 (let ((opoint (point))
23647 (level (funcall outline-level)))
23648 (outline-previous-heading)
23649 (when (and (/= (point) opoint) (outline-on-heading-p t))
23650 (while (and (> (funcall outline-level) level)
23651 (not (bobp)))
23652 (outline-previous-heading))
23653 (if (< (funcall outline-level) level)
23655 (point)))))
23657 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23658 "Goto to the end of a subtree."
23659 ;; This contains an exact copy of the original function, but it uses
23660 ;; `org-back-to-heading', to make it work also in invisible
23661 ;; trees. And is uses an invisible-ok argument.
23662 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23663 ;; Furthermore, when used inside Org, finding the end of a large subtree
23664 ;; with many children and grandchildren etc, this can be much faster
23665 ;; than the outline version.
23666 (org-back-to-heading invisible-ok)
23667 (let ((first t)
23668 (level (funcall outline-level)))
23669 (if (and (derived-mode-p 'org-mode) (< level 1000))
23670 ;; A true heading (not a plain list item), in Org-mode
23671 ;; This means we can easily find the end by looking
23672 ;; only for the right number of stars. Using a regexp to do
23673 ;; this is so much faster than using a Lisp loop.
23674 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23675 (forward-char 1)
23676 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23677 ;; something else, do it the slow way
23678 (while (and (not (eobp))
23679 (or first (> (funcall outline-level) level)))
23680 (setq first nil)
23681 (outline-next-heading)))
23682 (unless to-heading
23683 (if (memq (preceding-char) '(?\n ?\^M))
23684 (progn
23685 ;; Go to end of line before heading
23686 (forward-char -1)
23687 (if (memq (preceding-char) '(?\n ?\^M))
23688 ;; leave blank line before heading
23689 (forward-char -1))))))
23690 (point))
23692 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23693 "Use Org version in org-mode, for dramatic speed-up."
23694 (if (derived-mode-p 'org-mode)
23695 (progn
23696 (org-end-of-subtree nil t)
23697 (unless (eobp) (backward-char 1)))
23698 ad-do-it))
23700 (defun org-end-of-meta-data-and-drawers ()
23701 "Jump to the first text after meta data and drawers in the current entry.
23702 This will move over empty lines, lines with planning time stamps,
23703 clocking lines, and drawers."
23704 (org-back-to-heading t)
23705 (let ((end (save-excursion (outline-next-heading) (point)))
23706 (re (concat "\\(" org-drawer-regexp "\\)"
23707 "\\|" "[ \t]*" org-keyword-time-regexp)))
23708 (forward-line 1)
23709 (while (re-search-forward re end t)
23710 (if (not (match-end 1))
23711 ;; empty or planning line
23712 (forward-line 1)
23713 ;; a drawer, find the end
23714 (re-search-forward "^[ \t]*:END:" end 'move)
23715 (forward-line 1)))
23716 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23717 (point)))
23719 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23720 "Move forward to the ARG'th subheading at same level as this one.
23721 Stop at the first and last subheadings of a superior heading.
23722 Normally this only looks at visible headings, but when INVISIBLE-OK is
23723 non-nil it will also look at invisible ones."
23724 (interactive "p")
23725 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23726 (if (and arg (< arg 0))
23727 (goto-char (point-min))
23728 (outline-next-heading))
23729 (org-at-heading-p)
23730 (let ((level (- (match-end 0) (match-beginning 0) 1))
23731 (f (if (and arg (< arg 0))
23732 're-search-backward
23733 're-search-forward))
23734 (count (if arg (abs arg) 1))
23735 (result (point)))
23736 (while (and (prog1 (> count 0)
23737 (forward-char (if (and arg (< arg 0)) -1 1)))
23738 (funcall f org-outline-regexp-bol nil 'move))
23739 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23740 (cond ((< l level) (setq count 0))
23741 ((and (= l level)
23742 (or invisible-ok
23743 (progn
23744 (goto-char (line-beginning-position))
23745 (not (outline-invisible-p)))))
23746 (setq count (1- count))
23747 (when (eq l level)
23748 (setq result (point)))))))
23749 (goto-char result))
23750 (beginning-of-line 1)))
23752 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23753 "Move backward to the ARG'th subheading at same level as this one.
23754 Stop at the first and last subheadings of a superior heading."
23755 (interactive "p")
23756 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23758 (defun org-next-block (arg &optional backward block-regexp)
23759 "Jump to the next block.
23760 With a prefix argument ARG, jump forward ARG many source blocks.
23761 When BACKWARD is non-nil, jump to the previous block.
23762 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23763 (interactive "p")
23764 (let ((re (or block-regexp org-block-regexp))
23765 (re-search-fn (or (and backward 're-search-backward)
23766 're-search-forward)))
23767 (if (looking-at re) (forward-char 1))
23768 (condition-case nil
23769 (funcall re-search-fn re nil nil arg)
23770 (error (user-error "No %s code blocks"
23771 (if backward "previous" "further" ))))
23772 (goto-char (match-beginning 0)) (org-show-context)))
23774 (defun org-previous-block (arg &optional block-regexp)
23775 "Jump to the previous block.
23776 With a prefix argument ARG, jump backward ARG many source blocks.
23777 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23778 (interactive "p")
23779 (org-next-block arg t block-regexp))
23781 (defun org-forward-paragraph ()
23782 "Move forward to beginning of next paragraph or equivalent.
23784 The function moves point to the beginning of the next visible
23785 structural element, which can be a paragraph, a table, a list
23786 item, etc. It also provides some special moves for convenience:
23788 - On an affiliated keyword, jump to the beginning of the
23789 relative element.
23790 - On an item or a footnote definition, move to the second
23791 element inside, if any.
23792 - On a table or a property drawer, jump after it.
23793 - On a verse or source block, stop after blank lines."
23794 (interactive)
23795 (when (eobp) (user-error "Cannot move further down"))
23796 (let* ((deactivate-mark nil)
23797 (element (org-element-at-point))
23798 (type (org-element-type element))
23799 (post-affiliated (org-element-property :post-affiliated element))
23800 (contents-begin (org-element-property :contents-begin element))
23801 (contents-end (org-element-property :contents-end element))
23802 (end (let ((end (org-element-property :end element)) (parent element))
23803 (while (and (setq parent (org-element-property :parent parent))
23804 (= (org-element-property :contents-end parent) end))
23805 (setq end (org-element-property :end parent)))
23806 end)))
23807 (cond ((not element)
23808 (skip-chars-forward " \r\t\n")
23809 (or (eobp) (beginning-of-line)))
23810 ;; On affiliated keywords, move to element's beginning.
23811 ((and post-affiliated (< (point) post-affiliated))
23812 (goto-char post-affiliated))
23813 ;; At a table row, move to the end of the table. Similarly,
23814 ;; at a node property, move to the end of the property
23815 ;; drawer.
23816 ((memq type '(node-property table-row))
23817 (goto-char (org-element-property
23818 :end (org-element-property :parent element))))
23819 ((memq type '(property-drawer table)) (goto-char end))
23820 ;; Consider blank lines as separators in verse and source
23821 ;; blocks to ease editing.
23822 ((memq type '(src-block verse-block))
23823 (when (eq type 'src-block)
23824 (setq contents-end
23825 (save-excursion (goto-char end)
23826 (skip-chars-backward " \r\t\n")
23827 (line-beginning-position))))
23828 (beginning-of-line)
23829 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23830 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23831 (goto-char end)
23832 (skip-chars-forward " \r\t\n")
23833 (if (= (point) contents-end) (goto-char end)
23834 (beginning-of-line))))
23835 ;; With no contents, just skip element.
23836 ((not contents-begin) (goto-char end))
23837 ;; If contents are invisible, skip the element altogether.
23838 ((outline-invisible-p (line-end-position))
23839 (case type
23840 (headline
23841 (org-with-limited-levels (outline-next-visible-heading 1)))
23842 ;; At a plain list, make sure we move to the next item
23843 ;; instead of skipping the whole list.
23844 (plain-list (forward-char)
23845 (org-forward-paragraph))
23846 (otherwise (goto-char end))))
23847 ((>= (point) contents-end) (goto-char end))
23848 ((>= (point) contents-begin)
23849 ;; This can only happen on paragraphs and plain lists.
23850 (case type
23851 (paragraph (goto-char end))
23852 ;; At a plain list, try to move to second element in
23853 ;; first item, if possible.
23854 (plain-list (end-of-line)
23855 (org-forward-paragraph))))
23856 ;; When contents start on the middle of a line (e.g. in
23857 ;; items and footnote definitions), try to reach first
23858 ;; element starting after current line.
23859 ((> (line-end-position) contents-begin)
23860 (end-of-line)
23861 (org-forward-paragraph))
23862 (t (goto-char contents-begin)))))
23864 (defun org-backward-paragraph ()
23865 "Move backward to start of previous paragraph or equivalent.
23867 The function moves point to the beginning of the current
23868 structural element, which can be a paragraph, a table, a list
23869 item, etc., or to the beginning of the previous visible one if
23870 point is already there. It also provides some special moves for
23871 convenience:
23873 - On an affiliated keyword, jump to the first one.
23874 - On a table or a property drawer, move to its beginning.
23875 - On a verse or source block, stop before blank lines."
23876 (interactive)
23877 (when (bobp) (user-error "Cannot move further up"))
23878 (let* ((deactivate-mark nil)
23879 (element (org-element-at-point))
23880 (type (org-element-type element))
23881 (contents-begin (org-element-property :contents-begin element))
23882 (contents-end (org-element-property :contents-end element))
23883 (post-affiliated (org-element-property :post-affiliated element))
23884 (begin (org-element-property :begin element)))
23885 (cond
23886 ((not element) (goto-char (point-min)))
23887 ((= (point) begin)
23888 (backward-char)
23889 (org-backward-paragraph))
23890 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23891 ((memq type '(node-property table-row))
23892 (goto-char (org-element-property
23893 :post-affiliated (org-element-property :parent element))))
23894 ((memq type '(property-drawer table)) (goto-char begin))
23895 ((memq type '(src-block verse-block))
23896 (when (eq type 'src-block)
23897 (setq contents-begin
23898 (save-excursion (goto-char begin) (forward-line) (point))))
23899 (if (= (point) contents-begin) (goto-char post-affiliated)
23900 ;; Inside a verse block, see blank lines as paragraph
23901 ;; separators.
23902 (let ((origin (point)))
23903 (skip-chars-backward " \r\t\n" contents-begin)
23904 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23905 (skip-chars-forward " \r\t\n" origin)
23906 (if (= (point) origin) (goto-char contents-begin)
23907 (beginning-of-line))))))
23908 ((not contents-begin) (goto-char (or post-affiliated begin)))
23909 ((eq type 'paragraph)
23910 (goto-char contents-begin)
23911 ;; When at first paragraph in an item or a footnote definition,
23912 ;; move directly to beginning of line.
23913 (let ((parent-contents
23914 (org-element-property
23915 :contents-begin (org-element-property :parent element))))
23916 (when (and parent-contents (= parent-contents contents-begin))
23917 (beginning-of-line))))
23918 ;; At the end of a greater element, move to the beginning of the
23919 ;; last element within.
23920 ((>= (point) contents-end)
23921 (goto-char (1- contents-end))
23922 (org-backward-paragraph))
23923 (t (goto-char (or post-affiliated begin))))
23924 ;; Ensure we never leave point invisible.
23925 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23927 (defun org-forward-element ()
23928 "Move forward by one element.
23929 Move to the next element at the same level, when possible."
23930 (interactive)
23931 (cond ((eobp) (user-error "Cannot move further down"))
23932 ((org-with-limited-levels (org-at-heading-p))
23933 (let ((origin (point)))
23934 (goto-char (org-end-of-subtree nil t))
23935 (unless (org-with-limited-levels (org-at-heading-p))
23936 (goto-char origin)
23937 (user-error "Cannot move further down"))))
23939 (let* ((elem (org-element-at-point))
23940 (end (org-element-property :end elem))
23941 (parent (org-element-property :parent elem)))
23942 (cond ((and parent (= (org-element-property :contents-end parent) end))
23943 (goto-char (org-element-property :end parent)))
23944 ((integer-or-marker-p end) (goto-char end))
23945 (t (message "No element at point")))))))
23947 (defun org-backward-element ()
23948 "Move backward by one element.
23949 Move to the previous element at the same level, when possible."
23950 (interactive)
23951 (cond ((bobp) (user-error "Cannot move further up"))
23952 ((org-with-limited-levels (org-at-heading-p))
23953 ;; At a headline, move to the previous one, if any, or stay
23954 ;; here.
23955 (let ((origin (point)))
23956 (org-with-limited-levels (org-backward-heading-same-level 1))
23957 ;; When current headline has no sibling above, move to its
23958 ;; parent.
23959 (when (= (point) origin)
23960 (or (org-with-limited-levels (org-up-heading-safe))
23961 (progn (goto-char origin)
23962 (user-error "Cannot move further up"))))))
23964 (let* ((elem (org-element-at-point))
23965 (beg (org-element-property :begin elem)))
23966 (cond
23967 ;; Move to beginning of current element if point isn't
23968 ;; there already.
23969 ((null beg) (message "No element at point"))
23970 ((/= (point) beg) (goto-char beg))
23971 (t (goto-char beg)
23972 (skip-chars-backward " \r\t\n")
23973 (unless (bobp)
23974 (let ((prev (org-element-at-point)))
23975 (goto-char (org-element-property :begin prev))
23976 (while (and (setq prev (org-element-property :parent prev))
23977 (<= (org-element-property :end prev) beg))
23978 (goto-char (org-element-property :begin prev)))))))))))
23980 (defun org-up-element ()
23981 "Move to upper element."
23982 (interactive)
23983 (if (org-with-limited-levels (org-at-heading-p))
23984 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23985 (let* ((elem (org-element-at-point))
23986 (parent (org-element-property :parent elem)))
23987 (if parent (goto-char (org-element-property :begin parent))
23988 (if (org-with-limited-levels (org-before-first-heading-p))
23989 (user-error "No surrounding element")
23990 (org-with-limited-levels (org-back-to-heading)))))))
23992 (defvar org-element-greater-elements)
23993 (defun org-down-element ()
23994 "Move to inner element."
23995 (interactive)
23996 (let ((element (org-element-at-point)))
23997 (cond
23998 ((memq (org-element-type element) '(plain-list table))
23999 (goto-char (org-element-property :contents-begin element))
24000 (forward-char))
24001 ((memq (org-element-type element) org-element-greater-elements)
24002 ;; If contents are hidden, first disclose them.
24003 (when (outline-invisible-p (line-end-position)) (org-cycle))
24004 (goto-char (or (org-element-property :contents-begin element)
24005 (user-error "No content for this element"))))
24006 (t (user-error "No inner element")))))
24008 (defun org-drag-element-backward ()
24009 "Move backward element at point."
24010 (interactive)
24011 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24012 (let* ((elem (org-element-at-point))
24013 (prev-elem
24014 (save-excursion
24015 (goto-char (org-element-property :begin elem))
24016 (skip-chars-backward " \r\t\n")
24017 (unless (bobp)
24018 (let* ((beg (org-element-property :begin elem))
24019 (prev (org-element-at-point))
24020 (up prev))
24021 (while (and (setq up (org-element-property :parent up))
24022 (<= (org-element-property :end prev) beg))
24023 (setq prev up))
24024 prev)))))
24025 ;; Error out if no previous element or previous element is
24026 ;; a parent of the current one.
24027 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24028 (user-error "Cannot drag element backward")
24029 (let ((pos (point)))
24030 (org-element-swap-A-B prev-elem elem)
24031 (goto-char (+ (org-element-property :begin prev-elem)
24032 (- pos (org-element-property :begin elem)))))))))
24034 (defun org-drag-element-forward ()
24035 "Move forward element at point."
24036 (interactive)
24037 (let* ((pos (point))
24038 (elem (org-element-at-point)))
24039 (when (= (point-max) (org-element-property :end elem))
24040 (user-error "Cannot drag element forward"))
24041 (goto-char (org-element-property :end elem))
24042 (let ((next-elem (org-element-at-point)))
24043 (when (or (org-element-nested-p elem next-elem)
24044 (and (eq (org-element-type next-elem) 'headline)
24045 (not (eq (org-element-type elem) 'headline))))
24046 (goto-char pos)
24047 (user-error "Cannot drag element forward"))
24048 ;; Compute new position of point: it's shifted by NEXT-ELEM
24049 ;; body's length (without final blanks) and by the length of
24050 ;; blanks between ELEM and NEXT-ELEM.
24051 (let ((size-next (- (save-excursion
24052 (goto-char (org-element-property :end next-elem))
24053 (skip-chars-backward " \r\t\n")
24054 (forward-line)
24055 ;; Small correction if buffer doesn't end
24056 ;; with a newline character.
24057 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24058 (org-element-property :begin next-elem)))
24059 (size-blank (- (org-element-property :end elem)
24060 (save-excursion
24061 (goto-char (org-element-property :end elem))
24062 (skip-chars-backward " \r\t\n")
24063 (forward-line)
24064 (point)))))
24065 (org-element-swap-A-B elem next-elem)
24066 (goto-char (+ pos size-next size-blank))))))
24068 (defun org-drag-line-forward (arg)
24069 "Drag the line at point ARG lines forward."
24070 (interactive "p")
24071 (dotimes (n (abs arg))
24072 (let ((c (current-column)))
24073 (if (< 0 arg)
24074 (progn
24075 (beginning-of-line 2)
24076 (transpose-lines 1)
24077 (beginning-of-line 0))
24078 (transpose-lines 1)
24079 (beginning-of-line -1))
24080 (org-move-to-column c))))
24082 (defun org-drag-line-backward (arg)
24083 "Drag the line at point ARG lines backward."
24084 (interactive "p")
24085 (org-drag-line-forward (- arg)))
24087 (defun org-mark-element ()
24088 "Put point at beginning of this element, mark at end.
24090 Interactively, if this command is repeated or (in Transient Mark
24091 mode) if the mark is active, it marks the next element after the
24092 ones already marked."
24093 (interactive)
24094 (let (deactivate-mark)
24095 (if (and (org-called-interactively-p 'any)
24096 (or (and (eq last-command this-command) (mark t))
24097 (and transient-mark-mode mark-active)))
24098 (set-mark
24099 (save-excursion
24100 (goto-char (mark))
24101 (goto-char (org-element-property :end (org-element-at-point)))))
24102 (let ((element (org-element-at-point)))
24103 (end-of-line)
24104 (push-mark (org-element-property :end element) t t)
24105 (goto-char (org-element-property :begin element))))))
24107 (defun org-narrow-to-element ()
24108 "Narrow buffer to current element."
24109 (interactive)
24110 (let ((elem (org-element-at-point)))
24111 (cond
24112 ((eq (car elem) 'headline)
24113 (narrow-to-region
24114 (org-element-property :begin elem)
24115 (org-element-property :end elem)))
24116 ((memq (car elem) org-element-greater-elements)
24117 (narrow-to-region
24118 (org-element-property :contents-begin elem)
24119 (org-element-property :contents-end elem)))
24121 (narrow-to-region
24122 (org-element-property :begin elem)
24123 (org-element-property :end elem))))))
24125 (defun org-transpose-element ()
24126 "Transpose current and previous elements, keeping blank lines between.
24127 Point is moved after both elements."
24128 (interactive)
24129 (org-skip-whitespace)
24130 (let ((end (org-element-property :end (org-element-at-point))))
24131 (org-drag-element-backward)
24132 (goto-char end)))
24134 (defun org-unindent-buffer ()
24135 "Un-indent the visible part of the buffer.
24136 Relative indentation (between items, inside blocks, etc.) isn't
24137 modified."
24138 (interactive)
24139 (unless (eq major-mode 'org-mode)
24140 (user-error "Cannot un-indent a buffer not in Org mode"))
24141 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24142 unindent-tree ; For byte-compiler.
24143 (unindent-tree
24144 (function
24145 (lambda (contents)
24146 (mapc
24147 (lambda (element)
24148 (if (memq (org-element-type element) '(headline section))
24149 (funcall unindent-tree (org-element-contents element))
24150 (save-excursion
24151 (save-restriction
24152 (narrow-to-region
24153 (org-element-property :begin element)
24154 (org-element-property :end element))
24155 (org-do-remove-indentation)))))
24156 (reverse contents))))))
24157 (funcall unindent-tree (org-element-contents parse-tree))))
24159 (defun org-show-subtree ()
24160 "Show everything after this heading at deeper levels."
24161 (interactive)
24162 (outline-flag-region
24163 (point)
24164 (save-excursion
24165 (org-end-of-subtree t t))
24166 nil))
24168 (defun org-show-entry ()
24169 "Show the body directly following this heading.
24170 Show the heading too, if it is currently invisible."
24171 (interactive)
24172 (save-excursion
24173 (condition-case nil
24174 (progn
24175 (org-back-to-heading t)
24176 (outline-flag-region
24177 (max (point-min) (1- (point)))
24178 (save-excursion
24179 (if (re-search-forward
24180 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24181 (match-beginning 1)
24182 (point-max)))
24183 nil)
24184 (org-cycle-hide-drawers 'children))
24185 (error nil))))
24187 (defun org-make-options-regexp (kwds &optional extra)
24188 "Make a regular expression for keyword lines."
24189 (concat
24190 "^[ \t]*#\\+\\("
24191 (mapconcat 'regexp-quote kwds "\\|")
24192 (if extra (concat "\\|" extra))
24193 "\\):[ \t]*\\(.*\\)"))
24195 ;; Make isearch reveal the necessary context
24196 (defun org-isearch-end ()
24197 "Reveal context after isearch exits."
24198 (when isearch-success ; only if search was successful
24199 (if (featurep 'xemacs)
24200 ;; Under XEmacs, the hook is run in the correct place,
24201 ;; we directly show the context.
24202 (org-show-context 'isearch)
24203 ;; In Emacs the hook runs *before* restoring the overlays.
24204 ;; So we have to use a one-time post-command-hook to do this.
24205 ;; (Emacs 22 has a special variable, see function `org-mode')
24206 (unless (and (boundp 'isearch-mode-end-hook-quit)
24207 isearch-mode-end-hook-quit)
24208 ;; Only when the isearch was not quitted.
24209 (org-add-hook 'post-command-hook 'org-isearch-post-command
24210 'append 'local)))
24211 (org-fix-ellipsis-at-bol)))
24213 (defun org-isearch-post-command ()
24214 "Remove self from hook, and show context."
24215 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24216 (org-show-context 'isearch))
24219 ;;;; Integration with and fixes for other packages
24221 ;;; Imenu support
24223 (defvar org-imenu-markers nil
24224 "All markers currently used by Imenu.")
24225 (make-variable-buffer-local 'org-imenu-markers)
24227 (defun org-imenu-new-marker (&optional pos)
24228 "Return a new marker for use by Imenu, and remember the marker."
24229 (let ((m (make-marker)))
24230 (move-marker m (or pos (point)))
24231 (push m org-imenu-markers)
24234 (defun org-imenu-get-tree ()
24235 "Produce the index for Imenu."
24236 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24237 (setq org-imenu-markers nil)
24238 (let* ((n org-imenu-depth)
24239 (re (concat "^" (org-get-limited-outline-regexp)))
24240 (subs (make-vector (1+ n) nil))
24241 (last-level 0)
24242 m level head0 head)
24243 (save-excursion
24244 (save-restriction
24245 (widen)
24246 (goto-char (point-max))
24247 (while (re-search-backward re nil t)
24248 (setq level (org-reduced-level (funcall outline-level)))
24249 (when (and (<= level n)
24250 (looking-at org-complex-heading-regexp)
24251 (setq head0 (org-match-string-no-properties 4)))
24252 (setq head (org-link-display-format head0)
24253 m (org-imenu-new-marker))
24254 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24255 (if (>= level last-level)
24256 (push (cons head m) (aref subs level))
24257 (push (cons head (aref subs (1+ level))) (aref subs level))
24258 (loop for i from (1+ level) to n do (aset subs i nil)))
24259 (setq last-level level)))))
24260 (aref subs 1)))
24262 (eval-after-load "imenu"
24263 '(progn
24264 (add-hook 'imenu-after-jump-hook
24265 (lambda ()
24266 (if (derived-mode-p 'org-mode)
24267 (org-show-context 'org-goto))))))
24269 (defun org-link-display-format (link)
24270 "Replace a link with its the description.
24271 If there is no description, use the link target."
24272 (save-match-data
24273 (if (string-match org-bracket-link-analytic-regexp link)
24274 (replace-match (if (match-end 5)
24275 (match-string 5 link)
24276 (concat (match-string 1 link)
24277 (match-string 3 link)))
24278 nil t link)
24279 link)))
24281 (defun org-toggle-link-display ()
24282 "Toggle the literal or descriptive display of links."
24283 (interactive)
24284 (if org-descriptive-links
24285 (progn (org-remove-from-invisibility-spec '(org-link))
24286 (org-restart-font-lock)
24287 (setq org-descriptive-links nil))
24288 (progn (add-to-invisibility-spec '(org-link))
24289 (org-restart-font-lock)
24290 (setq org-descriptive-links t))))
24292 ;; Speedbar support
24294 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24295 "Overlay marking the agenda restriction line in speedbar.")
24296 (overlay-put org-speedbar-restriction-lock-overlay
24297 'face 'org-agenda-restriction-lock)
24298 (overlay-put org-speedbar-restriction-lock-overlay
24299 'help-echo "Agendas are currently limited to this item.")
24300 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24302 (defun org-speedbar-set-agenda-restriction ()
24303 "Restrict future agenda commands to the location at point in speedbar.
24304 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24305 (interactive)
24306 (require 'org-agenda)
24307 (let (p m tp np dir txt)
24308 (cond
24309 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24310 'org-imenu t))
24311 (setq m (get-text-property p 'org-imenu-marker))
24312 (with-current-buffer (marker-buffer m)
24313 (goto-char m)
24314 (org-agenda-set-restriction-lock 'subtree)))
24315 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24316 'speedbar-function 'speedbar-find-file))
24317 (setq tp (previous-single-property-change
24318 (1+ p) 'speedbar-function)
24319 np (next-single-property-change
24320 tp 'speedbar-function)
24321 dir (speedbar-line-directory)
24322 txt (buffer-substring-no-properties (or tp (point-min))
24323 (or np (point-max))))
24324 (with-current-buffer (find-file-noselect
24325 (let ((default-directory dir))
24326 (expand-file-name txt)))
24327 (unless (derived-mode-p 'org-mode)
24328 (user-error "Cannot restrict to non-Org-mode file"))
24329 (org-agenda-set-restriction-lock 'file)))
24330 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24331 (move-overlay org-speedbar-restriction-lock-overlay
24332 (point-at-bol) (point-at-eol))
24333 (setq current-prefix-arg nil)
24334 (org-agenda-maybe-redo)))
24336 (defvar speedbar-file-key-map)
24337 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24338 (eval-after-load "speedbar"
24339 '(progn
24340 (speedbar-add-supported-extension ".org")
24341 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24342 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24343 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24344 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24345 (add-hook 'speedbar-visiting-tag-hook
24346 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24348 ;;; Fixes and Hacks for problems with other packages
24350 (defun org-mode-flyspell-verify ()
24351 "Function used for `flyspell-generic-check-word-predicate'."
24352 (if (org-at-heading-p)
24353 ;; At a headline or an inlinetask, check title only. This is
24354 ;; faster than relying on `org-element-at-point'.
24355 (and (save-excursion (beginning-of-line)
24356 (and (let ((case-fold-search t))
24357 (not (looking-at "\\*+ END[ \t]*$")))
24358 (looking-at org-complex-heading-regexp)))
24359 (match-beginning 4)
24360 (>= (point) (match-beginning 4))
24361 (or (not (match-beginning 5))
24362 (< (point) (match-beginning 5))))
24363 (let* ((element (org-element-at-point))
24364 (post-affiliated (org-element-property :post-affiliated element))
24365 (object-check
24366 (function
24367 ;; Non-nil if checks can be done for object at point.
24368 (lambda ()
24369 (let ((object (save-excursion
24370 (when (org-looking-at-p "\\>") (backward-char))
24371 (org-element-context element))))
24372 (case (org-element-type object)
24373 ;; Prevent checks in links due to keybinding conflict
24374 ;; with Flyspell.
24375 ((code entity export-snippet inline-babel-call
24376 inline-src-block line-break latex-fragment link macro
24377 statistics-cookie target timestamp verbatim)
24378 nil)
24379 (footnote-reference
24380 ;; Only in inline footnotes, within the definition.
24381 (and (eq (org-element-property :type object) 'inline)
24382 (< (save-excursion
24383 (goto-char (org-element-property :begin object))
24384 (search-forward ":" nil t 2))
24385 (point))))
24386 (otherwise t)))))))
24387 (cond
24388 ;; Ignore checks in all affiliated keywords but captions.
24389 ((and post-affiliated (< (point) post-affiliated))
24390 (and (save-excursion
24391 (beginning-of-line)
24392 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24393 (> (point) (match-end 0))
24394 (funcall object-check)))
24395 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24396 ((and org-log-into-drawer
24397 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24398 (parent element))
24399 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24400 (setq parent (org-element-property :parent parent)))
24401 (and parent
24402 (eq (compare-strings
24403 log nil nil
24404 (org-element-property :drawer-name parent) nil nil t)
24405 t))))
24406 nil)
24408 (case (org-element-type element)
24409 ((comment quote-section) t)
24410 (comment-block
24411 ;; Allow checks between block markers, not on them.
24412 (and (> (line-beginning-position)
24413 (org-element-property :post-affiliated element))
24414 (save-excursion
24415 (end-of-line)
24416 (skip-chars-forward " \r\t\n")
24417 (< (point) (org-element-property :end element)))))
24418 ;; Arbitrary list of keywords where checks are meaningful.
24419 ;; Make sure point is on the value part of the element.
24420 (keyword
24421 (and (member (org-element-property :key element)
24422 '("DESCRIPTION" "TITLE"))
24423 (< (save-excursion
24424 (beginning-of-line) (search-forward ":") (point))
24425 (point))))
24426 ;; Check is globally allowed in paragraphs verse blocks and
24427 ;; table rows (after affiliated keywords) but some objects
24428 ;; must not be affected.
24429 ((paragraph table-row verse-block)
24430 (and (>= (point) (org-element-property :contents-begin element))
24431 (< (point) (org-element-property :contents-end element))
24432 (funcall object-check)))))))))
24433 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24435 (defun org-remove-flyspell-overlays-in (beg end)
24436 "Remove flyspell overlays in region."
24437 (and (org-bound-and-true-p flyspell-mode)
24438 (fboundp 'flyspell-delete-region-overlays)
24439 (flyspell-delete-region-overlays beg end)))
24441 (defvar flyspell-delayed-commands)
24442 (eval-after-load "flyspell"
24443 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24445 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24446 (eval-after-load "bookmark"
24447 '(if (boundp 'bookmark-after-jump-hook)
24448 ;; We can use the hook
24449 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24450 ;; Hook not available, use advice
24451 (defadvice bookmark-jump (after org-make-visible activate)
24452 "Make the position visible."
24453 (org-bookmark-jump-unhide))))
24455 ;; Make sure saveplace shows the location if it was hidden
24456 (eval-after-load "saveplace"
24457 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24458 "Make the position visible."
24459 (org-bookmark-jump-unhide)))
24461 ;; Make sure ecb shows the location if it was hidden
24462 (eval-after-load "ecb"
24463 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24464 "Make hierarchy visible when jumping into location from ECB tree buffer."
24465 (if (derived-mode-p 'org-mode)
24466 (org-show-context))))
24468 (defun org-bookmark-jump-unhide ()
24469 "Unhide the current position, to show the bookmark location."
24470 (and (derived-mode-p 'org-mode)
24471 (or (outline-invisible-p)
24472 (save-excursion (goto-char (max (point-min) (1- (point))))
24473 (outline-invisible-p)))
24474 (org-show-context 'bookmark-jump)))
24476 ;; Make session.el ignore our circular variable
24477 (defvar session-globals-exclude)
24478 (eval-after-load "session"
24479 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24481 ;;;; Finish up
24483 (provide 'org)
24485 (run-hooks 'org-load-hook)
24487 ;;; org.el ends here