Replace org-babel-*-graphical-output-file with generic version
[org-mode.git] / lisp / org.el
blob36c3dbbc6d261cbb07e2fbd8d0719ed015755d48
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 (when old-regexp
6134 (org-with-wide-buffer
6135 (goto-char (point-min))
6136 (while (re-search-forward old-regexp nil t)
6137 (org-element-cache-refresh (match-beginning 1)))))
6138 ;; Re fontify buffer.
6139 (when (memq 'radio org-highlight-links)
6140 (org-restart-font-lock)))))
6142 (defun org-hide-wide-columns (limit)
6143 (let (s e)
6144 (setq s (text-property-any (point) (or limit (point-max))
6145 'org-cwidth t))
6146 (when s
6147 (setq e (next-single-property-change s 'org-cwidth))
6148 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6149 (goto-char e)
6150 t)))
6152 (defvar org-latex-and-related-regexp nil
6153 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6155 (defun org-compute-latex-and-related-regexp ()
6156 "Compute regular expression for LaTeX, entities and sub/superscript.
6157 Result depends on variable `org-highlight-latex-and-related'."
6158 (org-set-local
6159 'org-latex-and-related-regexp
6160 (let* ((re-sub
6161 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6162 ((eq org-use-sub-superscripts '{})
6163 (list org-match-substring-with-braces-regexp))
6164 (org-use-sub-superscripts (list org-match-substring-regexp))))
6165 (re-latex
6166 (when (memq 'latex org-highlight-latex-and-related)
6167 (let ((matchers (plist-get org-format-latex-options :matchers)))
6168 (delq nil
6169 (mapcar (lambda (x)
6170 (and (member (car x) matchers) (nth 1 x)))
6171 org-latex-regexps)))))
6172 (re-entities
6173 (when (memq 'entities org-highlight-latex-and-related)
6174 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6175 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6177 (defun org-do-latex-and-related (limit)
6178 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6179 LIMIT bounds the search for syntax to highlight. Stop at first
6180 highlighted object, if any. Return t if some highlighting was
6181 done, nil otherwise."
6182 (when (org-string-nw-p org-latex-and-related-regexp)
6183 (catch 'found
6184 (while (re-search-forward org-latex-and-related-regexp limit t)
6185 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6186 'face))
6187 '(org-code org-verbatim underline))
6188 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6189 '(?_ ?^))
6191 0)))
6192 (font-lock-prepend-text-property
6193 (+ offset (match-beginning 0)) (match-end 0)
6194 'face 'org-latex-and-related)
6195 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6196 '(font-lock-multiline t)))
6197 (throw 'found t)))
6198 nil)))
6200 (defun org-restart-font-lock ()
6201 "Restart `font-lock-mode', to force refontification."
6202 (when (and (boundp 'font-lock-mode) font-lock-mode)
6203 (font-lock-mode -1)
6204 (font-lock-mode 1)))
6206 (defun org-activate-tags (limit)
6207 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6208 (progn
6209 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6210 (add-text-properties (match-beginning 1) (match-end 1)
6211 (list 'mouse-face 'highlight
6212 'keymap org-mouse-map))
6213 (org-rear-nonsticky-at (match-end 1))
6214 t)))
6216 (defun org-outline-level ()
6217 "Compute the outline level of the heading at point.
6218 If this is called at a normal headline, the level is the number of stars.
6219 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6220 (save-excursion
6221 (if (not (condition-case nil
6222 (org-back-to-heading t)
6223 (error nil)))
6225 (looking-at org-outline-regexp)
6226 (1- (- (match-end 0) (match-beginning 0))))))
6228 (defvar org-font-lock-keywords nil)
6230 (defsubst org-re-property (property &optional literal)
6231 "Return a regexp matching a PROPERTY line.
6232 Match group 3 will be set to the value if it exists."
6233 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6234 (if literal property (regexp-quote property))
6235 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6237 (defconst org-property-re
6238 (org-re-property ".*?" 'literal)
6239 "Regular expression matching a property line.
6240 There are four matching groups:
6241 1: :PROPKEY: including the leading and trailing colon,
6242 2: PROPKEY without the leading and trailing colon,
6243 3: PROPVAL without leading or trailing spaces,
6244 4: the indentation of the current line,
6245 5: trailing whitespace.")
6247 (defvar org-font-lock-hook nil
6248 "Functions to be called for special font lock stuff.")
6250 (defvar org-font-lock-set-keywords-hook nil
6251 "Functions that can manipulate `org-font-lock-extra-keywords'.
6252 This is called after `org-font-lock-extra-keywords' is defined, but before
6253 it is installed to be used by font lock. This can be useful if something
6254 needs to be inserted at a specific position in the font-lock sequence.")
6256 (defun org-font-lock-hook (limit)
6257 "Run `org-font-lock-hook' within LIMIT."
6258 (run-hook-with-args 'org-font-lock-hook limit))
6260 (defun org-set-font-lock-defaults ()
6261 "Set font lock defaults for the current buffer."
6262 (let* ((em org-fontify-emphasized-text)
6263 (lk org-highlight-links)
6264 (org-font-lock-extra-keywords
6265 (list
6266 ;; Call the hook
6267 '(org-font-lock-hook)
6268 ;; Headlines
6269 `(,(if org-fontify-whole-heading-line
6270 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6271 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6272 (1 (org-get-level-face 1))
6273 (2 (org-get-level-face 2))
6274 (3 (org-get-level-face 3)))
6275 ;; Table lines
6276 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6277 (1 'org-table t))
6278 ;; Table internals
6279 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6280 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6281 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6282 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6283 ;; Drawers
6284 '(org-fontify-drawers)
6285 ;; Properties
6286 (list org-property-re
6287 '(1 'org-special-keyword t)
6288 '(3 'org-property-value t))
6289 ;; Links
6290 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6291 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6292 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6293 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6294 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6295 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6296 (if (memq 'footnote lk) '(org-activate-footnote-links))
6297 ;; Targets.
6298 (list org-any-target-regexp '(0 'org-target t))
6299 ;; Diary sexps.
6300 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6301 ;; Macro
6302 '(org-fontify-macros)
6303 '(org-hide-wide-columns (0 nil append))
6304 ;; TODO keyword
6305 (list (format org-heading-keyword-regexp-format
6306 org-todo-regexp)
6307 '(2 (org-get-todo-face 2) t))
6308 ;; DONE
6309 (if org-fontify-done-headline
6310 (list (format org-heading-keyword-regexp-format
6311 (concat
6312 "\\(?:"
6313 (mapconcat 'regexp-quote org-done-keywords "\\|")
6314 "\\)"))
6315 '(2 'org-headline-done t))
6316 nil)
6317 ;; Priorities
6318 '(org-font-lock-add-priority-faces)
6319 ;; Tags
6320 '(org-font-lock-add-tag-faces)
6321 ;; Tags groups
6322 (if (and org-group-tags org-tag-groups-alist)
6323 (list (concat org-outline-regexp-bol ".+\\(:"
6324 (regexp-opt (mapcar 'car org-tag-groups-alist))
6325 ":\\).*$")
6326 '(1 'org-tag-group prepend)))
6327 ;; Special keywords
6328 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6329 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6330 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6331 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6332 ;; Emphasis
6333 (if em
6334 (if (featurep 'xemacs)
6335 '(org-do-emphasis-faces (0 nil append))
6336 '(org-do-emphasis-faces)))
6337 ;; Checkboxes
6338 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6339 1 'org-checkbox prepend)
6340 (if (cdr (assq 'checkbox org-list-automatic-rules))
6341 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6342 (0 (org-get-checkbox-statistics-face) t)))
6343 ;; Description list items
6344 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6345 1 'org-list-dt prepend)
6346 ;; ARCHIVEd headings
6347 (list (concat
6348 org-outline-regexp-bol
6349 "\\(.*:" org-archive-tag ":.*\\)")
6350 '(1 'org-archived prepend))
6351 ;; Specials
6352 '(org-do-latex-and-related)
6353 '(org-fontify-entities)
6354 '(org-raise-scripts)
6355 ;; Code
6356 '(org-activate-code (1 'org-code t))
6357 ;; COMMENT
6358 (list (format
6359 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6360 org-todo-regexp
6361 org-comment-string)
6362 '(9 'org-special-keyword t))
6363 ;; Blocks and meta lines
6364 '(org-fontify-meta-lines-and-blocks))))
6365 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6366 (run-hooks 'org-font-lock-set-keywords-hook)
6367 ;; Now set the full font-lock-keywords
6368 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6369 (org-set-local 'font-lock-defaults
6370 '(org-font-lock-keywords t nil nil backward-paragraph))
6371 (kill-local-variable 'font-lock-keywords) nil))
6373 (defun org-toggle-pretty-entities ()
6374 "Toggle the composition display of entities as UTF8 characters."
6375 (interactive)
6376 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6377 (org-restart-font-lock)
6378 (if org-pretty-entities
6379 (message "Entities are now displayed as UTF8 characters")
6380 (save-restriction
6381 (widen)
6382 (org-decompose-region (point-min) (point-max))
6383 (message "Entities are now displayed as plain text"))))
6385 (defvar org-custom-properties-overlays nil
6386 "List of overlays used for custom properties.")
6387 (make-variable-buffer-local 'org-custom-properties-overlays)
6389 (defun org-toggle-custom-properties-visibility ()
6390 "Display or hide properties in `org-custom-properties'."
6391 (interactive)
6392 (if org-custom-properties-overlays
6393 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6394 (setq org-custom-properties-overlays nil))
6395 (unless (not org-custom-properties)
6396 (save-excursion
6397 (save-restriction
6398 (widen)
6399 (goto-char (point-min))
6400 (while (re-search-forward org-property-re nil t)
6401 (mapc (lambda(p)
6402 (when (equal p (substring (match-string 1) 1 -1))
6403 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6404 (overlay-put o 'invisible t)
6405 (overlay-put o 'org-custom-property t)
6406 (push o org-custom-properties-overlays))))
6407 org-custom-properties)))))))
6409 (defun org-fontify-entities (limit)
6410 "Find an entity to fontify."
6411 (let (ee)
6412 (when org-pretty-entities
6413 (catch 'match
6414 (while (re-search-forward
6415 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6416 limit t)
6417 (if (and (not (org-in-indented-comment-line))
6418 (setq ee (org-entity-get (match-string 1)))
6419 (= (length (nth 6 ee)) 1))
6420 (let*
6421 ((end (if (equal (match-string 2) "{}")
6422 (match-end 2)
6423 (match-end 1))))
6424 (add-text-properties
6425 (match-beginning 0) end
6426 (list 'font-lock-fontified t))
6427 (compose-region (match-beginning 0) end
6428 (nth 6 ee) nil)
6429 (backward-char 1)
6430 (throw 'match t))))
6431 nil))))
6433 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6434 "Fontify string S like in Org-mode."
6435 (with-temp-buffer
6436 (insert s)
6437 (let ((org-odd-levels-only odd-levels))
6438 (org-mode)
6439 (font-lock-fontify-buffer)
6440 (buffer-string))))
6442 (defvar org-m nil)
6443 (defvar org-l nil)
6444 (defvar org-f nil)
6445 (defun org-get-level-face (n)
6446 "Get the right face for match N in font-lock matching of headlines."
6447 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6448 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6449 (if org-cycle-level-faces
6450 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6451 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6452 (cond
6453 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6454 ((eq n 2) org-f)
6455 (t (if org-level-color-stars-only nil org-f))))
6458 (defun org-get-todo-face (kwd)
6459 "Get the right face for a TODO keyword KWD.
6460 If KWD is a number, get the corresponding match group."
6461 (if (numberp kwd) (setq kwd (match-string kwd)))
6462 (or (org-face-from-face-or-color
6463 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6464 (and (member kwd org-done-keywords) 'org-done)
6465 'org-todo))
6467 (defun org-face-from-face-or-color (context inherit face-or-color)
6468 "Create a face list that inherits INHERIT, but sets the foreground color.
6469 When FACE-OR-COLOR is not a string, just return it."
6470 (if (stringp face-or-color)
6471 (list :inherit inherit
6472 (cdr (assoc context org-faces-easy-properties))
6473 face-or-color)
6474 face-or-color))
6476 (defun org-font-lock-add-tag-faces (limit)
6477 "Add the special tag faces."
6478 (when (and org-tag-faces org-tags-special-faces-re)
6479 (while (re-search-forward org-tags-special-faces-re limit t)
6480 (add-text-properties (match-beginning 1) (match-end 1)
6481 (list 'face (org-get-tag-face 1)
6482 'font-lock-fontified t))
6483 (backward-char 1))))
6485 (defun org-font-lock-add-priority-faces (limit)
6486 "Add the special priority faces."
6487 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6488 (when (save-match-data (org-at-heading-p))
6489 (add-text-properties
6490 (match-beginning 0) (match-end 0)
6491 (list 'face (or (org-face-from-face-or-color
6492 'priority 'org-priority
6493 (cdr (assoc (char-after (match-beginning 1))
6494 org-priority-faces)))
6495 'org-priority)
6496 'font-lock-fontified t)))))
6498 (defun org-get-tag-face (kwd)
6499 "Get the right face for a TODO keyword KWD.
6500 If KWD is a number, get the corresponding match group."
6501 (if (numberp kwd) (setq kwd (match-string kwd)))
6502 (or (org-face-from-face-or-color
6503 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6504 'org-tag))
6506 (defun org-unfontify-region (beg end &optional maybe_loudly)
6507 "Remove fontification and activation overlays from links."
6508 (font-lock-default-unfontify-region beg end)
6509 (let* ((buffer-undo-list t)
6510 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6511 (inhibit-modification-hooks t)
6512 deactivate-mark buffer-file-name buffer-file-truename)
6513 (org-decompose-region beg end)
6514 (remove-text-properties beg end
6515 '(mouse-face t keymap t org-linked-text t
6516 invisible t intangible t
6517 org-emphasis t))
6518 (org-remove-font-lock-display-properties beg end)))
6520 (defconst org-script-display '(((raise -0.3) (height 0.7))
6521 ((raise 0.3) (height 0.7))
6522 ((raise -0.5))
6523 ((raise 0.5)))
6524 "Display properties for showing superscripts and subscripts.")
6526 (defun org-remove-font-lock-display-properties (beg end)
6527 "Remove specific display properties that have been added by font lock.
6528 The will remove the raise properties that are used to show superscripts
6529 and subscripts."
6530 (let (next prop)
6531 (while (< beg end)
6532 (setq next (next-single-property-change beg 'display nil end)
6533 prop (get-text-property beg 'display))
6534 (if (member prop org-script-display)
6535 (put-text-property beg next 'display nil))
6536 (setq beg next))))
6538 (defun org-raise-scripts (limit)
6539 "Add raise properties to sub/superscripts."
6540 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6541 (if (re-search-forward
6542 (if (eq org-use-sub-superscripts t)
6543 org-match-substring-regexp
6544 org-match-substring-with-braces-regexp)
6545 limit t)
6546 (let* ((pos (point)) table-p comment-p
6547 (mpos (match-beginning 3))
6548 (emph-p (get-text-property mpos 'org-emphasis))
6549 (link-p (get-text-property mpos 'mouse-face))
6550 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6551 (goto-char (point-at-bol))
6552 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6553 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6554 (goto-char pos)
6555 ;; Handle a_b^c
6556 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6557 (if (or comment-p emph-p link-p keyw-p)
6559 (put-text-property (match-beginning 3) (match-end 0)
6560 'display
6561 (if (equal (char-after (match-beginning 2)) ?^)
6562 (nth (if table-p 3 1) org-script-display)
6563 (nth (if table-p 2 0) org-script-display)))
6564 (add-text-properties (match-beginning 2) (match-end 2)
6565 (list 'invisible t
6566 'org-dwidth t 'org-dwidth-n 1))
6567 (if (and (eq (char-after (match-beginning 3)) ?{)
6568 (eq (char-before (match-end 3)) ?}))
6569 (progn
6570 (add-text-properties
6571 (match-beginning 3) (1+ (match-beginning 3))
6572 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6573 (add-text-properties
6574 (1- (match-end 3)) (match-end 3)
6575 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6576 t)))))
6578 ;;;; Visibility cycling, including org-goto and indirect buffer
6580 ;;; Cycling
6582 (defvar org-cycle-global-status nil)
6583 (make-variable-buffer-local 'org-cycle-global-status)
6584 (put 'org-cycle-global-status 'org-state t)
6585 (defvar org-cycle-subtree-status nil)
6586 (make-variable-buffer-local 'org-cycle-subtree-status)
6587 (put 'org-cycle-subtree-status 'org-state t)
6589 (defvar org-inlinetask-min-level)
6591 (defun org-unlogged-message (&rest args)
6592 "Display a message, but avoid logging it in the *Messages* buffer."
6593 (let ((message-log-max nil))
6594 (apply 'message args)))
6596 ;;;###autoload
6597 (defun org-cycle (&optional arg)
6598 "TAB-action and visibility cycling for Org-mode.
6600 This is the command invoked in Org-mode by the TAB key. Its main purpose
6601 is outline visibility cycling, but it also invokes other actions
6602 in special contexts.
6604 - When this function is called with a prefix argument, rotate the entire
6605 buffer through 3 states (global cycling)
6606 1. OVERVIEW: Show only top-level headlines.
6607 2. CONTENTS: Show all headlines of all levels, but no body text.
6608 3. SHOW ALL: Show everything.
6609 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6610 determined by the variable `org-startup-folded', and by any VISIBILITY
6611 properties in the buffer.
6612 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6613 including any drawers.
6615 - When inside a table, re-align the table and move to the next field.
6617 - When point is at the beginning of a headline, rotate the subtree started
6618 by this line through 3 different states (local cycling)
6619 1. FOLDED: Only the main headline is shown.
6620 2. CHILDREN: The main headline and the direct children are shown.
6621 From this state, you can move to one of the children
6622 and zoom in further.
6623 3. SUBTREE: Show the entire subtree, including body text.
6624 If there is no subtree, switch directly from CHILDREN to FOLDED.
6626 - When point is at the beginning of an empty headline and the variable
6627 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6628 of the headline by demoting and promoting it to likely levels. This
6629 speeds up creation document structure by pressing TAB once or several
6630 times right after creating a new headline.
6632 - When there is a numeric prefix, go up to a heading with level ARG, do
6633 a `show-subtree' and return to the previous cursor position. If ARG
6634 is negative, go up that many levels.
6636 - When point is not at the beginning of a headline, execute the global
6637 binding for TAB, which is re-indenting the line. See the option
6638 `org-cycle-emulate-tab' for details.
6640 - Special case: if point is at the beginning of the buffer and there is
6641 no headline in line 1, this function will act as if called with prefix arg
6642 (C-u TAB, same as S-TAB) also when called without prefix arg.
6643 But only if also the variable `org-cycle-global-at-bob' is t."
6644 (interactive "P")
6645 (org-load-modules-maybe)
6646 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6647 (and org-cycle-level-after-item/entry-creation
6648 (or (org-cycle-level)
6649 (org-cycle-item-indentation))))
6650 (let* ((limit-level
6651 (or org-cycle-max-level
6652 (and (boundp 'org-inlinetask-min-level)
6653 org-inlinetask-min-level
6654 (1- org-inlinetask-min-level))))
6655 (nstars (and limit-level
6656 (if org-odd-levels-only
6657 (and limit-level (1- (* limit-level 2)))
6658 limit-level)))
6659 (org-outline-regexp
6660 (if (not (derived-mode-p 'org-mode))
6661 outline-regexp
6662 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6663 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6664 (not (looking-at org-outline-regexp))))
6665 (org-cycle-hook
6666 (if bob-special
6667 (delq 'org-optimize-window-after-visibility-change
6668 (copy-sequence org-cycle-hook))
6669 org-cycle-hook))
6670 (pos (point)))
6672 (if (or bob-special (equal arg '(4)))
6673 ;; special case: use global cycling
6674 (setq arg t))
6676 (cond
6678 ((equal arg '(16))
6679 (setq last-command 'dummy)
6680 (org-set-startup-visibility)
6681 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6683 ((equal arg '(64))
6684 (show-all)
6685 (org-unlogged-message "Entire buffer visible, including drawers"))
6687 ;; Try cdlatex TAB completion
6688 ((org-try-cdlatex-tab))
6690 ;; Table: enter it or move to the next field.
6691 ((org-at-table-p 'any)
6692 (if (org-at-table.el-p)
6693 (message "Use C-c ' to edit table.el tables")
6694 (if arg (org-table-edit-field t)
6695 (org-table-justify-field-maybe)
6696 (call-interactively 'org-table-next-field))))
6698 ((run-hook-with-args-until-success
6699 'org-tab-after-check-for-table-hook))
6701 ;; Global cycling: delegate to `org-cycle-internal-global'.
6702 ((eq arg t) (org-cycle-internal-global))
6704 ;; Drawers: delegate to `org-flag-drawer'.
6705 ((save-excursion
6706 (beginning-of-line 1)
6707 (looking-at org-drawer-regexp))
6708 (org-flag-drawer ; toggle block visibility
6709 (not (get-char-property (match-end 0) 'invisible))))
6711 ;; Show-subtree, ARG levels up from here.
6712 ((integerp arg)
6713 (save-excursion
6714 (org-back-to-heading)
6715 (outline-up-heading (if (< arg 0) (- arg)
6716 (- (funcall outline-level) arg)))
6717 (org-show-subtree)))
6719 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6720 ((and (featurep 'org-inlinetask)
6721 (org-inlinetask-at-task-p)
6722 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6723 (org-inlinetask-toggle-visibility))
6725 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6726 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6727 (save-excursion (beginning-of-line 1)
6728 (looking-at org-outline-regexp)))
6729 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6730 (org-cycle-internal-local))
6732 ;; From there: TAB emulation and template completion.
6733 (buffer-read-only (org-back-to-heading))
6735 ((run-hook-with-args-until-success
6736 'org-tab-after-check-for-cycling-hook))
6738 ((org-try-structure-completion))
6740 ((run-hook-with-args-until-success
6741 'org-tab-before-tab-emulation-hook))
6743 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6744 (or (not (bolp))
6745 (not (looking-at org-outline-regexp))))
6746 (call-interactively (global-key-binding "\t")))
6748 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6749 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6750 (or (and (eq org-cycle-emulate-tab 'white)
6751 (= (match-end 0) (point-at-eol)))
6752 (and (eq org-cycle-emulate-tab 'whitestart)
6753 (>= (match-end 0) pos))))
6755 (eq org-cycle-emulate-tab t))
6756 (call-interactively (global-key-binding "\t")))
6758 (t (save-excursion
6759 (org-back-to-heading)
6760 (org-cycle)))))))
6762 (defun org-cycle-internal-global ()
6763 "Do the global cycling action."
6764 ;; Hack to avoid display of messages for .org attachments in Gnus
6765 (let ((ga (string-match "\\*fontification" (buffer-name))))
6766 (cond
6767 ((and (eq last-command this-command)
6768 (eq org-cycle-global-status 'overview))
6769 ;; We just created the overview - now do table of contents
6770 ;; This can be slow in very large buffers, so indicate action
6771 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6772 (unless ga (org-unlogged-message "CONTENTS..."))
6773 (org-content)
6774 (unless ga (org-unlogged-message "CONTENTS...done"))
6775 (setq org-cycle-global-status 'contents)
6776 (run-hook-with-args 'org-cycle-hook 'contents))
6778 ((and (eq last-command this-command)
6779 (eq org-cycle-global-status 'contents))
6780 ;; We just showed the table of contents - now show everything
6781 (run-hook-with-args 'org-pre-cycle-hook 'all)
6782 (show-all)
6783 (unless ga (org-unlogged-message "SHOW ALL"))
6784 (setq org-cycle-global-status 'all)
6785 (run-hook-with-args 'org-cycle-hook 'all))
6788 ;; Default action: go to overview
6789 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6790 (org-overview)
6791 (unless ga (org-unlogged-message "OVERVIEW"))
6792 (setq org-cycle-global-status 'overview)
6793 (run-hook-with-args 'org-cycle-hook 'overview)))))
6795 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6797 (defun org-cycle-internal-local ()
6798 "Do the local cycling action."
6799 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6800 ;; First, determine end of headline (EOH), end of subtree or item
6801 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6802 (save-excursion
6803 (if (org-at-item-p)
6804 (progn
6805 (beginning-of-line)
6806 (setq struct (org-list-struct))
6807 (setq eoh (point-at-eol))
6808 (setq eos (org-list-get-item-end-before-blank (point) struct))
6809 (setq has-children (org-list-has-child-p (point) struct)))
6810 (org-back-to-heading)
6811 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6812 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6813 (setq has-children
6814 (or (save-excursion
6815 (let ((level (funcall outline-level)))
6816 (outline-next-heading)
6817 (and (org-at-heading-p t)
6818 (> (funcall outline-level) level))))
6819 (save-excursion
6820 (org-list-search-forward (org-item-beginning-re) eos t)))))
6821 ;; Determine end invisible part of buffer (EOL)
6822 (beginning-of-line 2)
6823 ;; XEmacs doesn't have `next-single-char-property-change'
6824 (if (featurep 'xemacs)
6825 (while (and (not (eobp)) ;; this is like `next-line'
6826 (get-char-property (1- (point)) 'invisible))
6827 (beginning-of-line 2))
6828 (while (and (not (eobp)) ;; this is like `next-line'
6829 (get-char-property (1- (point)) 'invisible))
6830 (goto-char (next-single-char-property-change (point) 'invisible))
6831 (and (eolp) (beginning-of-line 2))))
6832 (setq eol (point)))
6833 ;; Find out what to do next and set `this-command'
6834 (cond
6835 ((= eos eoh)
6836 ;; Nothing is hidden behind this heading
6837 (unless (org-before-first-heading-p)
6838 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6839 (org-unlogged-message "EMPTY ENTRY")
6840 (setq org-cycle-subtree-status nil)
6841 (save-excursion
6842 (goto-char eos)
6843 (outline-next-heading)
6844 (if (outline-invisible-p) (org-flag-heading nil))))
6845 ((and (or (>= eol eos)
6846 (not (string-match "\\S-" (buffer-substring eol eos))))
6847 (or has-children
6848 (not (setq children-skipped
6849 org-cycle-skip-children-state-if-no-children))))
6850 ;; Entire subtree is hidden in one line: children view
6851 (unless (org-before-first-heading-p)
6852 (run-hook-with-args 'org-pre-cycle-hook 'children))
6853 (if (org-at-item-p)
6854 (org-list-set-item-visibility (point-at-bol) struct 'children)
6855 (org-show-entry)
6856 (org-with-limited-levels (show-children))
6857 ;; FIXME: This slows down the func way too much.
6858 ;; How keep drawers hidden in subtree anyway?
6859 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6860 ;; (org-cycle-hide-drawers 'subtree))
6862 ;; Fold every list in subtree to top-level items.
6863 (when (eq org-cycle-include-plain-lists 'integrate)
6864 (save-excursion
6865 (org-back-to-heading)
6866 (while (org-list-search-forward (org-item-beginning-re) eos t)
6867 (beginning-of-line 1)
6868 (let* ((struct (org-list-struct))
6869 (prevs (org-list-prevs-alist struct))
6870 (end (org-list-get-bottom-point struct)))
6871 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6872 (org-list-get-all-items (point) struct prevs))
6873 (goto-char (if (< end eos) end eos)))))))
6874 (org-unlogged-message "CHILDREN")
6875 (save-excursion
6876 (goto-char eos)
6877 (outline-next-heading)
6878 (if (outline-invisible-p) (org-flag-heading nil)))
6879 (setq org-cycle-subtree-status 'children)
6880 (unless (org-before-first-heading-p)
6881 (run-hook-with-args 'org-cycle-hook 'children)))
6882 ((or children-skipped
6883 (and (eq last-command this-command)
6884 (eq org-cycle-subtree-status 'children)))
6885 ;; We just showed the children, or no children are there,
6886 ;; now show everything.
6887 (unless (org-before-first-heading-p)
6888 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6889 (outline-flag-region eoh eos nil)
6890 (org-unlogged-message
6891 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6892 (setq org-cycle-subtree-status 'subtree)
6893 (unless (org-before-first-heading-p)
6894 (run-hook-with-args 'org-cycle-hook 'subtree)))
6896 ;; Default action: hide the subtree.
6897 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6898 (outline-flag-region eoh eos t)
6899 (org-unlogged-message "FOLDED")
6900 (setq org-cycle-subtree-status 'folded)
6901 (unless (org-before-first-heading-p)
6902 (run-hook-with-args 'org-cycle-hook 'folded))))))
6904 ;;;###autoload
6905 (defun org-global-cycle (&optional arg)
6906 "Cycle the global visibility. For details see `org-cycle'.
6907 With \\[universal-argument] prefix arg, switch to startup visibility.
6908 With a numeric prefix, show all headlines up to that level."
6909 (interactive "P")
6910 (let ((org-cycle-include-plain-lists
6911 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6912 (cond
6913 ((integerp arg)
6914 (show-all)
6915 (hide-sublevels arg)
6916 (setq org-cycle-global-status 'contents))
6917 ((equal arg '(4))
6918 (org-set-startup-visibility)
6919 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6921 (org-cycle '(4))))))
6923 (defun org-set-startup-visibility ()
6924 "Set the visibility required by startup options and properties."
6925 (cond
6926 ((eq org-startup-folded t)
6927 (org-overview))
6928 ((eq org-startup-folded 'content)
6929 (org-content))
6930 ((or (eq org-startup-folded 'showeverything)
6931 (eq org-startup-folded nil))
6932 (show-all)))
6933 (unless (eq org-startup-folded 'showeverything)
6934 (if org-hide-block-startup (org-hide-block-all))
6935 (org-set-visibility-according-to-property 'no-cleanup)
6936 (org-cycle-hide-archived-subtrees 'all)
6937 (org-cycle-hide-drawers 'all)
6938 (org-cycle-show-empty-lines t)))
6940 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6941 "Switch subtree visibilities according to :VISIBILITY: property."
6942 (interactive)
6943 (let (org-show-entry-below state)
6944 (save-excursion
6945 (goto-char (point-min))
6946 (while (re-search-forward
6947 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6948 nil t)
6949 (setq state (match-string 1))
6950 (save-excursion
6951 (org-back-to-heading t)
6952 (hide-subtree)
6953 (org-reveal)
6954 (cond
6955 ((equal state '("fold" "folded"))
6956 (hide-subtree))
6957 ((equal state "children")
6958 (org-show-hidden-entry)
6959 (show-children))
6960 ((equal state "content")
6961 (save-excursion
6962 (save-restriction
6963 (org-narrow-to-subtree)
6964 (org-content))))
6965 ((member state '("all" "showall"))
6966 (show-subtree)))))
6967 (unless no-cleanup
6968 (org-cycle-hide-archived-subtrees 'all)
6969 (org-cycle-hide-drawers 'all)
6970 (org-cycle-show-empty-lines 'all)))))
6972 ;; This function uses outline-regexp instead of the more fundamental
6973 ;; org-outline-regexp so that org-cycle-global works outside of Org
6974 ;; buffers, where outline-regexp is needed.
6975 (defun org-overview ()
6976 "Switch to overview mode, showing only top-level headlines.
6977 Really, this shows all headlines with level equal or greater than the level
6978 of the first headline in the buffer. This is important, because if the
6979 first headline is not level one, then (hide-sublevels 1) gives confusing
6980 results."
6981 (interactive)
6982 (let ((pos (point))
6983 (level (save-excursion
6984 (goto-char (point-min))
6985 (if (re-search-forward (concat "^" outline-regexp) nil t)
6986 (progn
6987 (goto-char (match-beginning 0))
6988 (funcall outline-level))))))
6989 (and level (hide-sublevels level))
6990 (recenter '(4))
6991 (goto-char pos)))
6993 (defun org-content (&optional arg)
6994 "Show all headlines in the buffer, like a table of contents.
6995 With numerical argument N, show content up to level N."
6996 (interactive "P")
6997 (org-overview)
6998 (save-excursion
6999 ;; Visit all headings and show their offspring
7000 (and (integerp arg) (org-overview))
7001 (goto-char (point-max))
7002 (catch 'exit
7003 (while (and (progn (condition-case nil
7004 (outline-previous-visible-heading 1)
7005 (error (goto-char (point-min))))
7007 (looking-at org-outline-regexp))
7008 (if (integerp arg)
7009 (show-children (1- arg))
7010 (show-branches))
7011 (if (bobp) (throw 'exit nil))))))
7013 (defun org-optimize-window-after-visibility-change (state)
7014 "Adjust the window after a change in outline visibility.
7015 This function is the default value of the hook `org-cycle-hook'."
7016 (when (get-buffer-window (current-buffer))
7017 (cond
7018 ((eq state 'content) nil)
7019 ((eq state 'all) nil)
7020 ((eq state 'folded) nil)
7021 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7022 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7024 (defun org-remove-empty-overlays-at (pos)
7025 "Remove outline overlays that do not contain non-white stuff."
7026 (mapc
7027 (lambda (o)
7028 (and (eq 'outline (overlay-get o 'invisible))
7029 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7030 (overlay-end o))))
7031 (delete-overlay o)))
7032 (overlays-at pos)))
7034 (defun org-clean-visibility-after-subtree-move ()
7035 "Fix visibility issues after moving a subtree."
7036 ;; First, find a reasonable region to look at:
7037 ;; Start two siblings above, end three below
7038 (let* ((beg (save-excursion
7039 (and (org-get-last-sibling)
7040 (org-get-last-sibling))
7041 (point)))
7042 (end (save-excursion
7043 (and (org-get-next-sibling)
7044 (org-get-next-sibling)
7045 (org-get-next-sibling))
7046 (if (org-at-heading-p)
7047 (point-at-eol)
7048 (point))))
7049 (level (looking-at "\\*+"))
7050 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7051 (save-excursion
7052 (save-restriction
7053 (narrow-to-region beg end)
7054 (when re
7055 ;; Properly fold already folded siblings
7056 (goto-char (point-min))
7057 (while (re-search-forward re nil t)
7058 (if (and (not (outline-invisible-p))
7059 (save-excursion
7060 (goto-char (point-at-eol)) (outline-invisible-p)))
7061 (hide-entry))))
7062 (org-cycle-show-empty-lines 'overview)
7063 (org-cycle-hide-drawers 'overview)))))
7065 (defun org-cycle-show-empty-lines (state)
7066 "Show empty lines above all visible headlines.
7067 The region to be covered depends on STATE when called through
7068 `org-cycle-hook'. Lisp program can use t for STATE to get the
7069 entire buffer covered. Note that an empty line is only shown if there
7070 are at least `org-cycle-separator-lines' empty lines before the headline."
7071 (when (not (= org-cycle-separator-lines 0))
7072 (save-excursion
7073 (let* ((n (abs org-cycle-separator-lines))
7074 (re (cond
7075 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7076 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7077 (t (let ((ns (number-to-string (- n 2))))
7078 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7079 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7080 beg end b e)
7081 (cond
7082 ((memq state '(overview contents t))
7083 (setq beg (point-min) end (point-max)))
7084 ((memq state '(children folded))
7085 (setq beg (point) end (progn (org-end-of-subtree t t)
7086 (beginning-of-line 2)
7087 (point)))))
7088 (when beg
7089 (goto-char beg)
7090 (while (re-search-forward re end t)
7091 (unless (get-char-property (match-end 1) 'invisible)
7092 (setq e (match-end 1))
7093 (if (< org-cycle-separator-lines 0)
7094 (setq b (save-excursion
7095 (goto-char (match-beginning 0))
7096 (org-back-over-empty-lines)
7097 (if (save-excursion
7098 (goto-char (max (point-min) (1- (point))))
7099 (org-at-heading-p))
7100 (1- (point))
7101 (point))))
7102 (setq b (match-beginning 1)))
7103 (outline-flag-region b e nil)))))))
7104 ;; Never hide empty lines at the end of the file.
7105 (save-excursion
7106 (goto-char (point-max))
7107 (outline-previous-heading)
7108 (outline-end-of-heading)
7109 (if (and (looking-at "[ \t\n]+")
7110 (= (match-end 0) (point-max)))
7111 (outline-flag-region (point) (match-end 0) nil))))
7113 (defun org-show-empty-lines-in-parent ()
7114 "Move to the parent and re-show empty lines before visible headlines."
7115 (save-excursion
7116 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7117 (org-cycle-show-empty-lines context))))
7119 (defun org-files-list ()
7120 "Return `org-agenda-files' list, plus all open org-mode files.
7121 This is useful for operations that need to scan all of a user's
7122 open and agenda-wise Org files."
7123 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7124 (dolist (buf (buffer-list))
7125 (with-current-buffer buf
7126 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7127 (let ((file (expand-file-name (buffer-file-name))))
7128 (unless (member file files)
7129 (push file files))))))
7130 files))
7132 (defsubst org-entry-beginning-position ()
7133 "Return the beginning position of the current entry."
7134 (save-excursion (outline-back-to-heading t) (point)))
7136 (defsubst org-entry-end-position ()
7137 "Return the end position of the current entry."
7138 (save-excursion (outline-next-heading) (point)))
7140 (defun org-cycle-hide-drawers (state &optional exceptions)
7141 "Re-hide all drawers after a visibility state change.
7142 When non-nil, optional argument EXCEPTIONS is a list of strings
7143 specifying which drawers should not be hidden."
7144 (when (and (derived-mode-p 'org-mode)
7145 (not (memq state '(overview folded contents))))
7146 (save-excursion
7147 (let* ((globalp (memq state '(contents all)))
7148 (beg (if globalp (point-min) (point)))
7149 (end (if globalp (point-max)
7150 (if (eq state 'children)
7151 (save-excursion (outline-next-heading) (point))
7152 (org-end-of-subtree t)))))
7153 (goto-char beg)
7154 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7155 (unless (member-ignore-case (match-string 1) exceptions)
7156 (let ((drawer (org-element-at-point)))
7157 (when (memq (org-element-type drawer) '(drawer property-drawer))
7158 (org-flag-drawer t drawer)
7159 ;; Make sure to skip drawer entirely or we might flag
7160 ;; it another time when matching its ending line with
7161 ;; `org-drawer-regexp'.
7162 (goto-char (org-element-property :end drawer))))))))))
7164 (defun org-cycle-hide-inline-tasks (state)
7165 "Re-hide inline tasks when switching to 'contents or 'children
7166 visibility state."
7167 (case state
7168 (contents
7169 (when (org-bound-and-true-p org-inlinetask-min-level)
7170 (hide-sublevels (1- org-inlinetask-min-level))))
7171 (children
7172 (when (featurep 'org-inlinetask)
7173 (save-excursion
7174 (while (and (outline-next-heading)
7175 (org-inlinetask-at-task-p))
7176 (org-inlinetask-toggle-visibility)
7177 (org-inlinetask-goto-end)))))))
7179 (defun org-flag-drawer (flag &optional element)
7180 "When FLAG is non-nil, hide the drawer we are at.
7181 Otherwise make it visible. When optional argument ELEMENT is
7182 a parsed drawer, as returned by `org-element-at-point', hide or
7183 show that drawer instead."
7184 (let ((drawer (or element (org-element-at-point))))
7185 (when (memq (org-element-type drawer) '(drawer property-drawer))
7186 (save-excursion
7187 (goto-char (org-element-property :post-affiliated drawer))
7188 (outline-flag-region
7189 (line-end-position)
7190 (progn (goto-char (org-element-property :end drawer))
7191 (skip-chars-backward " \r\t\n")
7192 (line-end-position))
7193 flag)))))
7195 (defun org-subtree-end-visible-p ()
7196 "Is the end of the current subtree visible?"
7197 (pos-visible-in-window-p
7198 (save-excursion (org-end-of-subtree t) (point))))
7200 (defun org-first-headline-recenter (&optional N)
7201 "Move cursor to the first headline and recenter the headline.
7202 Optional argument N means put the headline into the Nth line of the window."
7203 (goto-char (point-min))
7204 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7205 (beginning-of-line)
7206 (recenter (prefix-numeric-value N))))
7208 ;;; Saving and restoring visibility
7210 (defun org-outline-overlay-data (&optional use-markers)
7211 "Return a list of the locations of all outline overlays.
7212 These are overlays with the `invisible' property value `outline'.
7213 The return value is a list of cons cells, with start and stop
7214 positions for each overlay.
7215 If USE-MARKERS is set, return the positions as markers."
7216 (let (beg end)
7217 (save-excursion
7218 (save-restriction
7219 (widen)
7220 (delq nil
7221 (mapcar (lambda (o)
7222 (when (eq (overlay-get o 'invisible) 'outline)
7223 (setq beg (overlay-start o)
7224 end (overlay-end o))
7225 (and beg end (> end beg)
7226 (if use-markers
7227 (cons (copy-marker beg)
7228 (copy-marker end t))
7229 (cons beg end)))))
7230 (overlays-in (point-min) (point-max))))))))
7232 (defun org-set-outline-overlay-data (data)
7233 "Create visibility overlays for all positions in DATA.
7234 DATA should have been made by `org-outline-overlay-data'."
7235 (let (o)
7236 (save-excursion
7237 (save-restriction
7238 (widen)
7239 (show-all)
7240 (mapc (lambda (c)
7241 (outline-flag-region (car c) (cdr c) t))
7242 data)))))
7244 ;;; Folding of blocks
7246 (defvar org-hide-block-overlays nil
7247 "Overlays hiding blocks.")
7248 (make-variable-buffer-local 'org-hide-block-overlays)
7250 (defun org-block-map (function &optional start end)
7251 "Call FUNCTION at the head of all source blocks in the current buffer.
7252 Optional arguments START and END can be used to limit the range."
7253 (let ((start (or start (point-min)))
7254 (end (or end (point-max))))
7255 (save-excursion
7256 (goto-char start)
7257 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7258 (save-excursion
7259 (save-match-data
7260 (goto-char (match-beginning 0))
7261 (funcall function)))))))
7263 (defun org-hide-block-toggle-all ()
7264 "Toggle the visibility of all blocks in the current buffer."
7265 (org-block-map #'org-hide-block-toggle))
7267 (defun org-hide-block-all ()
7268 "Fold all blocks in the current buffer."
7269 (interactive)
7270 (org-show-block-all)
7271 (org-block-map #'org-hide-block-toggle-maybe))
7273 (defun org-show-block-all ()
7274 "Unfold all blocks in the current buffer."
7275 (interactive)
7276 (mapc 'delete-overlay org-hide-block-overlays)
7277 (setq org-hide-block-overlays nil))
7279 (defun org-hide-block-toggle-maybe ()
7280 "Toggle visibility of block at point."
7281 (interactive)
7282 (let ((case-fold-search t))
7283 (if (save-excursion
7284 (beginning-of-line 1)
7285 (looking-at org-block-regexp))
7286 (progn (org-hide-block-toggle)
7287 t) ;; to signal that we took action
7288 nil))) ;; to signal that we did not
7290 (defun org-hide-block-toggle (&optional force)
7291 "Toggle the visibility of the current block."
7292 (interactive)
7293 (save-excursion
7294 (beginning-of-line)
7295 (if (re-search-forward org-block-regexp nil t)
7296 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7297 (end (match-end 0)) ;; end of entire body
7299 (if (memq t (mapcar (lambda (overlay)
7300 (eq (overlay-get overlay 'invisible)
7301 'org-hide-block))
7302 (overlays-at start)))
7303 (if (or (not force) (eq force 'off))
7304 (mapc (lambda (ov)
7305 (when (member ov org-hide-block-overlays)
7306 (setq org-hide-block-overlays
7307 (delq ov org-hide-block-overlays)))
7308 (when (eq (overlay-get ov 'invisible)
7309 'org-hide-block)
7310 (delete-overlay ov)))
7311 (overlays-at start)))
7312 (setq ov (make-overlay start end))
7313 (overlay-put ov 'invisible 'org-hide-block)
7314 ;; make the block accessible to isearch
7315 (overlay-put
7316 ov 'isearch-open-invisible
7317 (lambda (ov)
7318 (when (member ov org-hide-block-overlays)
7319 (setq org-hide-block-overlays
7320 (delq ov org-hide-block-overlays)))
7321 (when (eq (overlay-get ov 'invisible)
7322 'org-hide-block)
7323 (delete-overlay ov))))
7324 (push ov org-hide-block-overlays)))
7325 (user-error "Not looking at a source block"))))
7327 ;; org-tab-after-check-for-cycling-hook
7328 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7329 ;; Remove overlays when changing major mode
7330 (add-hook 'org-mode-hook
7331 (lambda () (org-add-hook 'change-major-mode-hook
7332 'org-show-block-all 'append 'local)))
7334 ;;; Org-goto
7336 (defvar org-goto-window-configuration nil)
7337 (defvar org-goto-marker nil)
7338 (defvar org-goto-map)
7339 (defun org-goto-map ()
7340 "Set the keymap `org-goto'."
7341 (setq org-goto-map
7342 (let ((map (make-sparse-keymap)))
7343 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7344 mouse-drag-region universal-argument org-occur))
7345 cmd)
7346 (while (setq cmd (pop cmds))
7347 (substitute-key-definition cmd cmd map global-map)))
7348 (suppress-keymap map)
7349 (org-defkey map "\C-m" 'org-goto-ret)
7350 (org-defkey map [(return)] 'org-goto-ret)
7351 (org-defkey map [(left)] 'org-goto-left)
7352 (org-defkey map [(right)] 'org-goto-right)
7353 (org-defkey map [(control ?g)] 'org-goto-quit)
7354 (org-defkey map "\C-i" 'org-cycle)
7355 (org-defkey map [(tab)] 'org-cycle)
7356 (org-defkey map [(down)] 'outline-next-visible-heading)
7357 (org-defkey map [(up)] 'outline-previous-visible-heading)
7358 (if org-goto-auto-isearch
7359 (if (fboundp 'define-key-after)
7360 (define-key-after map [t] 'org-goto-local-auto-isearch)
7361 nil)
7362 (org-defkey map "q" 'org-goto-quit)
7363 (org-defkey map "n" 'outline-next-visible-heading)
7364 (org-defkey map "p" 'outline-previous-visible-heading)
7365 (org-defkey map "f" 'outline-forward-same-level)
7366 (org-defkey map "b" 'outline-backward-same-level)
7367 (org-defkey map "u" 'outline-up-heading))
7368 (org-defkey map "/" 'org-occur)
7369 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7370 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7371 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7372 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7373 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7374 map)))
7376 (defconst org-goto-help
7377 "Browse buffer copy, to find location or copy text.%s
7378 RET=jump to location C-g=quit and return to previous location
7379 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7381 (defvar org-goto-start-pos) ; dynamically scoped parameter
7383 (defun org-goto (&optional alternative-interface)
7384 "Look up a different location in the current file, keeping current visibility.
7386 When you want look-up or go to a different location in a
7387 document, the fastest way is often to fold the entire buffer and
7388 then dive into the tree. This method has the disadvantage, that
7389 the previous location will be folded, which may not be what you
7390 want.
7392 This command works around this by showing a copy of the current
7393 buffer in an indirect buffer, in overview mode. You can dive
7394 into the tree in that copy, use org-occur and incremental search
7395 to find a location. When pressing RET or `Q', the command
7396 returns to the original buffer in which the visibility is still
7397 unchanged. After RET it will also jump to the location selected
7398 in the indirect buffer and expose the headline hierarchy above.
7400 With a prefix argument, use the alternative interface: e.g. if
7401 `org-goto-interface' is 'outline use 'outline-path-completion."
7402 (interactive "P")
7403 (org-goto-map)
7404 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7405 (org-refile-use-outline-path t)
7406 (org-refile-target-verify-function nil)
7407 (interface
7408 (if (not alternative-interface)
7409 org-goto-interface
7410 (if (eq org-goto-interface 'outline)
7411 'outline-path-completion
7412 'outline)))
7413 (org-goto-start-pos (point))
7414 (selected-point
7415 (if (eq interface 'outline)
7416 (car (org-get-location (current-buffer) org-goto-help))
7417 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7418 (org-refile-check-position pa)
7419 (nth 3 pa)))))
7420 (if selected-point
7421 (progn
7422 (org-mark-ring-push org-goto-start-pos)
7423 (goto-char selected-point)
7424 (if (or (outline-invisible-p) (org-invisible-p2))
7425 (org-show-context 'org-goto)))
7426 (message "Quit"))))
7428 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7429 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7430 (defvar org-goto-local-auto-isearch-map) ; defined below
7432 (defun org-get-location (buf help)
7433 "Let the user select a location in the Org-mode buffer BUF.
7434 This function uses a recursive edit. It returns the selected position
7435 or nil."
7436 (org-no-popups
7437 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7438 (isearch-hide-immediately nil)
7439 (isearch-search-fun-function
7440 (lambda () 'org-goto-local-search-headings))
7441 (org-goto-selected-point org-goto-exit-command))
7442 (save-excursion
7443 (save-window-excursion
7444 (delete-other-windows)
7445 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7446 (org-pop-to-buffer-same-window
7447 (condition-case nil
7448 (make-indirect-buffer (current-buffer) "*org-goto*")
7449 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7450 (with-output-to-temp-buffer "*Org Help*"
7451 (princ (format help (if org-goto-auto-isearch
7452 " Just type for auto-isearch."
7453 " n/p/f/b/u to navigate, q to quit."))))
7454 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7455 (setq buffer-read-only nil)
7456 (let ((org-startup-truncated t)
7457 (org-startup-folded nil)
7458 (org-startup-align-all-tables nil))
7459 (org-mode)
7460 (org-overview))
7461 (setq buffer-read-only t)
7462 (if (and (boundp 'org-goto-start-pos)
7463 (integer-or-marker-p org-goto-start-pos))
7464 (let ((org-show-hierarchy-above t)
7465 (org-show-siblings t)
7466 (org-show-following-heading t))
7467 (goto-char org-goto-start-pos)
7468 (and (outline-invisible-p) (org-show-context)))
7469 (goto-char (point-min)))
7470 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7471 (message "Select location and press RET")
7472 (use-local-map org-goto-map)
7473 (recursive-edit)))
7474 (kill-buffer "*org-goto*")
7475 (cons org-goto-selected-point org-goto-exit-command))))
7477 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7478 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7479 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7480 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7482 (defun org-goto-local-search-headings (string bound noerror)
7483 "Search and make sure that any matches are in headlines."
7484 (catch 'return
7485 (while (if isearch-forward
7486 (search-forward string bound noerror)
7487 (search-backward string bound noerror))
7488 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7489 (and (member :headline context)
7490 (not (member :tags context))))
7491 (throw 'return (point))))))
7493 (defun org-goto-local-auto-isearch ()
7494 "Start isearch."
7495 (interactive)
7496 (goto-char (point-min))
7497 (let ((keys (this-command-keys)))
7498 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7499 (isearch-mode t)
7500 (isearch-process-search-char (string-to-char keys)))))
7502 (defun org-goto-ret (&optional arg)
7503 "Finish `org-goto' by going to the new location."
7504 (interactive "P")
7505 (setq org-goto-selected-point (point)
7506 org-goto-exit-command 'return)
7507 (throw 'exit nil))
7509 (defun org-goto-left ()
7510 "Finish `org-goto' by going to the new location."
7511 (interactive)
7512 (if (org-at-heading-p)
7513 (progn
7514 (beginning-of-line 1)
7515 (setq org-goto-selected-point (point)
7516 org-goto-exit-command 'left)
7517 (throw 'exit nil))
7518 (user-error "Not on a heading")))
7520 (defun org-goto-right ()
7521 "Finish `org-goto' by going to the new location."
7522 (interactive)
7523 (if (org-at-heading-p)
7524 (progn
7525 (setq org-goto-selected-point (point)
7526 org-goto-exit-command 'right)
7527 (throw 'exit nil))
7528 (user-error "Not on a heading")))
7530 (defun org-goto-quit ()
7531 "Finish `org-goto' without cursor motion."
7532 (interactive)
7533 (setq org-goto-selected-point nil)
7534 (setq org-goto-exit-command 'quit)
7535 (throw 'exit nil))
7537 ;;; Indirect buffer display of subtrees
7539 (defvar org-indirect-dedicated-frame nil
7540 "This is the frame being used for indirect tree display.")
7541 (defvar org-last-indirect-buffer nil)
7543 (defun org-tree-to-indirect-buffer (&optional arg)
7544 "Create indirect buffer and narrow it to current subtree.
7545 With a numerical prefix ARG, go up to this level and then take that tree.
7546 If ARG is negative, go up that many levels.
7548 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7549 indirect buffer previously made with this command, to avoid proliferation of
7550 indirect buffers. However, when you call the command with a \
7551 \\[universal-argument] prefix, or
7552 when `org-indirect-buffer-display' is `new-frame', the last buffer
7553 is kept so that you can work with several indirect buffers at the same time.
7554 If `org-indirect-buffer-display' is `dedicated-frame', the \
7555 \\[universal-argument] prefix also
7556 requests that a new frame be made for the new buffer, so that the dedicated
7557 frame is not changed."
7558 (interactive "P")
7559 (let ((cbuf (current-buffer))
7560 (cwin (selected-window))
7561 (pos (point))
7562 beg end level heading ibuf)
7563 (save-excursion
7564 (org-back-to-heading t)
7565 (when (numberp arg)
7566 (setq level (org-outline-level))
7567 (if (< arg 0) (setq arg (+ level arg)))
7568 (while (> (setq level (org-outline-level)) arg)
7569 (org-up-heading-safe)))
7570 (setq beg (point)
7571 heading (org-get-heading))
7572 (org-end-of-subtree t t)
7573 (if (org-at-heading-p) (backward-char 1))
7574 (setq end (point)))
7575 (if (and (buffer-live-p org-last-indirect-buffer)
7576 (not (eq org-indirect-buffer-display 'new-frame))
7577 (not arg))
7578 (kill-buffer org-last-indirect-buffer))
7579 (setq ibuf (org-get-indirect-buffer cbuf heading)
7580 org-last-indirect-buffer ibuf)
7581 (cond
7582 ((or (eq org-indirect-buffer-display 'new-frame)
7583 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7584 (select-frame (make-frame))
7585 (delete-other-windows)
7586 (org-pop-to-buffer-same-window ibuf)
7587 (org-set-frame-title heading))
7588 ((eq org-indirect-buffer-display 'dedicated-frame)
7589 (raise-frame
7590 (select-frame (or (and org-indirect-dedicated-frame
7591 (frame-live-p org-indirect-dedicated-frame)
7592 org-indirect-dedicated-frame)
7593 (setq org-indirect-dedicated-frame (make-frame)))))
7594 (delete-other-windows)
7595 (org-pop-to-buffer-same-window ibuf)
7596 (org-set-frame-title (concat "Indirect: " heading)))
7597 ((eq org-indirect-buffer-display 'current-window)
7598 (org-pop-to-buffer-same-window ibuf))
7599 ((eq org-indirect-buffer-display 'other-window)
7600 (pop-to-buffer ibuf))
7601 (t (error "Invalid value")))
7602 (if (featurep 'xemacs)
7603 (save-excursion (org-mode) (turn-on-font-lock)))
7604 (narrow-to-region beg end)
7605 (show-all)
7606 (goto-char pos)
7607 (run-hook-with-args 'org-cycle-hook 'all)
7608 (and (window-live-p cwin) (select-window cwin))))
7610 (defun org-get-indirect-buffer (&optional buffer heading)
7611 (setq buffer (or buffer (current-buffer)))
7612 (let ((n 1) (base (buffer-name buffer)) bname)
7613 (while (buffer-live-p
7614 (get-buffer
7615 (setq bname
7616 (concat base "-"
7617 (if heading (concat heading "-" (number-to-string n))
7618 (number-to-string n))))))
7619 (setq n (1+ n)))
7620 (condition-case nil
7621 (make-indirect-buffer buffer bname 'clone)
7622 (error (make-indirect-buffer buffer bname)))))
7624 (defun org-set-frame-title (title)
7625 "Set the title of the current frame to the string TITLE."
7626 ;; FIXME: how to name a single frame in XEmacs???
7627 (unless (featurep 'xemacs)
7628 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7630 ;;;; Structure editing
7632 ;;; Inserting headlines
7634 (defun org-previous-line-empty-p (&optional next)
7635 "Is the previous line a blank line?
7636 When NEXT is non-nil, check the next line instead."
7637 (save-excursion
7638 (and (not (bobp))
7639 (or (beginning-of-line (if next 2 0)) t)
7640 (save-match-data
7641 (looking-at "[ \t]*$")))))
7643 (defun org-insert-heading (&optional arg invisible-ok)
7644 "Insert a new heading or item with same depth at point.
7646 If point is in a plain list and ARG is nil, add a new list item.
7648 With one universal prefix argument, insert a heading even when
7649 the point is within a list.
7651 With two universal prefix arguments, insert the heading at the
7652 end of the grandparent subtree. For example, if point is within
7653 a 2nd-level heading, then it will insert a 2nd-level heading at
7654 the end of the 1st-level parent heading.
7656 If point is at the beginning of a headline, insert a sibling
7657 before the current headline. If point is not at the beginning,
7658 split the line and create a new headline with the text in the
7659 current line after point \(see `org-M-RET-may-split-line' on how
7660 to modify this behavior).
7662 If point is at the beginning of a normal line, turn this line
7663 into a heading.
7665 When INVISIBLE-OK is set, stop at invisible headlines when going
7666 back. This is important for non-interactive uses of the
7667 command."
7668 (interactive "P")
7669 (if (org-called-interactively-p 'any) (org-reveal))
7670 (let ((itemp (org-in-item-p))
7671 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7672 (respect-content (or org-insert-heading-respect-content
7673 (equal arg '(4))))
7674 (initial-content "")
7675 (adjust-empty-lines t))
7677 (cond
7679 ((or (= (buffer-size) 0)
7680 (and (not (save-excursion
7681 (and (ignore-errors (org-back-to-heading invisible-ok))
7682 (org-at-heading-p))))
7683 (or arg (not itemp))))
7684 ;; At beginning of buffer or so high up that only a heading
7685 ;; makes sense.
7686 (insert
7687 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7688 (if (org-in-src-block-p) ",* " "* "))
7689 (run-hooks 'org-insert-heading-hook))
7691 ((and itemp (not (equal arg '(4))))
7692 ;; Insert an item
7693 (org-insert-item))
7696 ;; Maybe move at the end of the subtree
7697 (when (equal arg '(16))
7698 (org-up-heading-safe)
7699 (org-end-of-subtree t))
7700 ;; Insert a heading
7701 (save-restriction
7702 (widen)
7703 (let* ((level nil)
7704 (on-heading (org-at-heading-p))
7705 (empty-line-p (if on-heading
7706 (org-previous-line-empty-p)
7707 ;; We will decide later
7708 nil))
7709 ;; Get a level string to fall back on
7710 (fix-level
7711 (save-excursion
7712 (org-back-to-heading t)
7713 (if (org-previous-line-empty-p) (setq empty-line-p t))
7714 (looking-at org-outline-regexp)
7715 (make-string (1- (length (match-string 0))) ?*)))
7716 (stars
7717 (save-excursion
7718 (condition-case nil
7719 (progn
7720 (org-back-to-heading invisible-ok)
7721 (when (and (not on-heading)
7722 (featurep 'org-inlinetask)
7723 (integerp org-inlinetask-min-level)
7724 (>= (length (match-string 0))
7725 org-inlinetask-min-level))
7726 ;; Find a heading level before the inline task
7727 (while (and (setq level (org-up-heading-safe))
7728 (>= level org-inlinetask-min-level)))
7729 (if (org-at-heading-p)
7730 (org-back-to-heading invisible-ok)
7731 (error "This should not happen")))
7732 (unless (and (save-excursion
7733 (save-match-data
7734 (org-backward-heading-same-level
7735 1 invisible-ok))
7736 (= (point) (match-beginning 0)))
7737 (not (org-previous-line-empty-p t)))
7738 (setq empty-line-p (or empty-line-p
7739 (org-previous-line-empty-p))))
7740 (match-string 0))
7741 (error (or fix-level "* ")))))
7742 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7743 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7744 pos hide-previous previous-pos)
7746 ;; If we insert after content, move there and clean up whitespace
7747 (when (and respect-content (not (org-on-heading-p)))
7748 (org-end-of-subtree nil t)
7749 (skip-chars-backward " \r\n")
7750 (and (not (looking-back "^\\*+"))
7751 (looking-at "[ \t]+") (replace-match ""))
7752 (unless (eobp) (forward-char 1))
7753 (when (looking-at "^\\*")
7754 (unless (bobp) (backward-char 1))
7755 (insert "\n")))
7757 ;; If we are splitting, grab the text that should be moved to the new headline
7758 (when may-split
7759 (if (org-on-heading-p)
7760 ;; This is a heading, we split intelligently (keeping tags)
7761 (let ((pos (point)))
7762 (goto-char (point-at-bol))
7763 (unless (looking-at org-complex-heading-regexp)
7764 (error "This should not happen"))
7765 (when (and (match-beginning 4)
7766 (> pos (match-beginning 4))
7767 (< pos (match-end 4)))
7768 (setq initial-content (buffer-substring pos (match-end 4)))
7769 (goto-char pos)
7770 (delete-region (point) (match-end 4))
7771 (if (looking-at "[ \t]*$")
7772 (replace-match "")
7773 (insert (make-string (length initial-content) ?\ )))
7774 (setq initial-content (org-trim initial-content)))
7775 (goto-char pos))
7776 ;; a normal line
7777 (unless (bolp)
7778 (setq initial-content (buffer-substring (point) (point-at-eol)))
7779 (delete-region (point) (point-at-eol))
7780 (setq initial-content (org-trim initial-content)))))
7782 ;; If we are at the beginning of the line, insert before it. Else after
7783 (cond
7784 ((and (bolp) (looking-at "[ \t]*$")))
7785 ((and (bolp) (not (looking-at "[ \t]*$")))
7786 (open-line 1))
7788 (goto-char (point-at-eol))
7789 (insert "\n")))
7791 ;; Insert the new heading
7792 (insert stars)
7793 (just-one-space)
7794 (insert initial-content)
7795 (when adjust-empty-lines
7796 (if (or (not blank)
7797 (and blank (not (org-previous-line-empty-p))))
7798 (org-N-empty-lines-before-current (if blank 1 0))))
7799 (run-hooks 'org-insert-heading-hook)))))))
7801 (defun org-N-empty-lines-before-current (N)
7802 "Make the number of empty lines before current exactly N.
7803 So this will delete or add empty lines."
7804 (save-excursion
7805 (goto-char (point-at-bol))
7806 (if (looking-back "\\s-+" nil 'greedy)
7807 (replace-match ""))
7808 (or (bobp) (insert "\n"))
7809 (while (> N 0)
7810 (insert "\n")
7811 (setq N (1- N)))))
7813 (defun org-get-heading (&optional no-tags no-todo)
7814 "Return the heading of the current entry, without the stars.
7815 When NO-TAGS is non-nil, don't include tags.
7816 When NO-TODO is non-nil, don't include TODO keywords."
7817 (save-excursion
7818 (org-back-to-heading t)
7819 (cond
7820 ((and no-tags no-todo)
7821 (looking-at org-complex-heading-regexp)
7822 (match-string 4))
7823 (no-tags
7824 (looking-at (concat org-outline-regexp
7825 "\\(.*?\\)"
7826 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7827 (match-string 1))
7828 (no-todo
7829 (looking-at org-todo-line-regexp)
7830 (match-string 3))
7831 (t (looking-at org-heading-regexp)
7832 (match-string 2)))))
7834 (defvar orgstruct-mode) ; defined below
7836 (defun org-heading-components ()
7837 "Return the components of the current heading.
7838 This is a list with the following elements:
7839 - the level as an integer
7840 - the reduced level, different if `org-odd-levels-only' is set.
7841 - the TODO keyword, or nil
7842 - the priority character, like ?A, or nil if no priority is given
7843 - the headline text itself, or the tags string if no headline text
7844 - the tags string, or nil."
7845 (save-excursion
7846 (org-back-to-heading t)
7847 (if (let (case-fold-search)
7848 (looking-at
7849 (if orgstruct-mode
7850 org-heading-regexp
7851 org-complex-heading-regexp)))
7852 (if orgstruct-mode
7853 (list (length (match-string 1))
7854 (org-reduced-level (length (match-string 1)))
7857 (match-string 2)
7858 nil)
7859 (list (length (match-string 1))
7860 (org-reduced-level (length (match-string 1)))
7861 (org-match-string-no-properties 2)
7862 (and (match-end 3) (aref (match-string 3) 2))
7863 (org-match-string-no-properties 4)
7864 (org-match-string-no-properties 5))))))
7866 (defun org-get-entry ()
7867 "Get the entry text, after heading, entire subtree."
7868 (save-excursion
7869 (org-back-to-heading t)
7870 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7872 (defun org-insert-heading-after-current ()
7873 "Insert a new heading with same level as current, after current subtree."
7874 (interactive)
7875 (org-back-to-heading)
7876 (org-insert-heading)
7877 (org-move-subtree-down)
7878 (end-of-line 1))
7880 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7881 "Insert heading with `org-insert-heading-respect-content' set to t."
7882 (interactive "P")
7883 (let ((org-insert-heading-respect-content t))
7884 (org-insert-heading '(4) invisible-ok)))
7886 (defun org-insert-todo-heading-respect-content (&optional force-state)
7887 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7888 (interactive "P")
7889 (let ((org-insert-heading-respect-content t))
7890 (org-insert-todo-heading force-state '(4))))
7892 (defun org-insert-todo-heading (arg &optional force-heading)
7893 "Insert a new heading with the same level and TODO state as current heading.
7894 If the heading has no TODO state, or if the state is DONE, use the first
7895 state (TODO by default). Also with one prefix arg, force first state. With
7896 two prefix args, force inserting at the end of the parent subtree."
7897 (interactive "P")
7898 (when (or force-heading (not (org-insert-item 'checkbox)))
7899 (org-insert-heading (or (and (equal arg '(16)) '(16))
7900 force-heading))
7901 (save-excursion
7902 (org-back-to-heading)
7903 (outline-previous-heading)
7904 (looking-at org-todo-line-regexp))
7905 (let*
7906 ((new-mark-x
7907 (if (or (equal arg '(4))
7908 (not (match-beginning 2))
7909 (member (match-string 2) org-done-keywords))
7910 (car org-todo-keywords-1)
7911 (match-string 2)))
7912 (new-mark
7914 (run-hook-with-args-until-success
7915 'org-todo-get-default-hook new-mark-x nil)
7916 new-mark-x)))
7917 (beginning-of-line 1)
7918 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7919 (if org-treat-insert-todo-heading-as-state-change
7920 (org-todo new-mark)
7921 (insert new-mark " "))))
7922 (when org-provide-todo-statistics
7923 (org-update-parent-todo-statistics))))
7925 (defun org-insert-subheading (arg)
7926 "Insert a new subheading and demote it.
7927 Works for outline headings and for plain lists alike."
7928 (interactive "P")
7929 (org-insert-heading arg)
7930 (cond
7931 ((org-at-heading-p) (org-do-demote))
7932 ((org-at-item-p) (org-indent-item))))
7934 (defun org-insert-todo-subheading (arg)
7935 "Insert a new subheading with TODO keyword or checkbox and demote it.
7936 Works for outline headings and for plain lists alike."
7937 (interactive "P")
7938 (org-insert-todo-heading arg)
7939 (cond
7940 ((org-at-heading-p) (org-do-demote))
7941 ((org-at-item-p) (org-indent-item))))
7943 ;;; Promotion and Demotion
7945 (defvar org-after-demote-entry-hook nil
7946 "Hook run after an entry has been demoted.
7947 The cursor will be at the beginning of the entry.
7948 When a subtree is being demoted, the hook will be called for each node.")
7950 (defvar org-after-promote-entry-hook nil
7951 "Hook run after an entry has been promoted.
7952 The cursor will be at the beginning of the entry.
7953 When a subtree is being promoted, the hook will be called for each node.")
7955 (defun org-promote-subtree ()
7956 "Promote the entire subtree.
7957 See also `org-promote'."
7958 (interactive)
7959 (save-excursion
7960 (org-with-limited-levels (org-map-tree 'org-promote)))
7961 (org-fix-position-after-promote))
7963 (defun org-demote-subtree ()
7964 "Demote the entire subtree. See `org-demote'.
7965 See also `org-promote'."
7966 (interactive)
7967 (save-excursion
7968 (org-with-limited-levels (org-map-tree 'org-demote)))
7969 (org-fix-position-after-promote))
7972 (defun org-do-promote ()
7973 "Promote the current heading higher up the tree.
7974 If the region is active in `transient-mark-mode', promote all headings
7975 in the region."
7976 (interactive)
7977 (save-excursion
7978 (if (org-region-active-p)
7979 (org-map-region 'org-promote (region-beginning) (region-end))
7980 (org-promote)))
7981 (org-fix-position-after-promote))
7983 (defun org-do-demote ()
7984 "Demote the current heading lower down the tree.
7985 If the region is active in `transient-mark-mode', demote all headings
7986 in the region."
7987 (interactive)
7988 (save-excursion
7989 (if (org-region-active-p)
7990 (org-map-region 'org-demote (region-beginning) (region-end))
7991 (org-demote)))
7992 (org-fix-position-after-promote))
7994 (defun org-fix-position-after-promote ()
7995 "Make sure that after pro/demotion cursor position is right."
7996 (let ((pos (point)))
7997 (when (save-excursion
7998 (beginning-of-line 1)
7999 (looking-at org-todo-line-regexp)
8000 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8001 (cond ((eobp) (insert " "))
8002 ((eolp) (insert " "))
8003 ((equal (char-after) ?\ ) (forward-char 1))))))
8005 (defun org-current-level ()
8006 "Return the level of the current entry, or nil if before the first headline.
8007 The level is the number of stars at the beginning of the headline."
8008 (save-excursion
8009 (org-with-limited-levels
8010 (if (ignore-errors (org-back-to-heading t))
8011 (funcall outline-level)))))
8013 (defun org-get-previous-line-level ()
8014 "Return the outline depth of the last headline before the current line.
8015 Returns 0 for the first headline in the buffer, and nil if before the
8016 first headline."
8017 (and (org-current-level)
8018 (or (and (/= (line-beginning-position) (point-min))
8019 (save-excursion (beginning-of-line 0) (org-current-level)))
8020 0)))
8022 (defun org-reduced-level (l)
8023 "Compute the effective level of a heading.
8024 This takes into account the setting of `org-odd-levels-only'."
8025 (cond
8026 ((zerop l) 0)
8027 (org-odd-levels-only (1+ (floor (/ l 2))))
8028 (t l)))
8030 (defun org-level-increment ()
8031 "Return the number of stars that will be added or removed at a
8032 time to headlines when structure editing, based on the value of
8033 `org-odd-levels-only'."
8034 (if org-odd-levels-only 2 1))
8036 (defun org-get-valid-level (level &optional change)
8037 "Rectify a level change under the influence of `org-odd-levels-only'
8038 LEVEL is a current level, CHANGE is by how much the level should be
8039 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8040 even level numbers will become the next higher odd number."
8041 (if org-odd-levels-only
8042 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8043 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8044 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8045 (max 1 (+ level (or change 0)))))
8047 (if (boundp 'define-obsolete-function-alias)
8048 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8049 (define-obsolete-function-alias 'org-get-legal-level
8050 'org-get-valid-level)
8051 (define-obsolete-function-alias 'org-get-legal-level
8052 'org-get-valid-level "23.1")))
8054 (defun org-promote ()
8055 "Promote the current heading higher up the tree.
8056 If the region is active in `transient-mark-mode', promote all headings
8057 in the region."
8058 (org-back-to-heading t)
8059 (let* ((level (save-match-data (funcall outline-level)))
8060 (after-change-functions (remove 'flyspell-after-change-function
8061 after-change-functions))
8062 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8063 (diff (abs (- level (length up-head) -1))))
8064 (cond ((and (= level 1) org-called-with-limited-levels
8065 org-allow-promoting-top-level-subtree)
8066 (replace-match "# " nil t))
8067 ((= level 1)
8068 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8069 (t (replace-match up-head nil t)))
8070 ;; Fixup tag positioning
8071 (unless (= level 1)
8072 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8073 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8074 (run-hooks 'org-after-promote-entry-hook)))
8076 (defun org-demote ()
8077 "Demote the current heading lower down the tree.
8078 If the region is active in `transient-mark-mode', demote all headings
8079 in the region."
8080 (org-back-to-heading t)
8081 (let* ((level (save-match-data (funcall outline-level)))
8082 (after-change-functions (remove 'flyspell-after-change-function
8083 after-change-functions))
8084 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8085 (diff (abs (- level (length down-head) -1))))
8086 (replace-match down-head nil t)
8087 ;; Fixup tag positioning
8088 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8089 (if org-adapt-indentation (org-fixup-indentation diff))
8090 (run-hooks 'org-after-demote-entry-hook)))
8092 (defun org-cycle-level ()
8093 "Cycle the level of an empty headline through possible states.
8094 This goes first to child, then to parent, level, then up the hierarchy.
8095 After top level, it switches back to sibling level."
8096 (interactive)
8097 (let ((org-adapt-indentation nil))
8098 (when (org-point-at-end-of-empty-headline)
8099 (setq this-command 'org-cycle-level) ; Only needed for caching
8100 (let ((cur-level (org-current-level))
8101 (prev-level (org-get-previous-line-level)))
8102 (cond
8103 ;; If first headline in file, promote to top-level.
8104 ((= prev-level 0)
8105 (loop repeat (/ (- cur-level 1) (org-level-increment))
8106 do (org-do-promote)))
8107 ;; If same level as prev, demote one.
8108 ((= prev-level cur-level)
8109 (org-do-demote))
8110 ;; If parent is top-level, promote to top level if not already.
8111 ((= prev-level 1)
8112 (loop repeat (/ (- cur-level 1) (org-level-increment))
8113 do (org-do-promote)))
8114 ;; If top-level, return to prev-level.
8115 ((= cur-level 1)
8116 (loop repeat (/ (- prev-level 1) (org-level-increment))
8117 do (org-do-demote)))
8118 ;; If less than prev-level, promote one.
8119 ((< cur-level prev-level)
8120 (org-do-promote))
8121 ;; If deeper than prev-level, promote until higher than
8122 ;; prev-level.
8123 ((> cur-level prev-level)
8124 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8125 do (org-do-promote))))
8126 t))))
8128 (defun org-map-tree (fun)
8129 "Call FUN for every heading underneath the current one."
8130 (org-back-to-heading)
8131 (let ((level (funcall outline-level)))
8132 (save-excursion
8133 (funcall fun)
8134 (while (and (progn
8135 (outline-next-heading)
8136 (> (funcall outline-level) level))
8137 (not (eobp)))
8138 (funcall fun)))))
8140 (defun org-map-region (fun beg end)
8141 "Call FUN for every heading between BEG and END."
8142 (let ((org-ignore-region t))
8143 (save-excursion
8144 (setq end (copy-marker end))
8145 (goto-char beg)
8146 (if (and (re-search-forward org-outline-regexp-bol nil t)
8147 (< (point) end))
8148 (funcall fun))
8149 (while (and (progn
8150 (outline-next-heading)
8151 (< (point) end))
8152 (not (eobp)))
8153 (funcall fun)))))
8155 (defvar org-property-end-re) ; silence byte-compiler
8156 (defun org-fixup-indentation (diff)
8157 "Change the indentation in the current entry by DIFF.
8158 However, if any line in the current entry has no indentation, or if it
8159 would end up with no indentation after the change, nothing at all is done."
8160 (save-excursion
8161 (let ((end (save-excursion (outline-next-heading)
8162 (point-marker)))
8163 (prohibit (if (> diff 0)
8164 "^\\S-"
8165 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8166 col)
8167 (unless (save-excursion (end-of-line 1)
8168 (re-search-forward prohibit end t))
8169 (while (and (< (point) end)
8170 (re-search-forward "^[ \t]+" end t))
8171 (goto-char (match-end 0))
8172 (setq col (current-column))
8173 (if (< diff 0) (replace-match ""))
8174 (org-indent-to-column (+ diff col))))
8175 (move-marker end nil))))
8177 (defun org-convert-to-odd-levels ()
8178 "Convert an org-mode file with all levels allowed to one with odd levels.
8179 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8180 level 5 etc."
8181 (interactive)
8182 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8183 (let ((outline-level 'org-outline-level)
8184 (org-odd-levels-only nil) n)
8185 (save-excursion
8186 (goto-char (point-min))
8187 (while (re-search-forward "^\\*\\*+ " nil t)
8188 (setq n (- (length (match-string 0)) 2))
8189 (while (>= (setq n (1- n)) 0)
8190 (org-demote))
8191 (end-of-line 1))))))
8193 (defun org-convert-to-oddeven-levels ()
8194 "Convert an org-mode file with only odd levels to one with odd/even levels.
8195 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8196 file contains a section with an even level, conversion would
8197 destroy the structure of the file. An error is signaled in this
8198 case."
8199 (interactive)
8200 (goto-char (point-min))
8201 ;; First check if there are no even levels
8202 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8203 (org-show-context t)
8204 (error "Not all levels are odd in this file. Conversion not possible"))
8205 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8206 (let ((outline-regexp org-outline-regexp)
8207 (outline-level 'org-outline-level)
8208 (org-odd-levels-only nil) n)
8209 (save-excursion
8210 (goto-char (point-min))
8211 (while (re-search-forward "^\\*\\*+ " nil t)
8212 (setq n (/ (1- (length (match-string 0))) 2))
8213 (while (>= (setq n (1- n)) 0)
8214 (org-promote))
8215 (end-of-line 1))))))
8217 (defun org-tr-level (n)
8218 "Make N odd if required."
8219 (if org-odd-levels-only (1+ (/ n 2)) n))
8221 ;;; Vertical tree motion, cutting and pasting of subtrees
8223 (defun org-move-subtree-up (&optional arg)
8224 "Move the current subtree up past ARG headlines of the same level."
8225 (interactive "p")
8226 (org-move-subtree-down (- (prefix-numeric-value arg))))
8228 (defun org-move-subtree-down (&optional arg)
8229 "Move the current subtree down past ARG headlines of the same level."
8230 (interactive "p")
8231 (setq arg (prefix-numeric-value arg))
8232 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8233 'org-get-last-sibling))
8234 (ins-point (make-marker))
8235 (cnt (abs arg))
8236 (col (current-column))
8237 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8238 ;; Select the tree
8239 (org-back-to-heading)
8240 (setq beg0 (point))
8241 (save-excursion
8242 (setq ne-beg (org-back-over-empty-lines))
8243 (setq beg (point)))
8244 (save-match-data
8245 (save-excursion (outline-end-of-heading)
8246 (setq folded (outline-invisible-p)))
8247 (outline-end-of-subtree))
8248 (outline-next-heading)
8249 (setq ne-end (org-back-over-empty-lines))
8250 (setq end (point))
8251 (goto-char beg0)
8252 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8253 ;; include less whitespace
8254 (save-excursion
8255 (goto-char beg)
8256 (forward-line (- ne-beg ne-end))
8257 (setq beg (point))))
8258 ;; Find insertion point, with error handling
8259 (while (> cnt 0)
8260 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8261 (progn (goto-char beg0)
8262 (user-error "Cannot move past superior level or buffer limit")))
8263 (setq cnt (1- cnt)))
8264 (if (> arg 0)
8265 ;; Moving forward - still need to move over subtree
8266 (progn (org-end-of-subtree t t)
8267 (save-excursion
8268 (org-back-over-empty-lines)
8269 (or (bolp) (newline)))))
8270 (setq ne-ins (org-back-over-empty-lines))
8271 (move-marker ins-point (point))
8272 (setq txt (buffer-substring beg end))
8273 (org-save-markers-in-region beg end)
8274 (delete-region beg end)
8275 (org-remove-empty-overlays-at beg)
8276 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8277 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8278 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8279 (let ((bbb (point)))
8280 (insert-before-markers txt)
8281 (org-reinstall-markers-in-region bbb)
8282 (move-marker ins-point bbb))
8283 (or (bolp) (insert "\n"))
8284 (setq ins-end (point))
8285 (goto-char ins-point)
8286 (org-skip-whitespace)
8287 (when (and (< arg 0)
8288 (org-first-sibling-p)
8289 (> ne-ins ne-beg))
8290 ;; Move whitespace back to beginning
8291 (save-excursion
8292 (goto-char ins-end)
8293 (let ((kill-whole-line t))
8294 (kill-line (- ne-ins ne-beg)) (point)))
8295 (insert (make-string (- ne-ins ne-beg) ?\n)))
8296 (move-marker ins-point nil)
8297 (if folded
8298 (hide-subtree)
8299 (org-show-entry)
8300 (show-children)
8301 (org-cycle-hide-drawers 'children))
8302 (org-clean-visibility-after-subtree-move)
8303 ;; move back to the initial column we were at
8304 (move-to-column col)))
8306 (defvar org-subtree-clip ""
8307 "Clipboard for cut and paste of subtrees.
8308 This is actually only a copy of the kill, because we use the normal kill
8309 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8311 (defvar org-subtree-clip-folded nil
8312 "Was the last copied subtree folded?
8313 This is used to fold the tree back after pasting.")
8315 (defun org-cut-subtree (&optional n)
8316 "Cut the current subtree into the clipboard.
8317 With prefix arg N, cut this many sequential subtrees.
8318 This is a short-hand for marking the subtree and then cutting it."
8319 (interactive "p")
8320 (org-copy-subtree n 'cut))
8322 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8323 "Copy the current subtree it in the clipboard.
8324 With prefix arg N, copy this many sequential subtrees.
8325 This is a short-hand for marking the subtree and then copying it.
8326 If CUT is non-nil, actually cut the subtree.
8327 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8328 of some markers in the region, even if CUT is non-nil. This is
8329 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8330 (interactive "p")
8331 (let (beg end folded (beg0 (point)))
8332 (if (org-called-interactively-p 'any)
8333 (org-back-to-heading nil) ; take what looks like a subtree
8334 (org-back-to-heading t)) ; take what is really there
8335 (setq beg (point))
8336 (skip-chars-forward " \t\r\n")
8337 (save-match-data
8338 (if nosubtrees
8339 (outline-next-heading)
8340 (save-excursion (outline-end-of-heading)
8341 (setq folded (outline-invisible-p)))
8342 (condition-case nil
8343 (org-forward-heading-same-level (1- n) t)
8344 (error nil))
8345 (org-end-of-subtree t t)))
8346 (setq end (point))
8347 (goto-char beg0)
8348 (when (> end beg)
8349 (setq org-subtree-clip-folded folded)
8350 (when (or cut force-store-markers)
8351 (org-save-markers-in-region beg end))
8352 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8353 (setq org-subtree-clip (current-kill 0))
8354 (message "%s: Subtree(s) with %d characters"
8355 (if cut "Cut" "Copied")
8356 (length org-subtree-clip)))))
8358 (defun org-paste-subtree (&optional level tree for-yank)
8359 "Paste the clipboard as a subtree, with modification of headline level.
8360 The entire subtree is promoted or demoted in order to match a new headline
8361 level.
8363 If the cursor is at the beginning of a headline, the same level as
8364 that headline is used to paste the tree.
8366 If not, the new level is derived from the *visible* headings
8367 before and after the insertion point, and taken to be the inferior headline
8368 level of the two. So if the previous visible heading is level 3 and the
8369 next is level 4 (or vice versa), level 4 will be used for insertion.
8370 This makes sure that the subtree remains an independent subtree and does
8371 not swallow low level entries.
8373 You can also force a different level, either by using a numeric prefix
8374 argument, or by inserting the heading marker by hand. For example, if the
8375 cursor is after \"*****\", then the tree will be shifted to level 5.
8377 If optional TREE is given, use this text instead of the kill ring.
8379 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8380 move back over whitespace before inserting, and move point to the end of
8381 the inserted text when done."
8382 (interactive "P")
8383 (setq tree (or tree (and kill-ring (current-kill 0))))
8384 (unless (org-kill-is-subtree-p tree)
8385 (user-error "%s"
8386 (substitute-command-keys
8387 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8388 (org-with-limited-levels
8389 (let* ((visp (not (outline-invisible-p)))
8390 (txt tree)
8391 (^re_ "\\(\\*+\\)[ \t]*")
8392 (old-level (if (string-match org-outline-regexp-bol txt)
8393 (- (match-end 0) (match-beginning 0) 1)
8394 -1))
8395 (force-level (cond (level (prefix-numeric-value level))
8396 ((and (looking-at "[ \t]*$")
8397 (string-match
8398 "^\\*+$" (buffer-substring
8399 (point-at-bol) (point))))
8400 (- (match-end 1) (match-beginning 1)))
8401 ((and (bolp)
8402 (looking-at org-outline-regexp))
8403 (- (match-end 0) (point) 1))))
8404 (previous-level (save-excursion
8405 (condition-case nil
8406 (progn
8407 (outline-previous-visible-heading 1)
8408 (if (looking-at ^re_)
8409 (- (match-end 0) (match-beginning 0) 1)
8411 (error 1))))
8412 (next-level (save-excursion
8413 (condition-case nil
8414 (progn
8415 (or (looking-at org-outline-regexp)
8416 (outline-next-visible-heading 1))
8417 (if (looking-at ^re_)
8418 (- (match-end 0) (match-beginning 0) 1)
8420 (error 1))))
8421 (new-level (or force-level (max previous-level next-level)))
8422 (shift (if (or (= old-level -1)
8423 (= new-level -1)
8424 (= old-level new-level))
8426 (- new-level old-level)))
8427 (delta (if (> shift 0) -1 1))
8428 (func (if (> shift 0) 'org-demote 'org-promote))
8429 (org-odd-levels-only nil)
8430 beg end newend)
8431 ;; Remove the forced level indicator
8432 (if force-level
8433 (delete-region (point-at-bol) (point)))
8434 ;; Paste
8435 (beginning-of-line (if (bolp) 1 2))
8436 (setq beg (point))
8437 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8438 (insert-before-markers txt)
8439 (unless (string-match "\n\\'" txt) (insert "\n"))
8440 (setq newend (point))
8441 (org-reinstall-markers-in-region beg)
8442 (setq end (point))
8443 (goto-char beg)
8444 (skip-chars-forward " \t\n\r")
8445 (setq beg (point))
8446 (if (and (outline-invisible-p) visp)
8447 (save-excursion (outline-show-heading)))
8448 ;; Shift if necessary
8449 (unless (= shift 0)
8450 (save-restriction
8451 (narrow-to-region beg end)
8452 (while (not (= shift 0))
8453 (org-map-region func (point-min) (point-max))
8454 (setq shift (+ delta shift)))
8455 (goto-char (point-min))
8456 (setq newend (point-max))))
8457 (when (or (org-called-interactively-p 'interactive) for-yank)
8458 (message "Clipboard pasted as level %d subtree" new-level))
8459 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8460 kill-ring
8461 (eq org-subtree-clip (current-kill 0))
8462 org-subtree-clip-folded)
8463 ;; The tree was folded before it was killed/copied
8464 (hide-subtree))
8465 (and for-yank (goto-char newend)))))
8467 (defun org-kill-is-subtree-p (&optional txt)
8468 "Check if the current kill is an outline subtree, or a set of trees.
8469 Returns nil if kill does not start with a headline, or if the first
8470 headline level is not the largest headline level in the tree.
8471 So this will actually accept several entries of equal levels as well,
8472 which is OK for `org-paste-subtree'.
8473 If optional TXT is given, check this string instead of the current kill."
8474 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8475 (re (org-get-limited-outline-regexp))
8476 (^re (concat "^" re))
8477 (start-level (and kill
8478 (string-match
8479 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8480 kill)
8481 (- (match-end 2) (match-beginning 2) 1)))
8482 (start (1+ (or (match-beginning 2) -1))))
8483 (if (not start-level)
8484 (progn
8485 nil) ;; does not even start with a heading
8486 (catch 'exit
8487 (while (setq start (string-match ^re kill (1+ start)))
8488 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8489 (throw 'exit nil)))
8490 t))))
8492 (defvar org-markers-to-move nil
8493 "Markers that should be moved with a cut-and-paste operation.
8494 Those markers are stored together with their positions relative to
8495 the start of the region.")
8497 (defun org-save-markers-in-region (beg end)
8498 "Check markers in region.
8499 If these markers are between BEG and END, record their position relative
8500 to BEG, so that after moving the block of text, we can put the markers back
8501 into place.
8502 This function gets called just before an entry or tree gets cut from the
8503 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8504 called immediately, to move the markers with the entries."
8505 (setq org-markers-to-move nil)
8506 (when (featurep 'org-clock)
8507 (org-clock-save-markers-for-cut-and-paste beg end))
8508 (when (featurep 'org-agenda)
8509 (org-agenda-save-markers-for-cut-and-paste beg end)))
8511 (defun org-check-and-save-marker (marker beg end)
8512 "Check if MARKER is between BEG and END.
8513 If yes, remember the marker and the distance to BEG."
8514 (when (and (marker-buffer marker)
8515 (equal (marker-buffer marker) (current-buffer)))
8516 (if (and (>= marker beg) (< marker end))
8517 (push (cons marker (- marker beg)) org-markers-to-move))))
8519 (defun org-reinstall-markers-in-region (beg)
8520 "Move all remembered markers to their position relative to BEG."
8521 (mapc (lambda (x)
8522 (move-marker (car x) (+ beg (cdr x))))
8523 org-markers-to-move)
8524 (setq org-markers-to-move nil))
8526 (defun org-narrow-to-subtree ()
8527 "Narrow buffer to the current subtree."
8528 (interactive)
8529 (save-excursion
8530 (save-match-data
8531 (org-with-limited-levels
8532 (narrow-to-region
8533 (progn (org-back-to-heading t) (point))
8534 (progn (org-end-of-subtree t t)
8535 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8536 (point)))))))
8538 (defun org-narrow-to-block ()
8539 "Narrow buffer to the current block."
8540 (interactive)
8541 (let* ((case-fold-search t)
8542 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8543 "^[ \t]*#\\+end_.*")))
8544 (if blockp
8545 (narrow-to-region (car blockp) (cdr blockp))
8546 (user-error "Not in a block"))))
8548 (eval-when-compile
8549 (defvar org-property-drawer-re))
8551 (defvar org-property-start-re) ;; defined below
8552 (defun org-clone-subtree-with-time-shift (n &optional shift)
8553 "Clone the task (subtree) at point N times.
8554 The clones will be inserted as siblings.
8556 In interactive use, the user will be prompted for the number of
8557 clones to be produced. If the entry has a timestamp, the user
8558 will also be prompted for a time shift, which may be a repeater
8559 as used in time stamps, for example `+3d'. To disable this,
8560 you can call the function with a universal prefix argument.
8562 When a valid repeater is given and the entry contains any time
8563 stamps, the clones will become a sequence in time, with time
8564 stamps in the subtree shifted for each clone produced. If SHIFT
8565 is nil or the empty string, time stamps will be left alone. The
8566 ID property of the original subtree is removed.
8568 If the original subtree did contain time stamps with a repeater,
8569 the following will happen:
8570 - the repeater will be removed in each clone
8571 - an additional clone will be produced, with the current, unshifted
8572 date(s) in the entry.
8573 - the original entry will be placed *after* all the clones, with
8574 repeater intact.
8575 - the start days in the repeater in the original entry will be shifted
8576 to past the last clone.
8577 In this way you can spell out a number of instances of a repeating task,
8578 and still retain the repeater to cover future instances of the task."
8579 (interactive "nNumber of clones to produce: ")
8580 (let ((shift
8581 (or shift
8582 (if (and (not (equal current-prefix-arg '(4)))
8583 (save-excursion
8584 (re-search-forward org-ts-regexp-both
8585 (save-excursion
8586 (org-end-of-subtree t)
8587 (point)) t)))
8588 (read-from-minibuffer
8589 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8590 ""))) ;; No time shift
8591 (n-no-remove -1)
8592 (drawer-re org-drawer-regexp)
8593 beg end template task idprop
8594 shift-n shift-what doshift nmin nmax)
8595 (if (not (and (integerp n) (> n 0)))
8596 (user-error "Invalid number of replications %s" n))
8597 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8598 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8599 shift)))
8600 (user-error "Invalid shift specification %s" shift))
8601 (when doshift
8602 (setq shift-n (string-to-number (match-string 1 shift))
8603 shift-what (cdr (assoc (match-string 2 shift)
8604 '(("d" . day) ("w" . week)
8605 ("m" . month) ("y" . year))))))
8606 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8607 (setq nmin 1 nmax n)
8608 (org-back-to-heading t)
8609 (setq beg (point))
8610 (setq idprop (org-entry-get nil "ID"))
8611 (org-end-of-subtree t t)
8612 (or (bolp) (insert "\n"))
8613 (setq end (point))
8614 (setq template (buffer-substring beg end))
8615 (when (and doshift
8616 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8617 (delete-region beg end)
8618 (setq end beg)
8619 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8620 (goto-char end)
8621 (loop for n from nmin to nmax do
8622 ;; prepare clone
8623 (with-temp-buffer
8624 (insert template)
8625 (org-mode)
8626 (goto-char (point-min))
8627 (org-show-subtree)
8628 (and idprop (if org-clone-delete-id
8629 (org-entry-delete nil "ID")
8630 (org-id-get-create t)))
8631 (unless (= n 0)
8632 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8633 (kill-whole-line))
8634 (goto-char (point-min))
8635 (while (re-search-forward drawer-re nil t)
8636 (org-remove-empty-drawer-at (point))))
8637 (goto-char (point-min))
8638 (when doshift
8639 (while (re-search-forward org-ts-regexp-both nil t)
8640 (org-timestamp-change (* n shift-n) shift-what))
8641 (unless (= n n-no-remove)
8642 (goto-char (point-min))
8643 (while (re-search-forward org-ts-regexp nil t)
8644 (save-excursion
8645 (goto-char (match-beginning 0))
8646 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8647 (delete-region (match-beginning 1) (match-end 1)))))))
8648 (setq task (buffer-string)))
8649 (insert task))
8650 (goto-char beg)))
8652 ;;; Outline Sorting
8654 (defun org-sort (with-case)
8655 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8656 Optional argument WITH-CASE means sort case-sensitively."
8657 (interactive "P")
8658 (cond
8659 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8660 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8662 (org-call-with-arg 'org-sort-entries with-case))))
8664 (defun org-sort-remove-invisible (s)
8665 "Remove invisible links from string S."
8666 (remove-text-properties 0 (length s) org-rm-props s)
8667 (while (string-match org-bracket-link-regexp s)
8668 (setq s (replace-match (if (match-end 2)
8669 (match-string 3 s)
8670 (match-string 1 s)) t t s)))
8671 (let ((st (format " %s " s)))
8672 (while (string-match org-emph-re st)
8673 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8674 (setq s (substring st 1 -1)))
8677 (defvar org-priority-regexp) ; defined later in the file
8679 (defvar org-after-sorting-entries-or-items-hook nil
8680 "Hook that is run after a bunch of entries or items have been sorted.
8681 When children are sorted, the cursor is in the parent line when this
8682 hook gets called. When a region or a plain list is sorted, the cursor
8683 will be in the first entry of the sorted region/list.")
8685 (defun org-sort-entries
8686 (&optional with-case sorting-type getkey-func compare-func property)
8687 "Sort entries on a certain level of an outline tree.
8688 If there is an active region, the entries in the region are sorted.
8689 Else, if the cursor is before the first entry, sort the top-level items.
8690 Else, the children of the entry at point are sorted.
8692 Sorting can be alphabetically, numerically, by date/time as given by
8693 a time stamp, by a property, by priority order, or by a custom function.
8695 The command prompts for the sorting type unless it has been given to the
8696 function through the SORTING-TYPE argument, which needs to be a character,
8697 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8698 the precise meaning of each character:
8700 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8701 c By creation time, which is assumed to be the first inactive time stamp
8702 at the beginning of a line.
8703 d By deadline date/time.
8704 k By clocking time.
8705 n Numerically, by converting the beginning of the entry/item to a number.
8706 o By order of TODO keywords.
8707 p By priority according to the cookie.
8708 r By the value of a property.
8709 s By scheduled date/time.
8710 t By date/time, either the first active time stamp in the entry, or, if
8711 none exist, by the first inactive one.
8713 Capital letters will reverse the sort order.
8715 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8716 called with point at the beginning of the record. It must return either
8717 a string or a number that should serve as the sorting key for that record.
8719 Comparing entries ignores case by default. However, with an optional argument
8720 WITH-CASE, the sorting considers case as well.
8722 Sorting is done against the visible part of the headlines, it ignores hidden
8723 links.
8725 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8726 (interactive "P")
8727 (let ((case-func (if with-case 'identity 'downcase))
8728 (cmstr
8729 ;; The clock marker is lost when using `sort-subr', let's
8730 ;; store the clocking string.
8731 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8732 (save-excursion
8733 (goto-char org-clock-marker)
8734 (looking-back "^.*") (match-string-no-properties 0))))
8735 start beg end stars re re2
8736 txt what tmp)
8737 ;; Find beginning and end of region to sort
8738 (cond
8739 ((org-region-active-p)
8740 ;; we will sort the region
8741 (setq end (region-end)
8742 what "region")
8743 (goto-char (region-beginning))
8744 (if (not (org-at-heading-p)) (outline-next-heading))
8745 (setq start (point)))
8746 ((or (org-at-heading-p)
8747 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8748 ;; we will sort the children of the current headline
8749 (org-back-to-heading)
8750 (setq start (point)
8751 end (progn (org-end-of-subtree t t)
8752 (or (bolp) (insert "\n"))
8753 (when (>= (org-back-over-empty-lines) 1)
8754 (forward-line 1))
8755 (point))
8756 what "children")
8757 (goto-char start)
8758 (show-subtree)
8759 (outline-next-heading))
8761 ;; we will sort the top-level entries in this file
8762 (goto-char (point-min))
8763 (or (org-at-heading-p) (outline-next-heading))
8764 (setq start (point))
8765 (goto-char (point-max))
8766 (beginning-of-line 1)
8767 (when (looking-at ".*?\\S-")
8768 ;; File ends in a non-white line
8769 (end-of-line 1)
8770 (insert "\n"))
8771 (setq end (point-max))
8772 (setq what "top-level")
8773 (goto-char start)
8774 (show-all)))
8776 (setq beg (point))
8777 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8779 (looking-at "\\(\\*+\\)")
8780 (setq stars (match-string 1)
8781 re (concat "^" (regexp-quote stars) " +")
8782 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8783 txt (buffer-substring beg end))
8784 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8785 (if (and (not (equal stars "*")) (string-match re2 txt))
8786 (user-error "Region to sort contains a level above the first entry"))
8788 (unless sorting-type
8789 (message
8790 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8791 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8792 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8793 what)
8794 (setq sorting-type (read-char-exclusive))
8796 (unless getkey-func
8797 (and (= (downcase sorting-type) ?f)
8798 (setq getkey-func
8799 (org-icompleting-read "Sort using function: "
8800 obarray 'fboundp t nil nil))
8801 (setq getkey-func (intern getkey-func))))
8803 (and (= (downcase sorting-type) ?r)
8804 (not property)
8805 (setq property
8806 (org-icompleting-read "Property: "
8807 (mapcar 'list (org-buffer-property-keys t))
8808 nil t))))
8810 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8811 (message "Sorting entries...")
8813 (save-restriction
8814 (narrow-to-region start end)
8815 (let ((dcst (downcase sorting-type))
8816 (case-fold-search nil)
8817 (now (current-time)))
8818 (sort-subr
8819 (/= dcst sorting-type)
8820 ;; This function moves to the beginning character of the "record" to
8821 ;; be sorted.
8822 (lambda nil
8823 (if (re-search-forward re nil t)
8824 (goto-char (match-beginning 0))
8825 (goto-char (point-max))))
8826 ;; This function moves to the last character of the "record" being
8827 ;; sorted.
8828 (lambda nil
8829 (save-match-data
8830 (condition-case nil
8831 (outline-forward-same-level 1)
8832 (error
8833 (goto-char (point-max))))))
8834 ;; This function returns the value that gets sorted against.
8835 (lambda nil
8836 (cond
8837 ((= dcst ?n)
8838 (if (looking-at org-complex-heading-regexp)
8839 (string-to-number (org-sort-remove-invisible (match-string 4)))
8840 nil))
8841 ((= dcst ?a)
8842 (if (looking-at org-complex-heading-regexp)
8843 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8844 nil))
8845 ((= dcst ?k)
8846 (or (get-text-property (point) :org-clock-minutes) 0))
8847 ((= dcst ?t)
8848 (let ((end (save-excursion (outline-next-heading) (point))))
8849 (if (or (re-search-forward org-ts-regexp end t)
8850 (re-search-forward org-ts-regexp-both end t))
8851 (org-time-string-to-seconds (match-string 0))
8852 (org-float-time now))))
8853 ((= dcst ?c)
8854 (let ((end (save-excursion (outline-next-heading) (point))))
8855 (if (re-search-forward
8856 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8857 end t)
8858 (org-time-string-to-seconds (match-string 0))
8859 (org-float-time now))))
8860 ((= dcst ?s)
8861 (let ((end (save-excursion (outline-next-heading) (point))))
8862 (if (re-search-forward org-scheduled-time-regexp end t)
8863 (org-time-string-to-seconds (match-string 1))
8864 (org-float-time now))))
8865 ((= dcst ?d)
8866 (let ((end (save-excursion (outline-next-heading) (point))))
8867 (if (re-search-forward org-deadline-time-regexp end t)
8868 (org-time-string-to-seconds (match-string 1))
8869 (org-float-time now))))
8870 ((= dcst ?p)
8871 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8872 (string-to-char (match-string 2))
8873 org-default-priority))
8874 ((= dcst ?r)
8875 (or (org-entry-get nil property) ""))
8876 ((= dcst ?o)
8877 (if (looking-at org-complex-heading-regexp)
8878 (- 9999 (length (member (match-string 2)
8879 org-todo-keywords-1)))))
8880 ((= dcst ?f)
8881 (if getkey-func
8882 (progn
8883 (setq tmp (funcall getkey-func))
8884 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8885 tmp)
8886 (error "Invalid key function `%s'" getkey-func)))
8887 (t (error "Invalid sorting type `%c'" sorting-type))))
8889 (cond
8890 ((= dcst ?a) 'string<)
8891 ((= dcst ?f) compare-func)
8892 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8893 (run-hooks 'org-after-sorting-entries-or-items-hook)
8894 ;; Reset the clock marker if needed
8895 (when cmstr
8896 (save-excursion
8897 (goto-char start)
8898 (search-forward cmstr nil t)
8899 (move-marker org-clock-marker (point))))
8900 (message "Sorting entries...done")))
8902 (defun org-do-sort (table what &optional with-case sorting-type)
8903 "Sort TABLE of WHAT according to SORTING-TYPE.
8904 The user will be prompted for the SORTING-TYPE if the call to this
8905 function does not specify it.
8906 WHAT is only for the prompt, to indicate what is being sorted.
8907 The sorting key will be extracted from the car of the elements of
8908 the table.
8909 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8910 (unless sorting-type
8911 (message
8912 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8913 what)
8914 (setq sorting-type (read-char-exclusive)))
8915 (let ((dcst (downcase sorting-type))
8916 extractfun comparefun)
8917 ;; Define the appropriate functions
8918 (cond
8919 ((= dcst ?n)
8920 (setq extractfun 'string-to-number
8921 comparefun (if (= dcst sorting-type) '< '>)))
8922 ((= dcst ?a)
8923 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8924 (lambda(x) (downcase (org-sort-remove-invisible x))))
8925 comparefun (if (= dcst sorting-type)
8926 'string<
8927 (lambda (a b) (and (not (string< a b))
8928 (not (string= a b)))))))
8929 ((= dcst ?t)
8930 (setq extractfun
8931 (lambda (x)
8932 (cond ((or (string-match org-ts-regexp x)
8933 (string-match org-ts-regexp-both x))
8934 (org-float-time
8935 (org-time-string-to-time (match-string 0 x))))
8936 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
8937 (org-hh:mm-string-to-minutes x))
8938 (t 0)))
8939 comparefun (if (= dcst sorting-type) '< '>)))
8940 (t (error "Invalid sorting type `%c'" sorting-type)))
8942 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8943 table)
8944 (lambda (a b) (funcall comparefun (car a) (car b))))))
8947 ;;; The orgstruct minor mode
8949 ;; Define a minor mode which can be used in other modes in order to
8950 ;; integrate the org-mode structure editing commands.
8952 ;; This is really a hack, because the org-mode structure commands use
8953 ;; keys which normally belong to the major mode. Here is how it
8954 ;; works: The minor mode defines all the keys necessary to operate the
8955 ;; structure commands, but wraps the commands into a function which
8956 ;; tests if the cursor is currently at a headline or a plain list
8957 ;; item. If that is the case, the structure command is used,
8958 ;; temporarily setting many Org-mode variables like regular
8959 ;; expressions for filling etc. However, when any of those keys is
8960 ;; used at a different location, function uses `key-binding' to look
8961 ;; up if the key has an associated command in another currently active
8962 ;; keymap (minor modes, major mode, global), and executes that
8963 ;; command. There might be problems if any of the keys is otherwise
8964 ;; used as a prefix key.
8966 (defcustom orgstruct-heading-prefix-regexp ""
8967 "Regexp that matches the custom prefix of Org headlines in
8968 orgstruct(++)-mode."
8969 :group 'org
8970 :version "24.4"
8971 :package-version '(Org . "8.3")
8972 :type 'regexp)
8973 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8975 (defcustom orgstruct-setup-hook nil
8976 "Hook run after orgstruct-mode-map is filled."
8977 :group 'org
8978 :version "24.4"
8979 :package-version '(Org . "8.0")
8980 :type 'hook)
8982 (defvar orgstruct-initialized nil)
8984 (defvar org-local-vars nil
8985 "List of local variables, for use by `orgstruct-mode'.")
8987 ;;;###autoload
8988 (define-minor-mode orgstruct-mode
8989 "Toggle the minor mode `orgstruct-mode'.
8990 This mode is for using Org-mode structure commands in other
8991 modes. The following keys behave as if Org-mode were active, if
8992 the cursor is on a headline, or on a plain list item (both as
8993 defined by Org-mode)."
8994 nil " OrgStruct" (make-sparse-keymap)
8995 (funcall (if orgstruct-mode
8996 'add-to-invisibility-spec
8997 'remove-from-invisibility-spec)
8998 '(outline . t))
8999 (when orgstruct-mode
9000 (org-load-modules-maybe)
9001 (unless orgstruct-initialized
9002 (orgstruct-setup)
9003 (setq orgstruct-initialized t))))
9005 ;;;###autoload
9006 (defun turn-on-orgstruct ()
9007 "Unconditionally turn on `orgstruct-mode'."
9008 (orgstruct-mode 1))
9010 (defvar org-fb-vars nil)
9011 (make-variable-buffer-local 'org-fb-vars)
9012 (defun orgstruct++-mode (&optional arg)
9013 "Toggle `orgstruct-mode', the enhanced version of it.
9014 In addition to setting orgstruct-mode, this also exports all
9015 indentation and autofilling variables from org-mode into the
9016 buffer. It will also recognize item context in multiline items."
9017 (interactive "P")
9018 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9019 (if (< arg 1)
9020 (progn (orgstruct-mode -1)
9021 (mapc (lambda(v)
9022 (org-set-local (car v)
9023 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9024 org-fb-vars))
9025 (orgstruct-mode 1)
9026 (setq org-fb-vars nil)
9027 (unless org-local-vars
9028 (setq org-local-vars (org-get-local-variables)))
9029 (let (var val)
9030 (mapc
9031 (lambda (x)
9032 (when (string-match
9033 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9034 (symbol-name (car x)))
9035 (setq var (car x) val (nth 1 x))
9036 (push (list var `(quote ,(eval var))) org-fb-vars)
9037 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9038 org-local-vars)
9039 (org-set-local 'orgstruct-is-++ t))))
9041 (defvar orgstruct-is-++ nil
9042 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9043 (make-variable-buffer-local 'orgstruct-is-++)
9045 ;;;###autoload
9046 (defun turn-on-orgstruct++ ()
9047 "Unconditionally turn on `orgstruct++-mode'."
9048 (orgstruct++-mode 1))
9050 (defun orgstruct-error ()
9051 "Error when there is no default binding for a structure key."
9052 (interactive)
9053 (funcall (if (fboundp 'user-error)
9054 'user-error
9055 'error)
9056 "This key has no function outside structure elements"))
9058 (defun orgstruct-setup ()
9059 "Setup orgstruct keymap."
9060 (dolist (cell '((org-demote . t)
9061 (org-metaleft . t)
9062 (org-metaright . t)
9063 (org-promote . t)
9064 (org-shiftmetaleft . t)
9065 (org-shiftmetaright . t)
9066 org-backward-element
9067 org-backward-heading-same-level
9068 org-ctrl-c-ret
9069 org-ctrl-c-minus
9070 org-ctrl-c-star
9071 org-cycle
9072 org-forward-heading-same-level
9073 org-insert-heading
9074 org-insert-heading-respect-content
9075 org-kill-note-or-show-branches
9076 org-mark-subtree
9077 org-meta-return
9078 org-metadown
9079 org-metaup
9080 org-narrow-to-subtree
9081 org-promote-subtree
9082 org-reveal
9083 org-shiftdown
9084 org-shiftleft
9085 org-shiftmetadown
9086 org-shiftmetaup
9087 org-shiftright
9088 org-shifttab
9089 org-shifttab
9090 org-shiftup
9091 org-show-subtree
9092 org-sort
9093 org-up-element
9094 outline-demote
9095 outline-next-visible-heading
9096 outline-previous-visible-heading
9097 outline-promote
9098 outline-up-heading
9099 show-children))
9100 (let ((f (or (car-safe cell) cell))
9101 (disable-when-heading-prefix (cdr-safe cell)))
9102 (when (fboundp f)
9103 (let ((new-bindings))
9104 (dolist (binding (nconc (where-is-internal f org-mode-map)
9105 (where-is-internal f outline-mode-map)))
9106 (push binding new-bindings)
9107 ;; TODO use local-function-key-map
9108 (dolist (rep '(("<tab>" . "TAB")
9109 ("<return>" . "RET")
9110 ("<escape>" . "ESC")
9111 ("<delete>" . "DEL")))
9112 (setq binding (read-kbd-macro
9113 (let ((case-fold-search))
9114 (replace-regexp-in-string
9115 (regexp-quote (cdr rep))
9116 (car rep)
9117 (key-description binding)))))
9118 (pushnew binding new-bindings :test 'equal)))
9119 (dolist (binding new-bindings)
9120 (let ((key (lookup-key orgstruct-mode-map binding)))
9121 (when (or (not key) (numberp key))
9122 (condition-case nil
9123 (org-defkey orgstruct-mode-map
9124 binding
9125 (orgstruct-make-binding f binding disable-when-heading-prefix))
9126 (error nil)))))))))
9127 (run-hooks 'orgstruct-setup-hook))
9129 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9130 "Create a function for binding in the structure minor mode.
9131 FUN is the command to call inside a table. KEY is the key that
9132 should be checked in for a command to execute outside of tables.
9133 Non-nil `disable-when-heading-prefix' means to disable the command
9134 if `orgstruct-heading-prefix-regexp' is not empty."
9135 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9136 (let ((nname name)
9137 (i 0))
9138 (while (fboundp (intern nname))
9139 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9140 (setq name (intern nname)))
9141 (eval
9142 (let ((bindings '((org-heading-regexp
9143 (concat "^"
9144 orgstruct-heading-prefix-regexp
9145 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9146 (org-outline-regexp
9147 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9148 (org-outline-regexp-bol
9149 (concat "^" org-outline-regexp))
9150 (outline-regexp org-outline-regexp)
9151 (outline-heading-end-regexp "\n")
9152 (outline-level 'org-outline-level)
9153 (outline-heading-alist))))
9154 `(defun ,name (arg)
9155 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9156 "Outside of structure, run the binding of `"
9157 (key-description key) "'."
9158 (when disable-when-heading-prefix
9159 (concat
9160 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9161 "back to the default binding due to limitations of Org's implementation of\n"
9162 "`" (symbol-name fun) "'.")))
9163 (interactive "p")
9164 (let* ((disable
9165 ,(and disable-when-heading-prefix
9166 '(not (string= orgstruct-heading-prefix-regexp ""))))
9167 (fallback
9168 (or disable
9169 (not
9170 (let* ,bindings
9171 (org-context-p 'headline 'item
9172 ,(when (memq fun
9173 '(org-insert-heading
9174 org-insert-heading-respect-content
9175 org-meta-return))
9176 '(when orgstruct-is-++
9177 'item-body))))))))
9178 (if fallback
9179 (let* ((orgstruct-mode)
9180 (binding
9181 (loop with key = ,key
9182 for rep in
9183 '(nil
9184 ("<\\([^>]*\\)tab>" . "\\1TAB")
9185 ("<\\([^>]*\\)return>" . "\\1RET")
9186 ("<\\([^>]*\\)escape>" . "\\1ESC")
9187 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9189 (when rep
9190 (setq key (read-kbd-macro
9191 (let ((case-fold-search))
9192 (replace-regexp-in-string
9193 (car rep)
9194 (cdr rep)
9195 (key-description key))))))
9196 thereis (key-binding key))))
9197 (if (keymapp binding)
9198 (org-set-transient-map binding)
9199 (let ((func (or binding
9200 (unless disable
9201 'orgstruct-error))))
9202 (when func
9203 (call-interactively func)))))
9204 (org-run-like-in-org-mode
9205 (lambda ()
9206 (interactive)
9207 (let* ,bindings
9208 (call-interactively ',fun)))))))))
9209 name))
9211 (defun org-contextualize-keys (alist contexts)
9212 "Return valid elements in ALIST depending on CONTEXTS.
9214 `org-agenda-custom-commands' or `org-capture-templates' are the
9215 values used for ALIST, and `org-agenda-custom-commands-contexts'
9216 or `org-capture-templates-contexts' are the associated contexts
9217 definitions."
9218 (let ((contexts
9219 ;; normalize contexts
9220 (mapcar
9221 (lambda(c) (cond ((listp (cadr c))
9222 (list (car c) (car c) (cadr c)))
9223 ((string= "" (cadr c))
9224 (list (car c) (car c) (caddr c)))
9225 (t c))) contexts))
9226 (a alist) c r s)
9227 ;; loop over all commands or templates
9228 (while (setq c (pop a))
9229 (let (vrules repl)
9230 (cond
9231 ((not (assoc (car c) contexts))
9232 (push c r))
9233 ((and (assoc (car c) contexts)
9234 (setq vrules (org-contextualize-validate-key
9235 (car c) contexts)))
9236 (mapc (lambda (vr)
9237 (when (not (equal (car vr) (cadr vr)))
9238 (setq repl vr))) vrules)
9239 (if (not repl) (push c r)
9240 (push (cadr repl) s)
9241 (push
9242 (cons (car c)
9243 (cdr (or (assoc (cadr repl) alist)
9244 (error "Undefined key `%s' as contextual replacement for `%s'"
9245 (cadr repl) (car c)))))
9246 r))))))
9247 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9248 (delq
9250 (delete-dups
9251 (mapcar (lambda (x)
9252 (let ((tpl (car x)))
9253 (when (not (delq
9255 (mapcar (lambda(y)
9256 (equal y tpl)) s))) x)))
9257 (reverse r))))))
9259 (defun org-contextualize-validate-key (key contexts)
9260 "Check CONTEXTS for agenda or capture KEY."
9261 (let (r rr res)
9262 (while (setq r (pop contexts))
9263 (mapc
9264 (lambda (rr)
9265 (when
9266 (and (equal key (car r))
9267 (if (functionp rr) (funcall rr)
9268 (or (and (eq (car rr) 'in-file)
9269 (buffer-file-name)
9270 (string-match (cdr rr) (buffer-file-name)))
9271 (and (eq (car rr) 'in-mode)
9272 (string-match (cdr rr) (symbol-name major-mode)))
9273 (and (eq (car rr) 'in-buffer)
9274 (string-match (cdr rr) (buffer-name)))
9275 (when (and (eq (car rr) 'not-in-file)
9276 (buffer-file-name))
9277 (not (string-match (cdr rr) (buffer-file-name))))
9278 (when (eq (car rr) 'not-in-mode)
9279 (not (string-match (cdr rr) (symbol-name major-mode))))
9280 (when (eq (car rr) 'not-in-buffer)
9281 (not (string-match (cdr rr) (buffer-name)))))))
9282 (push r res)))
9283 (car (last r))))
9284 (delete-dups (delq nil res))))
9286 (defun org-context-p (&rest contexts)
9287 "Check if local context is any of CONTEXTS.
9288 Possible values in the list of contexts are `table', `headline', and `item'."
9289 (let ((pos (point)))
9290 (goto-char (point-at-bol))
9291 (prog1 (or (and (memq 'table contexts)
9292 (looking-at "[ \t]*|"))
9293 (and (memq 'headline contexts)
9294 (looking-at org-outline-regexp))
9295 (and (memq 'item contexts)
9296 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9297 (and (memq 'item-body contexts)
9298 (org-in-item-p)))
9299 (goto-char pos))))
9301 (defun org-get-local-variables ()
9302 "Return a list of all local variables in an Org mode buffer."
9303 (let (varlist)
9304 (with-current-buffer (get-buffer-create "*Org tmp*")
9305 (erase-buffer)
9306 (org-mode)
9307 (setq varlist (buffer-local-variables)))
9308 (kill-buffer "*Org tmp*")
9309 (delq nil
9310 (mapcar
9311 (lambda (x)
9312 (setq x
9313 (if (symbolp x)
9314 (list x)
9315 (list (car x) (cdr x))))
9316 (if (and (not (get (car x) 'org-state))
9317 (string-match
9318 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9319 (symbol-name (car x))))
9320 x nil))
9321 varlist))))
9323 (defun org-clone-local-variables (from-buffer &optional regexp)
9324 "Clone local variables from FROM-BUFFER.
9325 Optional argument REGEXP selects variables to clone."
9326 (mapc
9327 (lambda (pair)
9328 (and (symbolp (car pair))
9329 (or (null regexp)
9330 (string-match regexp (symbol-name (car pair))))
9331 (set (make-local-variable (car pair))
9332 (cdr pair))))
9333 (buffer-local-variables from-buffer)))
9335 ;;;###autoload
9336 (defun org-run-like-in-org-mode (cmd)
9337 "Run a command, pretending that the current buffer is in Org-mode.
9338 This will temporarily bind local variables that are typically bound in
9339 Org-mode to the values they have in Org-mode, and then interactively
9340 call CMD."
9341 (org-load-modules-maybe)
9342 (unless org-local-vars
9343 (setq org-local-vars (org-get-local-variables)))
9344 (let (binds)
9345 (dolist (var org-local-vars)
9346 (when (or (not (boundp (car var)))
9347 (eq (symbol-value (car var))
9348 (default-value (car var))))
9349 (push (list (car var) `(quote ,(cadr var))) binds)))
9350 (eval `(let ,binds
9351 (call-interactively (quote ,cmd))))))
9353 ;;;; Archiving
9355 (defun org-get-category (&optional pos force-refresh)
9356 "Get the category applying to position POS."
9357 (save-match-data
9358 (if force-refresh (org-refresh-category-properties))
9359 (let ((pos (or pos (point))))
9360 (or (get-text-property pos 'org-category)
9361 (progn (org-refresh-category-properties)
9362 (get-text-property pos 'org-category))))))
9364 (defun org-refresh-category-properties ()
9365 "Refresh category text properties in the buffer."
9366 (let ((case-fold-search t)
9367 (inhibit-read-only t)
9368 (def-cat (cond
9369 ((null org-category)
9370 (if buffer-file-name
9371 (file-name-sans-extension
9372 (file-name-nondirectory buffer-file-name))
9373 "???"))
9374 ((symbolp org-category) (symbol-name org-category))
9375 (t org-category)))
9376 beg end cat pos optionp)
9377 (org-with-silent-modifications
9378 (save-excursion
9379 (save-restriction
9380 (widen)
9381 (goto-char (point-min))
9382 (put-text-property (point) (point-max) 'org-category def-cat)
9383 (while (re-search-forward
9384 "^[ \t]*\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9385 (setq pos (match-end 0)
9386 optionp (equal (char-after (match-beginning 0)) ?#)
9387 cat (org-trim (match-string 2)))
9388 (if optionp
9389 (setq beg (point-at-bol) end (point-max))
9390 (org-back-to-heading t)
9391 (setq beg (point) end (org-end-of-subtree t t)))
9392 (put-text-property beg end 'org-category cat)
9393 (put-text-property beg end 'org-category-position beg)
9394 (goto-char pos)))))))
9396 (defun org-refresh-properties (dprop tprop)
9397 "Refresh buffer text properties.
9398 DPROP is the drawer property and TPROP is the corresponding text
9399 property to set."
9400 (let ((case-fold-search t)
9401 (inhibit-read-only t) p)
9402 (org-with-silent-modifications
9403 (save-excursion
9404 (save-restriction
9405 (widen)
9406 (goto-char (point-min))
9407 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9408 (setq p (org-match-string-no-properties 1))
9409 (save-excursion
9410 (org-back-to-heading t)
9411 (put-text-property
9412 (point-at-bol) (or (outline-next-heading) (point-max)) tprop p))))))))
9415 ;;;; Link Stuff
9417 ;;; Link abbreviations
9419 (defun org-link-expand-abbrev (link)
9420 "Apply replacements as defined in `org-link-abbrev-alist'."
9421 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9422 (let* ((key (match-string 1 link))
9423 (as (or (assoc key org-link-abbrev-alist-local)
9424 (assoc key org-link-abbrev-alist)))
9425 (tag (and (match-end 2) (match-string 3 link)))
9426 rpl)
9427 (if (not as)
9428 link
9429 (setq rpl (cdr as))
9430 (cond
9431 ((symbolp rpl) (funcall rpl tag))
9432 ((string-match "%(\\([^)]+\\))" rpl)
9433 (replace-match
9434 (save-match-data
9435 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9436 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9437 ((string-match "%h" rpl)
9438 (replace-match (url-hexify-string (or tag "")) t t rpl))
9439 (t (concat rpl tag)))))
9440 link))
9442 ;;; Storing and inserting links
9444 (defvar org-insert-link-history nil
9445 "Minibuffer history for links inserted with `org-insert-link'.")
9447 (defvar org-stored-links nil
9448 "Contains the links stored with `org-store-link'.")
9450 (defvar org-store-link-plist nil
9451 "Plist with info about the most recently link created with `org-store-link'.")
9453 (defvar org-link-protocols nil
9454 "Link protocols added to Org-mode using `org-add-link-type'.")
9456 (defvar org-store-link-functions nil
9457 "List of functions that are called to create and store a link.
9458 Each function will be called in turn until one returns a non-nil
9459 value. Each function should check if it is responsible for creating
9460 this link (for example by looking at the major mode).
9461 If not, it must exit and return nil.
9462 If yes, it should return a non-nil value after a calling
9463 `org-store-link-props' with a list of properties and values.
9464 Special properties are:
9466 :type The link prefix, like \"http\". This must be given.
9467 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9468 This is obligatory as well.
9469 :description Optional default description for the second pair
9470 of brackets in an Org-mode link. The user can still change
9471 this when inserting this link into an Org-mode buffer.
9473 In addition to these, any additional properties can be specified
9474 and then used in capture templates.")
9476 (defun org-add-link-type (type &optional follow export)
9477 "Add TYPE to the list of `org-link-types'.
9478 Re-compute all regular expressions depending on `org-link-types'
9480 FOLLOW and EXPORT are two functions.
9482 FOLLOW should take the link path as the single argument and do whatever
9483 is necessary to follow the link, for example find a file or display
9484 a mail message.
9486 EXPORT should format the link path for export to one of the export formats.
9487 It should be a function accepting three arguments:
9489 path the path of the link, the text after the prefix (like \"http:\")
9490 desc the description of the link, if any, or a description added by
9491 org-export-normalize-links if there is none
9492 format the export format, a symbol like `html' or `latex' or `ascii'..
9494 The function may use the FORMAT information to return different values
9495 depending on the format. The return value will be put literally into
9496 the exported file. If the return value is nil, this means Org should
9497 do what it normally does with links which do not have EXPORT defined.
9499 Org-mode has a built-in default for exporting links. If you are happy with
9500 this default, there is no need to define an export function for the link
9501 type. For a simple example of an export function, see `org-bbdb.el'."
9502 (add-to-list 'org-link-types type t)
9503 (org-make-link-regexps)
9504 (if (assoc type org-link-protocols)
9505 (setcdr (assoc type org-link-protocols) (list follow export))
9506 (push (list type follow export) org-link-protocols)))
9508 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9509 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9511 ;;;###autoload
9512 (defun org-store-link (arg)
9513 "\\<org-mode-map>Store an org-link to the current location.
9514 This link is added to `org-stored-links' and can later be inserted
9515 into an org-buffer with \\[org-insert-link].
9517 For some link types, a prefix arg is interpreted.
9518 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9519 For file links, arg negates `org-context-in-file-links'.
9521 A double prefix arg force skipping storing functions that are not
9522 part of Org's core.
9524 A triple prefix arg force storing a link for each line in the
9525 active region."
9526 (interactive "P")
9527 (org-load-modules-maybe)
9528 (if (and (equal arg '(64)) (org-region-active-p))
9529 (save-excursion
9530 (let ((end (region-end)))
9531 (goto-char (region-beginning))
9532 (set-mark (point))
9533 (while (< (point-at-eol) end)
9534 (move-end-of-line 1) (activate-mark)
9535 (let (current-prefix-arg)
9536 (call-interactively 'org-store-link))
9537 (move-beginning-of-line 2)
9538 (set-mark (point)))))
9539 (org-with-limited-levels
9540 (setq org-store-link-plist nil)
9541 (let (link cpltxt desc description search
9542 txt custom-id agenda-link sfuns sfunsn)
9543 (cond
9545 ;; Store a link using an external link type
9546 ((and (not (equal arg '(16)))
9547 (setq sfuns
9548 (delq
9549 nil (mapcar (lambda (f)
9550 (let (fs) (if (funcall f) (push f fs))))
9551 org-store-link-functions))
9552 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9553 (or (and (cdr sfuns)
9554 (funcall (intern
9555 (completing-read
9556 "Which function for creating the link? "
9557 sfunsn nil t (car sfunsn)))))
9558 (funcall (caar sfuns)))
9559 (setq link (plist-get org-store-link-plist :link)
9560 desc (or (plist-get org-store-link-plist
9561 :description) link))))
9563 ;; Store a link from a source code buffer
9564 ((org-src-edit-buffer-p)
9565 (let (label gc)
9566 (while (or (not label)
9567 (save-excursion
9568 (save-restriction
9569 (widen)
9570 (goto-char (point-min))
9571 (re-search-forward
9572 (regexp-quote (format org-coderef-label-format label))
9573 nil t))))
9574 (when label (message "Label exists already") (sit-for 2))
9575 (setq label (read-string "Code line label: " label)))
9576 (end-of-line 1)
9577 (setq link (format org-coderef-label-format label))
9578 (setq gc (- 79 (length link)))
9579 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9580 (insert link)
9581 (setq link (concat "(" label ")") desc nil)))
9583 ;; We are in the agenda, link to referenced location
9584 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9585 (let ((m (or (get-text-property (point) 'org-hd-marker)
9586 (get-text-property (point) 'org-marker))))
9587 (when m
9588 (org-with-point-at m
9589 (setq agenda-link
9590 (if (org-called-interactively-p 'any)
9591 (call-interactively 'org-store-link)
9592 (org-store-link nil)))))))
9594 ((eq major-mode 'calendar-mode)
9595 (let ((cd (calendar-cursor-to-date)))
9596 (setq link
9597 (format-time-string
9598 (car org-time-stamp-formats)
9599 (apply 'encode-time
9600 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9601 nil nil nil))))
9602 (org-store-link-props :type "calendar" :date cd)))
9604 ((eq major-mode 'help-mode)
9605 (setq link (concat "help:" (save-excursion
9606 (goto-char (point-min))
9607 (looking-at "^[^ ]+")
9608 (match-string 0))))
9609 (org-store-link-props :type "help"))
9611 ((eq major-mode 'w3-mode)
9612 (setq cpltxt (if (and (buffer-name)
9613 (not (string-match "Untitled" (buffer-name))))
9614 (buffer-name)
9615 (url-view-url t))
9616 link (url-view-url t))
9617 (org-store-link-props :type "w3" :url (url-view-url t)))
9619 ((eq major-mode 'image-mode)
9620 (setq cpltxt (concat "file:"
9621 (abbreviate-file-name buffer-file-name))
9622 link cpltxt)
9623 (org-store-link-props :type "image" :file buffer-file-name))
9625 ;; In dired, store a link to the file of the current line
9626 ((derived-mode-p 'dired-mode)
9627 (let ((file (dired-get-filename nil t)))
9628 (setq file (if file
9629 (abbreviate-file-name
9630 (expand-file-name (dired-get-filename nil t)))
9631 ;; otherwise, no file so use current directory.
9632 default-directory))
9633 (setq cpltxt (concat "file:" file)
9634 link cpltxt)))
9636 ((setq search (run-hook-with-args-until-success
9637 'org-create-file-search-functions))
9638 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9639 "::" search))
9640 (setq cpltxt (or description link)))
9642 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9643 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9644 (cond
9645 ;; Store a link using the target at point
9646 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9647 (setq cpltxt
9648 (concat "file:"
9649 (abbreviate-file-name
9650 (buffer-file-name (buffer-base-buffer)))
9651 "::" (match-string 1))
9652 link cpltxt))
9653 ((and (featurep 'org-id)
9654 (or (eq org-id-link-to-org-use-id t)
9655 (and (org-called-interactively-p 'any)
9656 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9657 (and (eq org-id-link-to-org-use-id
9658 'create-if-interactive-and-no-custom-id)
9659 (not custom-id))))
9660 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9661 ;; Store a link using the ID at point
9662 (setq link (condition-case nil
9663 (prog1 (org-id-store-link)
9664 (setq desc (or (plist-get org-store-link-plist
9665 :description)
9666 "")))
9667 (error
9668 ;; Probably before first headline, link only to file
9669 (concat "file:"
9670 (abbreviate-file-name
9671 (buffer-file-name (buffer-base-buffer))))))))
9673 ;; Just link to current headline
9674 (setq cpltxt (concat "file:"
9675 (abbreviate-file-name
9676 (buffer-file-name (buffer-base-buffer)))))
9677 ;; Add a context search string
9678 (when (org-xor org-context-in-file-links arg)
9679 (let* ((ee (org-element-at-point))
9680 (et (org-element-type ee))
9681 (ev (plist-get (cadr ee) :value))
9682 (ek (plist-get (cadr ee) :key))
9683 (eok (and (stringp ek) (string-match "name" ek))))
9684 (setq txt (cond
9685 ((org-at-heading-p) nil)
9686 ((and (eq et 'keyword) eok) ev)
9687 ((org-region-active-p)
9688 (buffer-substring (region-beginning) (region-end)))))
9689 (when (or (null txt) (string-match "\\S-" txt))
9690 (setq cpltxt
9691 (concat cpltxt "::"
9692 (condition-case nil
9693 (org-make-org-heading-search-string txt)
9694 (error "")))
9695 desc (or (and (eq et 'keyword) eok ev)
9696 (nth 4 (ignore-errors (org-heading-components)))
9697 "NONE")))))
9698 (if (string-match "::\\'" cpltxt)
9699 (setq cpltxt (substring cpltxt 0 -2)))
9700 (setq link cpltxt))))
9702 ((buffer-file-name (buffer-base-buffer))
9703 ;; Just link to this file here.
9704 (setq cpltxt (concat "file:"
9705 (abbreviate-file-name
9706 (buffer-file-name (buffer-base-buffer)))))
9707 ;; Add a context string.
9708 (when (org-xor org-context-in-file-links arg)
9709 (setq txt (if (org-region-active-p)
9710 (buffer-substring (region-beginning) (region-end))
9711 (buffer-substring (point-at-bol) (point-at-eol))))
9712 ;; Only use search option if there is some text.
9713 (when (string-match "\\S-" txt)
9714 (setq cpltxt
9715 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9716 desc "NONE")))
9717 (setq link cpltxt))
9719 ((org-called-interactively-p 'interactive)
9720 (user-error "No method for storing a link from this buffer"))
9722 (t (setq link nil)))
9724 ;; We're done setting link and desc, clean up
9725 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9726 (setq link (or link cpltxt)
9727 desc (or desc cpltxt))
9728 (cond ((equal desc "NONE") (setq desc nil))
9729 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9730 (let ((d0 (match-string 3 desc))
9731 (p0 (match-string 5 desc)))
9732 (setq desc
9733 (replace-regexp-in-string
9734 org-bracket-link-regexp
9735 (concat (or p0 d0)
9736 (if (equal (length (match-string 0 desc))
9737 (length desc)) "*" "")) desc)))))
9739 ;; Return the link
9740 (if (not (and (or (org-called-interactively-p 'any)
9741 executing-kbd-macro) link))
9742 (or agenda-link (and link (org-make-link-string link desc)))
9743 (push (list link desc) org-stored-links)
9744 (message "Stored: %s" (or desc link))
9745 (when custom-id
9746 (setq link (concat "file:" (abbreviate-file-name
9747 (buffer-file-name)) "::#" custom-id))
9748 (push (list link desc) org-stored-links))
9749 (car org-stored-links))))))
9751 (defun org-store-link-props (&rest plist)
9752 "Store link properties, extract names and addresses."
9753 (let (x adr)
9754 (when (setq x (plist-get plist :from))
9755 (setq adr (mail-extract-address-components x))
9756 (setq plist (plist-put plist :fromname (car adr)))
9757 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9758 (when (setq x (plist-get plist :to))
9759 (setq adr (mail-extract-address-components x))
9760 (setq plist (plist-put plist :toname (car adr)))
9761 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9762 (let ((from (plist-get plist :from))
9763 (to (plist-get plist :to)))
9764 (when (and from to org-from-is-user-regexp)
9765 (setq plist
9766 (plist-put plist :fromto
9767 (if (string-match org-from-is-user-regexp from)
9768 (concat "to %t")
9769 (concat "from %f"))))))
9770 (setq org-store-link-plist plist))
9772 (defun org-add-link-props (&rest plist)
9773 "Add these properties to the link property list."
9774 (let (key value)
9775 (while plist
9776 (setq key (pop plist) value (pop plist))
9777 (setq org-store-link-plist
9778 (plist-put org-store-link-plist key value)))))
9780 (defun org-email-link-description (&optional fmt)
9781 "Return the description part of an email link.
9782 This takes information from `org-store-link-plist' and formats it
9783 according to FMT (default from `org-email-link-description-format')."
9784 (setq fmt (or fmt org-email-link-description-format))
9785 (let* ((p org-store-link-plist)
9786 (to (plist-get p :toaddress))
9787 (from (plist-get p :fromaddress))
9788 (table
9789 (list
9790 (cons "%c" (plist-get p :fromto))
9791 (cons "%F" (plist-get p :from))
9792 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9793 (cons "%T" (plist-get p :to))
9794 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9795 (cons "%s" (plist-get p :subject))
9796 (cons "%d" (plist-get p :date))
9797 (cons "%m" (plist-get p :message-id)))))
9798 (when (string-match "%c" fmt)
9799 ;; Check if the user wrote this message
9800 (if (and org-from-is-user-regexp from to
9801 (save-match-data (string-match org-from-is-user-regexp from)))
9802 (setq fmt (replace-match "to %t" t t fmt))
9803 (setq fmt (replace-match "from %f" t t fmt))))
9804 (org-replace-escapes fmt table)))
9806 (defun org-make-org-heading-search-string (&optional string)
9807 "Make search string for the current headline or STRING."
9808 (let ((s (or string
9809 (and (derived-mode-p 'org-mode)
9810 (save-excursion
9811 (org-back-to-heading t)
9812 (org-element-property :raw-value (org-element-at-point))))))
9813 (lines org-context-in-file-links))
9814 (or string (setq s (concat "*" s))) ; Add * for headlines
9815 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9816 (when (and string (integerp lines) (> lines 0))
9817 (let ((slines (org-split-string s "\n")))
9818 (when (< lines (length slines))
9819 (setq s (mapconcat
9820 'identity
9821 (reverse (nthcdr (- (length slines) lines)
9822 (reverse slines))) "\n")))))
9823 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9825 (defun org-make-link-string (link &optional description)
9826 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9827 (unless (string-match "\\S-" link)
9828 (error "Empty link"))
9829 (when (and description
9830 (stringp description)
9831 (not (string-match "\\S-" description)))
9832 (setq description nil))
9833 (when (stringp description)
9834 ;; Remove brackets from the description, they are fatal.
9835 (while (string-match "\\[" description)
9836 (setq description (replace-match "{" t t description)))
9837 (while (string-match "\\]" description)
9838 (setq description (replace-match "}" t t description))))
9839 (when (equal link description)
9840 ;; No description needed, it is identical
9841 (setq description nil))
9842 (when (and (not description)
9843 (not (string-match (org-image-file-name-regexp) link))
9844 (not (equal link (org-link-escape link))))
9845 (setq description (org-extract-attributes link)))
9846 (setq link
9847 (cond ((string-match (org-image-file-name-regexp) link) link)
9848 ((string-match org-link-types-re link)
9849 (concat (match-string 1 link)
9850 (org-link-escape (substring link (match-end 1)))))
9851 (t (org-link-escape link))))
9852 (concat "[[" link "]"
9853 (if description (concat "[" description "]") "")
9854 "]"))
9856 (defconst org-link-escape-chars
9857 ;;%20 %2B %3B %3D %5B %5D
9858 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9859 "List of characters that should be escaped in a link when stored to Org.
9860 This is the list that is used for internal purposes.")
9862 (defconst org-link-escape-chars-browser
9863 ;;%20 %22
9864 '(?\ ?\")
9865 "List of characters to be escaped before handing over to the browser.
9866 If you consider using this constant then you probably want to use
9867 the function `org-link-escape-browser' instead. See there why
9868 this constant is a candidate to be removed once Org drops support
9869 for Emacs 24.1 and 24.2.")
9871 (defun org-link-escape (text &optional table merge)
9872 "Return percent escaped representation of TEXT.
9873 TEXT is a string with the text to escape.
9874 Optional argument TABLE is a list with characters that should be
9875 escaped. When nil, `org-link-escape-chars' is used.
9876 If optional argument MERGE is set, merge TABLE into
9877 `org-link-escape-chars'."
9878 (cond
9879 ((and table merge)
9880 (mapc (lambda (defchr)
9881 (unless (member defchr table)
9882 (setq table (cons defchr table)))) org-link-escape-chars))
9883 ((null table)
9884 (setq table org-link-escape-chars)))
9885 (mapconcat
9886 (lambda (char)
9887 (if (or (member char table)
9888 (and (or (< char 32) (= char ?\%) (> char 126))
9889 org-url-hexify-p))
9890 (mapconcat (lambda (sequence-element)
9891 (format "%%%.2X" sequence-element))
9892 (or (encode-coding-char char 'utf-8)
9893 (error "Unable to percent escape character: %s"
9894 (char-to-string char))) "")
9895 (char-to-string char))) text ""))
9897 (defun org-link-escape-browser (text)
9898 "Escape some characters before handing over to the browser.
9899 This function is a candidate to be removed together with the
9900 constant `org-link-escape-chars-browser' once Org drops support
9901 for Emacs 24.1 and 24.2. All calls to this function will have to
9902 be replaced with `url-encode-url' which is available since Emacs
9903 24.3.1."
9904 ;; Example with the Org link
9905 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
9906 ;; to open the browser with +subject:"Release 8.2" filled into the
9907 ;; query field: In this case the variable TEXT contains the
9908 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
9909 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
9910 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
9911 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
9912 (if (fboundp 'url-encode-url)
9913 (url-encode-url text)
9914 (if (org-string-match-p
9915 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9916 text)
9917 (org-link-escape text org-link-escape-chars-browser)
9918 text)))
9920 (defun org-link-unescape (str)
9921 "Unhex hexified Unicode strings as returned from the JavaScript function
9922 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9923 (unless (and (null str) (string= "" str))
9924 (let ((pos 0) (case-fold-search t) unhexed)
9925 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9926 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9927 (setq str (replace-match unhexed t t str))
9928 (setq pos (+ pos (length unhexed))))))
9929 str)
9931 (defun org-link-unescape-compound (hex)
9932 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9933 Note: this function also decodes single byte encodings like
9934 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9935 (save-match-data
9936 (let* ((bytes (cdr (split-string hex "%")))
9937 (ret "")
9938 (eat 0)
9939 (sum 0))
9940 (while bytes
9941 (let* ((val (string-to-number (pop bytes) 16))
9942 (shift-xor
9943 (if (= 0 eat)
9944 (cond
9945 ((>= val 252) (cons 6 252))
9946 ((>= val 248) (cons 5 248))
9947 ((>= val 240) (cons 4 240))
9948 ((>= val 224) (cons 3 224))
9949 ((>= val 192) (cons 2 192))
9950 (t (cons 0 0)))
9951 (cons 6 128))))
9952 (if (>= val 192) (setq eat (car shift-xor)))
9953 (setq val (logxor val (cdr shift-xor)))
9954 (setq sum (+ (lsh sum (car shift-xor)) val))
9955 (if (> eat 0) (setq eat (- eat 1)))
9956 (cond
9957 ((= 0 eat) ;multi byte
9958 (setq ret (concat ret (org-char-to-string sum)))
9959 (setq sum 0))
9960 ((not bytes) ; single byte(s)
9961 (setq ret (org-link-unescape-single-byte-sequence hex))))
9962 )) ;; end (while bytes
9963 ret )))
9965 (defun org-link-unescape-single-byte-sequence (hex)
9966 "Unhexify hex-encoded single byte character sequences."
9967 (mapconcat (lambda (byte)
9968 (char-to-string (string-to-number byte 16)))
9969 (cdr (split-string hex "%")) ""))
9971 (defun org-xor (a b)
9972 "Exclusive or."
9973 (if a (not b) b))
9975 (defun org-fixup-message-id-for-http (s)
9976 "Replace special characters in a message id, so it can be used in an http query."
9977 (when (string-match "%" s)
9978 (setq s (mapconcat (lambda (c)
9979 (if (eq c ?%)
9980 "%25"
9981 (char-to-string c)))
9982 s "")))
9983 (while (string-match "<" s)
9984 (setq s (replace-match "%3C" t t s)))
9985 (while (string-match ">" s)
9986 (setq s (replace-match "%3E" t t s)))
9987 (while (string-match "@" s)
9988 (setq s (replace-match "%40" t t s)))
9991 (defun org-link-prettify (link)
9992 "Return a human-readable representation of LINK.
9993 The car of LINK must be a raw link.
9994 The cdr of LINK must be either a link description or nil."
9995 (let ((desc (or (cadr link) "<no description>")))
9996 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9997 "<" (car link) ">")))
9999 ;;;###autoload
10000 (defun org-insert-link-global ()
10001 "Insert a link like Org-mode does.
10002 This command can be called in any mode to insert a link in Org-mode syntax."
10003 (interactive)
10004 (org-load-modules-maybe)
10005 (org-run-like-in-org-mode 'org-insert-link))
10007 (defun org-insert-all-links (arg &optional pre post)
10008 "Insert all links in `org-stored-links'.
10009 When a universal prefix, do not delete the links from `org-stored-links'.
10010 When `ARG' is a number, insert the last N link(s).
10011 `PRE' and `POST' are optional arguments to define a string to
10012 prepend or to append."
10013 (interactive "P")
10014 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10015 (links (copy-seq org-stored-links))
10016 (pr (or pre "- "))
10017 (po (or post "\n"))
10018 (cnt 1) l)
10019 (if (null org-stored-links)
10020 (message "No link to insert")
10021 (while (and (or (listp arg) (>= arg cnt))
10022 (setq l (if (listp arg)
10023 (pop links)
10024 (pop org-stored-links))))
10025 (setq cnt (1+ cnt))
10026 (insert pr)
10027 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10028 (insert po)))))
10030 (defun org-insert-last-stored-link (arg)
10031 "Insert the last link stored in `org-stored-links'."
10032 (interactive "p")
10033 (org-insert-all-links arg "" "\n"))
10035 (defun org-link-fontify-links-to-this-file ()
10036 "Fontify links to the current file in `org-stored-links'."
10037 (let ((f (buffer-file-name)) a b)
10038 (setq a (mapcar (lambda(l)
10039 (let ((ll (car l)))
10040 (when (and (string-match "^file:\\(.+\\)::" ll)
10041 (equal f (expand-file-name (match-string 1 ll))))
10042 ll)))
10043 org-stored-links))
10044 (when (featurep 'org-id)
10045 (setq b (mapcar (lambda(l)
10046 (let ((ll (car l)))
10047 (when (and (string-match "^id:\\(.+\\)$" ll)
10048 (equal f (expand-file-name
10049 (or (org-id-find-id-file
10050 (match-string 1 ll)) ""))))
10051 ll)))
10052 org-stored-links)))
10053 (mapcar (lambda(l)
10054 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10055 (delq nil (append a b)))))
10057 (defvar org-link-links-in-this-file nil)
10058 (defun org-insert-link (&optional complete-file link-location default-description)
10059 "Insert a link. At the prompt, enter the link.
10061 Completion can be used to insert any of the link protocol prefixes like
10062 http or ftp in use.
10064 The history can be used to select a link previously stored with
10065 `org-store-link'. When the empty string is entered (i.e. if you just
10066 press RET at the prompt), the link defaults to the most recently
10067 stored link. As SPC triggers completion in the minibuffer, you need to
10068 use M-SPC or C-q SPC to force the insertion of a space character.
10070 You will also be prompted for a description, and if one is given, it will
10071 be displayed in the buffer instead of the link.
10073 If there is already a link at point, this command will allow you to edit link
10074 and description parts.
10076 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10077 be selected using completion. The path to the file will be relative to the
10078 current directory if the file is in the current directory or a subdirectory.
10079 Otherwise, the link will be the absolute path as completed in the minibuffer
10080 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10081 option `org-link-file-path-type'.
10083 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10084 the current directory or below.
10086 With three \\[universal-argument] prefixes, negate the meaning of
10087 `org-keep-stored-link-after-insertion'.
10089 If `org-make-link-description-function' is non-nil, this function will be
10090 called with the link target, and the result will be the default
10091 link description.
10093 If the LINK-LOCATION parameter is non-nil, this value will be
10094 used as the link location instead of reading one interactively.
10096 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10097 be used as the default description."
10098 (interactive "P")
10099 (let* ((wcf (current-window-configuration))
10100 (origbuf (current-buffer))
10101 (region (if (org-region-active-p)
10102 (buffer-substring (region-beginning) (region-end))))
10103 (remove (and region (list (region-beginning) (region-end))))
10104 (desc region)
10105 tmphist ; byte-compile incorrectly complains about this
10106 (link link-location)
10107 (abbrevs org-link-abbrev-alist-local)
10108 entry file all-prefixes auto-desc)
10109 (cond
10110 (link-location) ; specified by arg, just use it.
10111 ((org-in-regexp org-bracket-link-regexp 1)
10112 ;; We do have a link at point, and we are going to edit it.
10113 (setq remove (list (match-beginning 0) (match-end 0)))
10114 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10115 (setq link (read-string "Link: "
10116 (org-link-unescape
10117 (org-match-string-no-properties 1)))))
10118 ((or (org-in-regexp org-angle-link-re)
10119 (org-in-regexp org-plain-link-re))
10120 ;; Convert to bracket link
10121 (setq remove (list (match-beginning 0) (match-end 0))
10122 link (read-string "Link: "
10123 (org-remove-angle-brackets (match-string 0)))))
10124 ((member complete-file '((4) (16)))
10125 ;; Completing read for file names.
10126 (setq link (org-file-complete-link complete-file)))
10128 ;; Read link, with completion for stored links.
10129 (org-link-fontify-links-to-this-file)
10130 (org-switch-to-buffer-other-window "*Org Links*")
10131 (with-current-buffer "*Org Links*"
10132 (erase-buffer)
10133 (insert "Insert a link.
10134 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10135 (when org-stored-links
10136 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10137 (insert (mapconcat 'org-link-prettify
10138 (reverse org-stored-links) "\n")))
10139 (goto-char (point-min)))
10140 (let ((cw (selected-window)))
10141 (select-window (get-buffer-window "*Org Links*" 'visible))
10142 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10143 (unless (pos-visible-in-window-p (point-max))
10144 (org-fit-window-to-buffer))
10145 (and (window-live-p cw) (select-window cw)))
10146 ;; Fake a link history, containing the stored links.
10147 (setq tmphist (append (mapcar 'car org-stored-links)
10148 org-insert-link-history))
10149 (setq all-prefixes (append (mapcar 'car abbrevs)
10150 (mapcar 'car org-link-abbrev-alist)
10151 org-link-types))
10152 (unwind-protect
10153 (progn
10154 (setq link
10155 (org-completing-read
10156 "Link: "
10157 (append
10158 (mapcar (lambda (x) (concat x ":"))
10159 all-prefixes)
10160 (mapcar 'car org-stored-links))
10161 nil nil nil
10162 'tmphist
10163 (caar org-stored-links)))
10164 (if (not (string-match "\\S-" link))
10165 (user-error "No link selected"))
10166 (mapc (lambda(l)
10167 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10168 org-stored-links)
10169 (if (or (member link all-prefixes)
10170 (and (equal ":" (substring link -1))
10171 (member (substring link 0 -1) all-prefixes)
10172 (setq link (substring link 0 -1))))
10173 (setq link (with-current-buffer origbuf
10174 (org-link-try-special-completion link)))))
10175 (set-window-configuration wcf)
10176 (kill-buffer "*Org Links*"))
10177 (setq entry (assoc link org-stored-links))
10178 (or entry (push link org-insert-link-history))
10179 (setq desc (or desc (nth 1 entry)))))
10181 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10182 (not org-keep-stored-link-after-insertion))
10183 (setq org-stored-links (delq (assoc link org-stored-links)
10184 org-stored-links)))
10186 (if (and (string-match org-plain-link-re link)
10187 (not (string-match org-ts-regexp link)))
10188 ;; URL-like link, normalize the use of angular brackets.
10189 (setq link (org-remove-angle-brackets link)))
10191 ;; Check if we are linking to the current file with a search
10192 ;; option If yes, simplify the link by using only the search
10193 ;; option.
10194 (when (and buffer-file-name
10195 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10196 (let* ((path (match-string 1 link))
10197 (case-fold-search nil)
10198 (search (match-string 2 link)))
10199 (save-match-data
10200 (if (equal (file-truename buffer-file-name) (file-truename path))
10201 ;; We are linking to this same file, with a search option
10202 (setq link search)))))
10204 ;; Check if we can/should use a relative path. If yes, simplify the link
10205 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10206 (let* ((type (match-string 1 link))
10207 (path (match-string 2 link))
10208 (origpath path)
10209 (case-fold-search nil))
10210 (cond
10211 ((or (eq org-link-file-path-type 'absolute)
10212 (equal complete-file '(16)))
10213 (setq path (abbreviate-file-name (expand-file-name path))))
10214 ((eq org-link-file-path-type 'noabbrev)
10215 (setq path (expand-file-name path)))
10216 ((eq org-link-file-path-type 'relative)
10217 (setq path (file-relative-name path)))
10219 (save-match-data
10220 (if (string-match (concat "^" (regexp-quote
10221 (expand-file-name
10222 (file-name-as-directory
10223 default-directory))))
10224 (expand-file-name path))
10225 ;; We are linking a file with relative path name.
10226 (setq path (substring (expand-file-name path)
10227 (match-end 0)))
10228 (setq path (abbreviate-file-name (expand-file-name path)))))))
10229 (setq link (concat type path))
10230 (if (equal desc origpath)
10231 (setq desc path))))
10233 (if org-make-link-description-function
10234 (setq desc
10235 (or (condition-case nil
10236 (funcall org-make-link-description-function link desc)
10237 (error (progn (message "Can't get link description from `%s'"
10238 (symbol-name org-make-link-description-function))
10239 (sit-for 2) nil)))
10240 (read-string "Description: " default-description)))
10241 (if default-description (setq desc default-description)
10242 (setq desc (or (and auto-desc desc)
10243 (read-string "Description: " desc)))))
10245 (unless (string-match "\\S-" desc) (setq desc nil))
10246 (if remove (apply 'delete-region remove))
10247 (insert (org-make-link-string link desc))))
10249 (defun org-link-try-special-completion (type)
10250 "If there is completion support for link type TYPE, offer it."
10251 (let ((fun (intern (concat "org-" type "-complete-link"))))
10252 (if (functionp fun)
10253 (funcall fun)
10254 (read-string "Link (no completion support): " (concat type ":")))))
10256 (defun org-file-complete-link (&optional arg)
10257 "Create a file link using completion."
10258 (let (file link)
10259 (setq file (org-iread-file-name "File: "))
10260 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10261 (pwd1 (file-name-as-directory (abbreviate-file-name
10262 (expand-file-name ".")))))
10263 (cond
10264 ((equal arg '(16))
10265 (setq link (concat
10266 "file:"
10267 (abbreviate-file-name (expand-file-name file)))))
10268 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10269 (setq link (concat "file:" (match-string 1 file))))
10270 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10271 (expand-file-name file))
10272 (setq link (concat
10273 "file:" (match-string 1 (expand-file-name file)))))
10274 (t (setq link (concat "file:" file)))))
10275 link))
10277 (defun org-iread-file-name (&rest args)
10278 "Read-file-name using `ido-mode' speedup if available.
10279 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10280 See `read-file-name' for a description of parameters."
10281 (org-without-partial-completion
10282 (if (and org-completion-use-ido
10283 (fboundp 'ido-read-file-name)
10284 (boundp 'ido-mode) ido-mode
10285 (listp (second args)))
10286 (let ((ido-enter-matching-directory nil))
10287 (apply 'ido-read-file-name args))
10288 (apply 'read-file-name args))))
10290 (defun org-completing-read (&rest args)
10291 "Completing-read with SPACE being a normal character."
10292 (let ((enable-recursive-minibuffers t)
10293 (minibuffer-local-completion-map
10294 (copy-keymap minibuffer-local-completion-map)))
10295 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10296 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10297 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10298 (apply 'org-icompleting-read args)))
10300 (defun org-completing-read-no-i (&rest args)
10301 (let (org-completion-use-ido org-completion-use-iswitchb)
10302 (apply 'org-completing-read args)))
10304 (defun org-iswitchb-completing-read (prompt choices &rest args)
10305 "Use iswitch as a completing-read replacement to choose from choices.
10306 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10307 from."
10308 (let* ((iswitchb-use-virtual-buffers nil)
10309 (iswitchb-make-buflist-hook
10310 (lambda ()
10311 (setq iswitchb-temp-buflist choices))))
10312 (iswitchb-read-buffer prompt)))
10314 (defun org-icompleting-read (&rest args)
10315 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10316 (org-without-partial-completion
10317 (if (and org-completion-use-ido
10318 (fboundp 'ido-completing-read)
10319 (boundp 'ido-mode) ido-mode
10320 (listp (second args)))
10321 (let ((ido-enter-matching-directory nil))
10322 (apply 'ido-completing-read (concat (car args))
10323 (if (consp (car (nth 1 args)))
10324 (mapcar 'car (nth 1 args))
10325 (nth 1 args))
10326 (cddr args)))
10327 (if (and org-completion-use-iswitchb
10328 (boundp 'iswitchb-mode) iswitchb-mode
10329 (listp (second args)))
10330 (apply 'org-iswitchb-completing-read (concat (car args))
10331 (if (consp (car (nth 1 args)))
10332 (mapcar 'car (nth 1 args))
10333 (nth 1 args))
10334 (cddr args))
10335 (apply 'completing-read args)))))
10337 (defun org-extract-attributes (s)
10338 "Extract the attributes cookie from a string and set as text property."
10339 (let (a attr (start 0) key value)
10340 (save-match-data
10341 (when (string-match "{{\\([^}]+\\)}}$" s)
10342 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10343 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10344 (setq key (match-string 1 a) value (match-string 2 a)
10345 start (match-end 0)
10346 attr (plist-put attr (intern key) value))))
10347 (org-add-props s nil 'org-attr attr))
10350 ;;; Opening/following a link
10352 (defvar org-link-search-failed nil)
10354 (defvar org-open-link-functions nil
10355 "Hook for functions finding a plain text link.
10356 These functions must take a single argument, the link content.
10357 They will be called for links that look like [[link text][description]]
10358 when LINK TEXT does not have a protocol like \"http:\" and does not look
10359 like a filename (e.g. \"./blue.png\").
10361 These functions will be called *before* Org attempts to resolve the
10362 link by doing text searches in the current buffer - so if you want a
10363 link \"[[target]]\" to still find \"<<target>>\", your function should
10364 handle this as a special case.
10366 When the function does handle the link, it must return a non-nil value.
10367 If it decides that it is not responsible for this link, it must return
10368 nil to indicate that that Org-mode can continue with other options
10369 like exact and fuzzy text search.")
10371 (defun org-next-link (&optional search-backward)
10372 "Move forward to the next link.
10373 If the link is in hidden text, expose it."
10374 (interactive "P")
10375 (when (and org-link-search-failed (eq this-command last-command))
10376 (goto-char (point-min))
10377 (message "Link search wrapped back to beginning of buffer"))
10378 (setq org-link-search-failed nil)
10379 (let* ((pos (point))
10380 (ct (org-context))
10381 (a (assoc :link ct))
10382 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10383 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10384 ((looking-at org-any-link-re)
10385 ;; Don't stay stuck at link without an org-link face
10386 (forward-char (if search-backward -1 1))))
10387 (if (funcall srch-fun org-any-link-re nil t)
10388 (progn
10389 (goto-char (match-beginning 0))
10390 (if (outline-invisible-p) (org-show-context)))
10391 (goto-char pos)
10392 (setq org-link-search-failed t)
10393 (message "No further link found"))))
10395 (defun org-previous-link ()
10396 "Move backward to the previous link.
10397 If the link is in hidden text, expose it."
10398 (interactive)
10399 (funcall 'org-next-link t))
10401 (defun org-translate-link (s)
10402 "Translate a link string if a translation function has been defined."
10403 (if (and org-link-translation-function
10404 (fboundp org-link-translation-function)
10405 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10406 (progn
10407 (setq s (funcall org-link-translation-function
10408 (match-string 1 s) (match-string 2 s)))
10409 (concat (car s) ":" (cdr s)))
10412 (defun org-translate-link-from-planner (type path)
10413 "Translate a link from Emacs Planner syntax so that Org can follow it.
10414 This is still an experimental function, your mileage may vary."
10415 (cond
10416 ((member type '("http" "https" "news" "ftp"))
10417 ;; standard Internet links are the same.
10418 nil)
10419 ((and (equal type "irc") (string-match "^//" path))
10420 ;; Planner has two / at the beginning of an irc link, we have 1.
10421 ;; We should have zero, actually....
10422 (setq path (substring path 1)))
10423 ((and (equal type "lisp") (string-match "^/" path))
10424 ;; Planner has a slash, we do not.
10425 (setq type "elisp" path (substring path 1)))
10426 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10427 ;; A typical message link. Planner has the id after the final slash,
10428 ;; we separate it with a hash mark
10429 (setq path (concat (match-string 1 path) "#"
10430 (org-remove-angle-brackets (match-string 2 path))))))
10431 (cons type path))
10433 (defun org-find-file-at-mouse (ev)
10434 "Open file link or URL at mouse."
10435 (interactive "e")
10436 (mouse-set-point ev)
10437 (org-open-at-point 'in-emacs))
10439 (defun org-open-at-mouse (ev)
10440 "Open file link or URL at mouse.
10441 See the docstring of `org-open-file' for details."
10442 (interactive "e")
10443 (mouse-set-point ev)
10444 (if (eq major-mode 'org-agenda-mode)
10445 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10446 (org-open-at-point))
10448 (defvar org-window-config-before-follow-link nil
10449 "The window configuration before following a link.
10450 This is saved in case the need arises to restore it.")
10452 (defvar org-open-link-marker (make-marker)
10453 "Marker pointing to the location where `org-open-at-point' was called.")
10455 ;;;###autoload
10456 (defun org-open-at-point-global ()
10457 "Follow a link like Org-mode does.
10458 This command can be called in any mode to follow a link that has
10459 Org-mode syntax."
10460 (interactive)
10461 (org-run-like-in-org-mode 'org-open-at-point))
10463 ;;;###autoload
10464 (defun org-open-link-from-string (s &optional arg reference-buffer)
10465 "Open a link in the string S, as if it was in Org-mode."
10466 (interactive "sLink: \nP")
10467 (let ((reference-buffer (or reference-buffer (current-buffer))))
10468 (with-temp-buffer
10469 (let ((org-inhibit-startup (not reference-buffer)))
10470 (org-mode)
10471 (insert s)
10472 (goto-char (point-min))
10473 (when reference-buffer
10474 (setq org-link-abbrev-alist-local
10475 (with-current-buffer reference-buffer
10476 org-link-abbrev-alist-local)))
10477 (org-open-at-point arg reference-buffer)))))
10479 (defvar org-open-at-point-functions nil
10480 "Hook that is run when following a link at point.
10482 Functions in this hook must return t if they identify and follow
10483 a link at point. If they don't find anything interesting at point,
10484 they must return nil.")
10486 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10487 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10488 (defun org-open-at-point (&optional arg reference-buffer)
10489 "Open link, timestamp, footnote or tags at point.
10491 When point is on a link, follow it. Normally, files will be
10492 opened by an appropriate application. If the optional prefix
10493 argument ARG is non-nil, Emacs will visit the file. With
10494 a double prefix argument, try to open outside of Emacs, in the
10495 application the system uses for this file type.
10497 When point is on a timestamp, open the agenda at the day
10498 specified.
10500 When point is a footnote definition, move to the first reference
10501 found. If it is on a reference, move to the associated
10502 definition.
10504 When point is on a headline, display a list of every link in the
10505 entry, so it is possible to pick one, or all, of them. If point
10506 is on a tag, call `org-tags-view' instead.
10508 When optional argument REFERENCE-BUFFER is non-nil, it should
10509 specify a buffer from where the link search should happen. This
10510 is used internally by `org-open-link-from-string'."
10511 (interactive "P")
10512 ;; On a code block, open block's results.
10513 (unless (call-interactively #'org-babel-open-src-block-result)
10514 (org-load-modules-maybe)
10515 (move-marker org-open-link-marker (point))
10516 (setq org-window-config-before-follow-link (current-window-configuration))
10517 (org-remove-occur-highlights nil nil t)
10518 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10519 (let* ((context (org-element-context)) type)
10520 ;; On an unsupported type, check if point is contained within
10521 ;; a support one.
10522 (while (and (not (memq (setq type (org-element-type context))
10523 '(headline inlinetask link footnote-definition
10524 footnote-reference timestamp)))
10525 (setq context (org-element-property :parent context))))
10526 (cond
10527 ;; Unsupported context: return an error.
10528 ((not context) (user-error "No link found"))
10529 ;; On a headline or an inlinetask, but not on a timestamp,
10530 ;; a link, a footnote reference or on tags.
10531 ((and (memq type '(headline inlinetask))
10532 ;; Not on tags.
10533 (progn (save-excursion (beginning-of-line)
10534 (looking-at org-complex-heading-regexp))
10535 (or (not (match-beginning 5))
10536 (< (point) (match-beginning 5)))))
10537 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10538 (links (car data))
10539 (links-end (cdr data)))
10540 (if links
10541 (dolist (link (if (stringp links) (list links) links))
10542 (search-forward link nil links-end)
10543 (goto-char (match-beginning 0))
10544 (org-open-at-point))
10545 (require 'org-attach)
10546 (org-attach-reveal 'if-exists))))
10547 ;; Do nothing on white spaces after an object, unless point
10548 ;; is right after it.
10549 ((> (point)
10550 (save-excursion
10551 (goto-char (org-element-property :end context))
10552 (skip-chars-backward " \t")
10553 (point)))
10554 (user-error "No link found"))
10555 ((eq type 'timestamp) (org-follow-timestamp-link))
10556 ;; On tags within a headline or an inlinetask.
10557 ((and (memq type '(headline inlinetask))
10558 (progn (save-excursion (beginning-of-line)
10559 (looking-at org-complex-heading-regexp))
10560 (and (match-beginning 5)
10561 (>= (point) (match-beginning 5)))))
10562 (org-tags-view arg (substring (match-string 5) 0 -1)))
10563 ((eq type 'link)
10564 (let ((type (org-element-property :type context))
10565 (path (org-link-unescape (org-element-property :path context))))
10566 ;; Switch back to REFERENCE-BUFFER needed when called in
10567 ;; a temporary buffer through `org-open-link-from-string'.
10568 (with-current-buffer (or reference-buffer (current-buffer))
10569 (cond
10570 ((equal type "file")
10571 (if (string-match "[*?{]" (file-name-nondirectory path))
10572 (dired path)
10573 ;; Look into `org-link-protocols' in order to find
10574 ;; a DEDICATED-FUNCTION to open file. The function
10575 ;; will be applied on raw link instead of parsed
10576 ;; link due to the limitation in `org-add-link-type'
10577 ;; ("open" function called with a single argument).
10578 ;; If no such function is found, fallback to
10579 ;; `org-open-file'.
10581 ;; Note : "file+emacs" and "file+sys" types are
10582 ;; hard-coded in order to escape the previous
10583 ;; limitation.
10584 (let* ((option (org-element-property :search-option context))
10585 (app (org-element-property :application context))
10586 (dedicated-function
10587 (nth 1 (assoc app org-link-protocols))))
10588 (if dedicated-function
10589 (funcall dedicated-function
10590 (concat path
10591 (and option (concat "::" option))))
10592 (apply #'org-open-file
10593 path
10594 (cond (arg)
10595 ((equal app "emacs") 'emacs)
10596 ((equal app "sys") 'system))
10597 (cond ((not option) nil)
10598 ((org-string-match-p "\\`[0-9]+\\'" option)
10599 (list (string-to-number option)))
10600 (t (list nil
10601 (org-link-unescape option)))))))))
10602 ((assoc type org-link-protocols)
10603 (funcall (nth 1 (assoc type org-link-protocols)) path))
10604 ((equal type "help")
10605 (let ((f-or-v (intern path)))
10606 (cond ((fboundp f-or-v) (describe-function f-or-v))
10607 ((boundp f-or-v) (describe-variable f-or-v))
10608 (t (error "Not a known function or variable")))))
10609 ((member type '("http" "https" "ftp" "mailto" "news"))
10610 (browse-url (org-link-escape-browser (concat type ":" path))))
10611 ((equal type "doi")
10612 (browse-url
10613 (org-link-escape-browser (concat org-doi-server-url path))))
10614 ((equal type "message") (browse-url (concat type ":" path)))
10615 ((equal type "shell")
10616 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10617 (cmd path))
10618 (if (or (and (org-string-nw-p
10619 org-confirm-shell-link-not-regexp)
10620 (string-match
10621 org-confirm-shell-link-not-regexp cmd))
10622 (not org-confirm-shell-link-function)
10623 (funcall org-confirm-shell-link-function
10624 (format "Execute \"%s\" in shell? "
10625 (org-add-props cmd nil
10626 'face 'org-warning))))
10627 (progn
10628 (message "Executing %s" cmd)
10629 (shell-command cmd buf)
10630 (when (featurep 'midnight)
10631 (setq clean-buffer-list-kill-buffer-names
10632 (cons buf
10633 clean-buffer-list-kill-buffer-names))))
10634 (user-error "Abort"))))
10635 ((equal type "elisp")
10636 (let ((cmd path))
10637 (if (or (and (org-string-nw-p
10638 org-confirm-elisp-link-not-regexp)
10639 (org-string-match-p
10640 org-confirm-elisp-link-not-regexp cmd))
10641 (not org-confirm-elisp-link-function)
10642 (funcall org-confirm-elisp-link-function
10643 (format "Execute \"%s\" as elisp? "
10644 (org-add-props cmd nil
10645 'face 'org-warning))))
10646 (message "%s => %s" cmd
10647 (if (eq (string-to-char cmd) ?\()
10648 (eval (read cmd))
10649 (call-interactively (read cmd))))
10650 (user-error "Abort"))))
10651 ((equal type "id")
10652 (require 'ord-id)
10653 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10654 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10655 (unless (run-hook-with-args-until-success
10656 'org-open-link-functions path)
10657 (if (not arg) (org-mark-ring-push)
10658 (switch-to-buffer-other-window
10659 (org-get-buffer-for-internal-link (current-buffer))))
10660 (let ((cmd `(org-link-search
10661 ,(if (member type '("custom-id" "coderef"))
10662 (org-element-property :raw-link context)
10663 path)
10664 ,(cond ((equal arg '(4)) 'occur)
10665 ((equal arg '(16)) 'org-occur))
10666 ,(org-element-property :begin context))))
10667 (condition-case nil
10668 (let ((org-link-search-inhibit-query t))
10669 (eval cmd))
10670 (error (progn (widen) (eval cmd)))))))
10671 (t (browse-url-at-point))))))
10672 ;; On a footnote reference or at a footnote definition's label.
10673 ((or (eq type 'footnote-reference)
10674 (and (eq type 'footnote-definition)
10675 (save-excursion
10676 ;; Do not validate action when point is on the
10677 ;; spaces right after the footnote label, in
10678 ;; order to be on par with behaviour on links.
10679 (skip-chars-forward " \t")
10680 (let ((begin
10681 (org-element-property :contents-begin context)))
10682 (if begin (< (point) begin)
10683 (= (org-element-property :post-affiliated context)
10684 (line-beginning-position)))))))
10685 (org-footnote-action))
10686 (t (user-error "No link found")))))
10687 (move-marker org-open-link-marker nil)
10688 (run-hook-with-args 'org-follow-link-hook)))
10690 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10691 "Offer links in the current entry and return the selected link.
10692 If there is only one link, return it.
10693 If NTH is an integer, return the NTH link found.
10694 If ZERO is a string, check also this string for a link, and if
10695 there is one, return it."
10696 (with-current-buffer buffer
10697 (save-excursion
10698 (save-restriction
10699 (widen)
10700 (goto-char marker)
10701 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10702 "\\(" org-angle-link-re "\\)\\|"
10703 "\\(" org-plain-link-re "\\)"))
10704 (cnt ?0)
10705 (in-emacs (if (integerp nth) nil nth))
10706 have-zero end links link c)
10707 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10708 (push (match-string 0 zero) links)
10709 (setq cnt (1- cnt) have-zero t))
10710 (save-excursion
10711 (org-back-to-heading t)
10712 (setq end (save-excursion (outline-next-heading) (point)))
10713 (while (re-search-forward re end t)
10714 (push (match-string 0) links))
10715 (setq links (org-uniquify (reverse links))))
10716 (cond
10717 ((null links)
10718 (message "No links"))
10719 ((equal (length links) 1)
10720 (setq link (car links)))
10721 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10722 (setq link (nth (if have-zero nth (1- nth)) links)))
10723 (t ; we have to select a link
10724 (save-excursion
10725 (save-window-excursion
10726 (delete-other-windows)
10727 (with-output-to-temp-buffer "*Select Link*"
10728 (mapc (lambda (l)
10729 (if (not (string-match org-bracket-link-regexp l))
10730 (princ (format "[%c] %s\n" (incf cnt)
10731 (org-remove-angle-brackets l)))
10732 (if (match-end 3)
10733 (princ (format "[%c] %s (%s)\n" (incf cnt)
10734 (match-string 3 l) (match-string 1 l)))
10735 (princ (format "[%c] %s\n" (incf cnt)
10736 (match-string 1 l))))))
10737 links))
10738 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10739 (message "Select link to open, RET to open all:")
10740 (setq c (read-char-exclusive))
10741 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10742 (when (equal c ?q) (user-error "Abort"))
10743 (if (equal c ?\C-m)
10744 (setq link links)
10745 (setq nth (- c ?0))
10746 (if have-zero (setq nth (1+ nth)))
10747 (unless (and (integerp nth) (>= (length links) nth))
10748 (user-error "Invalid link selection"))
10749 (setq link (nth (1- nth) links)))))
10750 (cons link end))))))
10752 ;; TODO: These functions are deprecated since `org-open-at-point'
10753 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10754 (defun org-open-file-with-system (path)
10755 "Open file at PATH using the system way of opening it."
10756 (org-open-file path 'system))
10757 (defun org-open-file-with-emacs (path)
10758 "Open file at PATH in Emacs."
10759 (org-open-file path 'emacs))
10762 ;;; File search
10764 (defvar org-create-file-search-functions nil
10765 "List of functions to construct the right search string for a file link.
10766 These functions are called in turn with point at the location to
10767 which the link should point.
10769 A function in the hook should first test if it would like to
10770 handle this file type, for example by checking the `major-mode'
10771 or the file extension. If it decides not to handle this file, it
10772 should just return nil to give other functions a chance. If it
10773 does handle the file, it must return the search string to be used
10774 when following the link. The search string will be part of the
10775 file link, given after a double colon, and `org-open-at-point'
10776 will automatically search for it. If special measures must be
10777 taken to make the search successful, another function should be
10778 added to the companion hook `org-execute-file-search-functions',
10779 which see.
10781 A function in this hook may also use `setq' to set the variable
10782 `description' to provide a suggestion for the descriptive text to
10783 be used for this link when it gets inserted into an Org-mode
10784 buffer with \\[org-insert-link].")
10786 (defvar org-execute-file-search-functions nil
10787 "List of functions to execute a file search triggered by a link.
10789 Functions added to this hook must accept a single argument, the
10790 search string that was part of the file link, the part after the
10791 double colon. The function must first check if it would like to
10792 handle this search, for example by checking the `major-mode' or
10793 the file extension. If it decides not to handle this search, it
10794 should just return nil to give other functions a chance. If it
10795 does handle the search, it must return a non-nil value to keep
10796 other functions from trying.
10798 Each function can access the current prefix argument through the
10799 variable `current-prefix-arg'. Note that a single prefix is used
10800 to force opening a link in Emacs, so it may be good to only use a
10801 numeric or double prefix to guide the search function.
10803 In case this is needed, a function in this hook can also restore
10804 the window configuration before `org-open-at-point' was called using:
10806 (set-window-configuration org-window-config-before-follow-link)")
10808 (defun org-link-search (s &optional type avoid-pos stealth)
10809 "Search for a link search option.
10810 If S is surrounded by forward slashes, it is interpreted as a
10811 regular expression. In org-mode files, this will create an `org-occur'
10812 sparse tree. In ordinary files, `occur' will be used to list matches.
10813 If the current buffer is in `dired-mode', grep will be used to search
10814 in all files. If AVOID-POS is given, ignore matches near that position.
10816 When optional argument STEALTH is non-nil, do not modify
10817 visibility around point, thus ignoring
10818 `org-show-hierarchy-above', `org-show-following-heading' and
10819 `org-show-siblings' variables."
10820 (let ((case-fold-search t)
10821 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10822 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10823 (append '(("") (" ") ("\t") ("\n"))
10824 org-emphasis-alist)
10825 "\\|") "\\)"))
10826 (pos (point))
10827 (pre nil) (post nil)
10828 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10829 (cond
10830 ;; First check if there are any special search functions
10831 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10832 ;; Now try the builtin stuff
10833 ((and (equal (string-to-char s0) ?#)
10834 (> (length s0) 1)
10835 (save-excursion
10836 (goto-char (point-min))
10837 (and
10838 (re-search-forward
10839 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10840 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10841 (setq type 'dedicated
10842 pos (match-beginning 0))))
10843 ;; There is an exact target for this
10844 (goto-char pos)
10845 (org-back-to-heading t)))
10846 ((save-excursion
10847 (goto-char (point-min))
10848 (and
10849 (re-search-forward
10850 (concat "<<" (regexp-quote s0) ">>") nil t)
10851 (setq type 'dedicated
10852 pos (match-beginning 0))))
10853 ;; There is an exact target for this
10854 (goto-char pos))
10855 ((save-excursion
10856 (goto-char (point-min))
10857 (and
10858 (re-search-forward
10859 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10860 (setq type 'dedicated pos (match-beginning 0))))
10861 ;; Found an element with a matching #+name affiliated keyword.
10862 (goto-char pos))
10863 ((and (string-match "^(\\(.*\\))$" s0)
10864 (save-excursion
10865 (goto-char (point-min))
10866 (and
10867 (re-search-forward
10868 (concat "[^[]" (regexp-quote
10869 (format org-coderef-label-format
10870 (match-string 1 s0))))
10871 nil t)
10872 (setq type 'dedicated
10873 pos (1+ (match-beginning 0))))))
10874 ;; There is a coderef target for this
10875 (goto-char pos))
10876 ((string-match "^/\\(.*\\)/$" s)
10877 ;; A regular expression
10878 (cond
10879 ((derived-mode-p 'org-mode)
10880 (org-occur (match-string 1 s)))
10881 (t (org-do-occur (match-string 1 s)))))
10882 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10883 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10884 (goto-char (point-min))
10885 (cond
10886 ((let (case-fold-search)
10887 (re-search-forward (format org-complex-heading-regexp-format
10888 (regexp-quote s))
10889 nil t))
10890 ;; OK, found a match
10891 (setq type 'dedicated)
10892 (goto-char (match-beginning 0)))
10893 ((and (not org-link-search-inhibit-query)
10894 (eq org-link-search-must-match-exact-headline 'query-to-create)
10895 (y-or-n-p "No match - create this as a new heading? "))
10896 (goto-char (point-max))
10897 (or (bolp) (newline))
10898 (insert "* " s "\n")
10899 (beginning-of-line 0))
10901 (goto-char pos)
10902 (error "No match"))))
10904 ;; A normal search string
10905 (when (equal (string-to-char s) ?*)
10906 ;; Anchor on headlines, post may include tags.
10907 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10908 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10909 s (substring s 1)))
10910 (remove-text-properties
10911 0 (length s)
10912 '(face nil mouse-face nil keymap nil fontified nil) s)
10913 ;; Make a series of regular expressions to find a match
10914 (setq words (org-split-string s "[ \n\r\t]+")
10916 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10917 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10918 "\\)" markers)
10919 re2a_ (concat "\\(" (mapconcat 'downcase words
10920 "[ \t\r\n]+") "\\)[ \t\r\n]")
10921 re2a (concat "[ \t\r\n]" re2a_)
10922 re4_ (concat "\\(" (mapconcat 'downcase words
10923 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10924 re4 (concat "[^a-zA-Z_]" re4_)
10926 re1 (concat pre re2 post)
10927 re3 (concat pre (if pre re4_ re4) post)
10928 re5 (concat pre ".*" re4)
10929 re2 (concat pre re2)
10930 re2a (concat pre (if pre re2a_ re2a))
10931 re4 (concat pre (if pre re4_ re4))
10932 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10933 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10934 re5 "\\)"))
10935 (cond
10936 ((eq type 'org-occur) (org-occur reall))
10937 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10938 (t (goto-char (point-min))
10939 (setq type 'fuzzy)
10940 (if (or (and (org-search-not-self 1 re0 nil t)
10941 (setq type 'dedicated))
10942 (org-search-not-self 1 re1 nil t)
10943 (org-search-not-self 1 re2 nil t)
10944 (org-search-not-self 1 re2a nil t)
10945 (org-search-not-self 1 re3 nil t)
10946 (org-search-not-self 1 re4 nil t)
10947 (org-search-not-self 1 re5 nil t))
10948 (goto-char (match-beginning 1))
10949 (goto-char pos)
10950 (error "No match"))))))
10951 (and (derived-mode-p 'org-mode)
10952 (not stealth)
10953 (org-show-context 'link-search))
10954 type))
10956 (defun org-search-not-self (group &rest args)
10957 "Execute `re-search-forward', but only accept matches that do not
10958 enclose the position of `org-open-link-marker'."
10959 (let ((m org-open-link-marker))
10960 (catch 'exit
10961 (while (apply 're-search-forward args)
10962 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10963 (goto-char (match-end group))
10964 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10965 (> (match-beginning 0) (marker-position m))
10966 (< (match-end 0) (marker-position m)))
10967 (save-match-data
10968 (or (not (org-in-regexp
10969 org-bracket-link-analytic-regexp 1))
10970 (not (match-end 4)) ; no description
10971 (and (<= (match-beginning 4) (point))
10972 (>= (match-end 4) (point))))))
10973 (throw 'exit (point))))))))
10975 (defun org-get-buffer-for-internal-link (buffer)
10976 "Return a buffer to be used for displaying the link target of internal links."
10977 (cond
10978 ((not org-display-internal-link-with-indirect-buffer)
10979 buffer)
10980 ((string-match "(Clone)$" (buffer-name buffer))
10981 (message "Buffer is already a clone, not making another one")
10982 ;; we also do not modify visibility in this case
10983 buffer)
10984 (t ; make a new indirect buffer for displaying the link
10985 (let* ((bn (buffer-name buffer))
10986 (ibn (concat bn "(Clone)"))
10987 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10988 (with-current-buffer ib (org-overview))
10989 ib))))
10991 (defun org-do-occur (regexp &optional cleanup)
10992 "Call the Emacs command `occur'.
10993 If CLEANUP is non-nil, remove the printout of the regular expression
10994 in the *Occur* buffer. This is useful if the regex is long and not useful
10995 to read."
10996 (occur regexp)
10997 (when cleanup
10998 (let ((cwin (selected-window)) win beg end)
10999 (when (setq win (get-buffer-window "*Occur*"))
11000 (select-window win))
11001 (goto-char (point-min))
11002 (when (re-search-forward "match[a-z]+" nil t)
11003 (setq beg (match-end 0))
11004 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11005 (setq end (1- (match-beginning 0)))))
11006 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11007 (goto-char (point-min))
11008 (select-window cwin))))
11010 ;;; The mark ring for links jumps
11012 (defvar org-mark-ring nil
11013 "Mark ring for positions before jumps in Org-mode.")
11014 (defvar org-mark-ring-last-goto nil
11015 "Last position in the mark ring used to go back.")
11016 ;; Fill and close the ring
11017 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11018 (loop for i from 1 to org-mark-ring-length do
11019 (push (make-marker) org-mark-ring))
11020 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11021 org-mark-ring)
11023 (defun org-mark-ring-push (&optional pos buffer)
11024 "Put the current position or POS into the mark ring and rotate it."
11025 (interactive)
11026 (setq pos (or pos (point)))
11027 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11028 (move-marker (car org-mark-ring)
11029 (or pos (point))
11030 (or buffer (current-buffer)))
11031 (message "%s"
11032 (substitute-command-keys
11033 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11035 (defun org-mark-ring-goto (&optional n)
11036 "Jump to the previous position in the mark ring.
11037 With prefix arg N, jump back that many stored positions. When
11038 called several times in succession, walk through the entire ring.
11039 Org-mode commands jumping to a different position in the current file,
11040 or to another Org-mode file, automatically push the old position
11041 onto the ring."
11042 (interactive "p")
11043 (let (p m)
11044 (if (eq last-command this-command)
11045 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11046 (setq p org-mark-ring))
11047 (setq org-mark-ring-last-goto p)
11048 (setq m (car p))
11049 (org-pop-to-buffer-same-window (marker-buffer m))
11050 (goto-char m)
11051 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11053 (defun org-remove-angle-brackets (s)
11054 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11055 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11057 (defun org-add-angle-brackets (s)
11058 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11059 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11061 (defun org-remove-double-quotes (s)
11062 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11063 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11066 ;;; Following specific links
11068 (defun org-follow-timestamp-link ()
11069 "Open an agenda view for the time-stamp date/range at point."
11070 (cond
11071 ((org-at-date-range-p t)
11072 (let ((org-agenda-start-on-weekday)
11073 (t1 (match-string 1))
11074 (t2 (match-string 2)) tt1 tt2)
11075 (setq tt1 (time-to-days (org-time-string-to-time t1))
11076 tt2 (time-to-days (org-time-string-to-time t2)))
11077 (let ((org-agenda-buffer-tmp-name
11078 (format "*Org Agenda(a:%s)"
11079 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11080 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11081 ((org-at-timestamp-p t)
11082 (let ((org-agenda-buffer-tmp-name
11083 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11084 (org-agenda-list nil (time-to-days (org-time-string-to-time
11085 (substring (match-string 1) 0 10)))
11086 1)))
11087 (t (error "This should not happen"))))
11090 ;;; Following file links
11091 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11092 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11093 (declare-function mailcap-mime-info
11094 "mailcap" (string &optional request no-decode))
11095 (defvar org-wait nil)
11096 (defun org-open-file (path &optional in-emacs line search)
11097 "Open the file at PATH.
11098 First, this expands any special file name abbreviations. Then the
11099 configuration variable `org-file-apps' is checked if it contains an
11100 entry for this file type, and if yes, the corresponding command is launched.
11102 If no application is found, Emacs simply visits the file.
11104 With optional prefix argument IN-EMACS, Emacs will visit the file.
11105 With a double \\[universal-argument] \\[universal-argument] \
11106 prefix arg, Org tries to avoid opening in Emacs
11107 and to use an external application to visit the file.
11109 Optional LINE specifies a line to go to, optional SEARCH a string
11110 to search for. If LINE or SEARCH is given, the file will be
11111 opened in Emacs, unless an entry from org-file-apps that makes
11112 use of groups in a regexp matches.
11114 If you want to change the way frames are used when following a
11115 link, please customize `org-link-frame-setup'.
11117 If the file does not exist, an error is thrown."
11118 (let* ((file (if (equal path "")
11119 buffer-file-name
11120 (substitute-in-file-name (expand-file-name path))))
11121 (file-apps (append org-file-apps (org-default-apps)))
11122 (apps (org-remove-if
11123 'org-file-apps-entry-match-against-dlink-p file-apps))
11124 (apps-dlink (org-remove-if-not
11125 'org-file-apps-entry-match-against-dlink-p file-apps))
11126 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11127 (dirp (if remp nil (file-directory-p file)))
11128 (file (if (and dirp org-open-directory-means-index-dot-org)
11129 (concat (file-name-as-directory file) "index.org")
11130 file))
11131 (a-m-a-p (assq 'auto-mode apps))
11132 (dfile (downcase file))
11133 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11134 (link (cond ((and (eq line nil)
11135 (eq search nil))
11136 file)
11137 (line
11138 (concat file "::" (number-to-string line)))
11139 (search
11140 (concat file "::" search))))
11141 (dlink (downcase link))
11142 (old-buffer (current-buffer))
11143 (old-pos (point))
11144 (old-mode major-mode)
11145 ext cmd link-match-data)
11146 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11147 (setq ext (match-string 1 dfile))
11148 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11149 (setq ext (match-string 1 dfile))))
11150 (cond
11151 ((member in-emacs '((16) system))
11152 (setq cmd (cdr (assoc 'system apps))))
11153 (in-emacs (setq cmd 'emacs))
11155 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11156 (and dirp (cdr (assoc 'directory apps)))
11157 ; first, try matching against apps-dlink
11158 ; if we get a match here, store the match data for later
11159 (let ((match (assoc-default dlink apps-dlink
11160 'string-match)))
11161 (if match
11162 (progn (setq link-match-data (match-data))
11163 match)
11164 (progn (setq in-emacs (or in-emacs line search))
11165 nil))) ; if we have no match in apps-dlink,
11166 ; always open the file in emacs if line or search
11167 ; is given (for backwards compatibility)
11168 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11169 'string-match)
11170 (cdr (assoc ext apps))
11171 (cdr (assoc t apps))))))
11172 (when (eq cmd 'system)
11173 (setq cmd (cdr (assoc 'system apps))))
11174 (when (eq cmd 'default)
11175 (setq cmd (cdr (assoc t apps))))
11176 (when (eq cmd 'mailcap)
11177 (require 'mailcap)
11178 (mailcap-parse-mailcaps)
11179 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11180 (command (mailcap-mime-info mime-type)))
11181 (if (stringp command)
11182 (setq cmd command)
11183 (setq cmd 'emacs))))
11184 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11185 (not (file-exists-p file))
11186 (not org-open-non-existing-files))
11187 (user-error "No such file: %s" file))
11188 (cond
11189 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11190 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11191 (while (string-match "['\"]%s['\"]" cmd)
11192 (setq cmd (replace-match "%s" t t cmd)))
11193 (while (string-match "%s" cmd)
11194 (setq cmd (replace-match
11195 (save-match-data
11196 (shell-quote-argument
11197 (convert-standard-filename file)))
11198 t t cmd)))
11200 ;; Replace "%1", "%2" etc. in command with group matches from regex
11201 (save-match-data
11202 (let ((match-index 1)
11203 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11204 (set-match-data link-match-data)
11205 (while (<= match-index number-of-groups)
11206 (let ((regex (concat "%" (number-to-string match-index)))
11207 (replace-with (match-string match-index dlink)))
11208 (while (string-match regex cmd)
11209 (setq cmd (replace-match replace-with t t cmd))))
11210 (setq match-index (+ match-index 1)))))
11212 (save-window-excursion
11213 (message "Running %s...done" cmd)
11214 (start-process-shell-command cmd nil cmd)
11215 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11216 ((or (stringp cmd)
11217 (eq cmd 'emacs))
11218 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11219 (widen)
11220 (if line (progn (org-goto-line line)
11221 (if (derived-mode-p 'org-mode)
11222 (org-reveal)))
11223 (if search (org-link-search search))))
11224 ((consp cmd)
11225 (let ((file (convert-standard-filename file)))
11226 (save-match-data
11227 (set-match-data link-match-data)
11228 (eval cmd))))
11229 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11230 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11231 (or (not (equal old-buffer (current-buffer)))
11232 (not (equal old-pos (point))))
11233 (org-mark-ring-push old-pos old-buffer))))
11235 (defun org-file-apps-entry-match-against-dlink-p (entry)
11236 "This function returns non-nil if `entry' uses a regular
11237 expression which should be matched against the whole link by
11238 org-open-file.
11240 It assumes that is the case when the entry uses a regular
11241 expression which has at least one grouping construct and the
11242 action is either a lisp form or a command string containing
11243 '%1', i.e. using at least one subexpression match as a
11244 parameter."
11245 (let ((selector (car entry))
11246 (action (cdr entry)))
11247 (if (stringp selector)
11248 (and (> (regexp-opt-depth selector) 0)
11249 (or (and (stringp action)
11250 (string-match "%[0-9]" action))
11251 (consp action)))
11252 nil)))
11254 (defun org-default-apps ()
11255 "Return the default applications for this operating system."
11256 (cond
11257 ((eq system-type 'darwin)
11258 org-file-apps-defaults-macosx)
11259 ((eq system-type 'windows-nt)
11260 org-file-apps-defaults-windowsnt)
11261 (t org-file-apps-defaults-gnu)))
11263 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11264 "Convert extensions to regular expressions in the cars of LIST.
11265 Also, weed out any non-string entries, because the return value is used
11266 only for regexp matching.
11267 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11268 point to the symbol `emacs', indicating that the file should
11269 be opened in Emacs."
11270 (append
11271 (delq nil
11272 (mapcar (lambda (x)
11273 (if (not (stringp (car x)))
11275 (if (string-match "\\W" (car x))
11277 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11278 list))
11279 (if add-auto-mode
11280 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11282 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11283 (defun org-file-remote-p (file)
11284 "Test whether FILE specifies a location on a remote system.
11285 Return non-nil if the location is indeed remote.
11287 For example, the filename \"/user@host:/foo\" specifies a location
11288 on the system \"/user@host:\"."
11289 (cond ((fboundp 'file-remote-p)
11290 (file-remote-p file))
11291 ((fboundp 'tramp-handle-file-remote-p)
11292 (tramp-handle-file-remote-p file))
11293 ((and (boundp 'ange-ftp-name-format)
11294 (string-match (car ange-ftp-name-format) file))
11295 t)))
11298 ;;;; Refiling
11300 (defun org-get-org-file ()
11301 "Read a filename, with default directory `org-directory'."
11302 (let ((default (or org-default-notes-file remember-data-file)))
11303 (read-file-name (format "File name [%s]: " default)
11304 (file-name-as-directory org-directory)
11305 default)))
11307 (defun org-notes-order-reversed-p ()
11308 "Check if the current file should receive notes in reversed order."
11309 (cond
11310 ((not org-reverse-note-order) nil)
11311 ((eq t org-reverse-note-order) t)
11312 ((not (listp org-reverse-note-order)) nil)
11313 (t (catch 'exit
11314 (let ((all org-reverse-note-order)
11315 entry)
11316 (while (setq entry (pop all))
11317 (if (string-match (car entry) buffer-file-name)
11318 (throw 'exit (cdr entry))))
11319 nil)))))
11321 (defvar org-refile-target-table nil
11322 "The list of refile targets, created by `org-refile'.")
11324 (defvar org-agenda-new-buffers nil
11325 "Buffers created to visit agenda files.")
11327 (defvar org-refile-cache nil
11328 "Cache for refile targets.")
11330 (defvar org-refile-markers nil
11331 "All the markers used for caching refile locations.")
11333 (defun org-refile-marker (pos)
11334 "Get a new refile marker, but only if caching is in use."
11335 (if (not org-refile-use-cache)
11337 (let ((m (make-marker)))
11338 (move-marker m pos)
11339 (push m org-refile-markers)
11340 m)))
11342 (defun org-refile-cache-clear ()
11343 "Clear the refile cache and disable all the markers."
11344 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11345 (setq org-refile-markers nil)
11346 (setq org-refile-cache nil)
11347 (message "Refile cache has been cleared"))
11349 (defun org-refile-cache-check-set (set)
11350 "Check if all the markers in the cache still have live buffers."
11351 (let (marker)
11352 (catch 'exit
11353 (while (and set (setq marker (nth 3 (pop set))))
11354 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11355 (when (and marker (null (marker-buffer marker)))
11356 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11357 (sit-for 3)
11358 (throw 'exit nil)))
11359 t)))
11361 (defun org-refile-cache-put (set &rest identifiers)
11362 "Push the refile targets SET into the cache, under IDENTIFIERS."
11363 (let* ((key (sha1 (prin1-to-string identifiers)))
11364 (entry (assoc key org-refile-cache)))
11365 (if entry
11366 (setcdr entry set)
11367 (push (cons key set) org-refile-cache))))
11369 (defun org-refile-cache-get (&rest identifiers)
11370 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11371 (cond
11372 ((not org-refile-cache) nil)
11373 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11375 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11376 org-refile-cache))))
11377 (and set (org-refile-cache-check-set set) set)))))
11379 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11380 "Produce a table with refile targets."
11381 (let ((case-fold-search nil)
11382 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11383 (entries (or org-refile-targets '((nil . (:level . 1)))))
11384 targets tgs txt re files f desc descre fast-path-p level pos0)
11385 (message "Getting targets...")
11386 (with-current-buffer (or default-buffer (current-buffer))
11387 (while (setq entry (pop entries))
11388 (setq files (car entry) desc (cdr entry))
11389 (setq fast-path-p nil)
11390 (cond
11391 ((null files) (setq files (list (current-buffer))))
11392 ((eq files 'org-agenda-files)
11393 (setq files (org-agenda-files 'unrestricted)))
11394 ((and (symbolp files) (fboundp files))
11395 (setq files (funcall files)))
11396 ((and (symbolp files) (boundp files))
11397 (setq files (symbol-value files))))
11398 (if (stringp files) (setq files (list files)))
11399 (cond
11400 ((eq (car desc) :tag)
11401 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11402 ((eq (car desc) :todo)
11403 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11404 ((eq (car desc) :regexp)
11405 (setq descre (cdr desc)))
11406 ((eq (car desc) :level)
11407 (setq descre (concat "^\\*\\{" (number-to-string
11408 (if org-odd-levels-only
11409 (1- (* 2 (cdr desc)))
11410 (cdr desc)))
11411 "\\}[ \t]")))
11412 ((eq (car desc) :maxlevel)
11413 (setq fast-path-p t)
11414 (setq descre (concat "^\\*\\{1," (number-to-string
11415 (if org-odd-levels-only
11416 (1- (* 2 (cdr desc)))
11417 (cdr desc)))
11418 "\\}[ \t]")))
11419 (t (error "Bad refiling target description %s" desc)))
11420 (while (setq f (pop files))
11421 (with-current-buffer
11422 (if (bufferp f) f (org-get-agenda-file-buffer f))
11424 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11425 (progn
11426 (if (bufferp f) (setq f (buffer-file-name
11427 (buffer-base-buffer f))))
11428 (setq f (and f (expand-file-name f)))
11429 (if (eq org-refile-use-outline-path 'file)
11430 (push (list (file-name-nondirectory f) f nil nil) tgs))
11431 (save-excursion
11432 (save-restriction
11433 (widen)
11434 (goto-char (point-min))
11435 (while (re-search-forward descre nil t)
11436 (goto-char (setq pos0 (point-at-bol)))
11437 (catch 'next
11438 (when org-refile-target-verify-function
11439 (save-match-data
11440 (or (funcall org-refile-target-verify-function)
11441 (throw 'next t))))
11442 (when (and (looking-at org-complex-heading-regexp)
11443 (not (member (match-string 4) excluded-entries))
11444 (match-string 4))
11445 (setq level (org-reduced-level
11446 (- (match-end 1) (match-beginning 1)))
11447 txt (org-link-display-format (match-string 4))
11448 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11449 re (format org-complex-heading-regexp-format
11450 (regexp-quote (match-string 4))))
11451 (when org-refile-use-outline-path
11452 (setq txt (mapconcat
11453 'org-protect-slash
11454 (append
11455 (if (eq org-refile-use-outline-path
11456 'file)
11457 (list (file-name-nondirectory
11458 (buffer-file-name
11459 (buffer-base-buffer))))
11460 (if (eq org-refile-use-outline-path
11461 'full-file-path)
11462 (list (buffer-file-name
11463 (buffer-base-buffer)))))
11464 (org-get-outline-path fast-path-p
11465 level txt)
11466 (list txt))
11467 "/")))
11468 (push (list txt f re (org-refile-marker (point)))
11469 tgs)))
11470 (when (= (point) pos0)
11471 ;; verification function has not moved point
11472 (goto-char (point-at-eol))))))))
11473 (when org-refile-use-cache
11474 (org-refile-cache-put tgs (buffer-file-name) descre))
11475 (setq targets (append tgs targets))))))
11476 (message "Getting targets...done")
11477 (nreverse targets)))
11479 (defun org-protect-slash (s)
11480 (while (string-match "/" s)
11481 (setq s (replace-match "\\" t t s)))
11484 (defvar org-olpa (make-vector 20 nil))
11486 (defun org-get-outline-path (&optional fastp level heading)
11487 "Return the outline path to the current entry, as a list.
11489 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11490 routine which makes outline path derivations for an entire file,
11491 avoiding backtracing. Refile target collection makes use of that."
11492 (if fastp
11493 (progn
11494 (if (> level 19)
11495 (error "Outline path failure, more than 19 levels"))
11496 (loop for i from level upto 19 do
11497 (aset org-olpa i nil))
11498 (prog1
11499 (delq nil (append org-olpa nil))
11500 (aset org-olpa level heading)))
11501 (let (rtn case-fold-search)
11502 (save-excursion
11503 (save-restriction
11504 (widen)
11505 (while (org-up-heading-safe)
11506 (when (looking-at org-complex-heading-regexp)
11507 (push (org-trim
11508 (replace-regexp-in-string
11509 ;; Remove statistical/checkboxes cookies
11510 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11511 (org-match-string-no-properties 4)))
11512 rtn)))
11513 rtn)))))
11515 (defun org-format-outline-path (path &optional width prefix separator)
11516 "Format the outline path PATH for display.
11517 WIDTH is the maximum number of characters that is available.
11518 PREFIX is a prefix to be included in the returned string,
11519 such as the file name.
11520 SEPARATOR is inserted between the different parts of the path,
11521 the default is \"/\"."
11522 (setq width (or width 79))
11523 (if prefix (setq width (- width (length prefix))))
11524 (if (not path)
11525 (or prefix "")
11526 (let* ((nsteps (length path))
11527 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11528 (maxwidth (if (<= total-width width)
11529 10000 ;; everything fits
11530 ;; we need to shorten the level headings
11531 (/ (- width nsteps) nsteps)))
11532 (org-odd-levels-only nil)
11533 (n 0)
11534 (total (1+ (length prefix))))
11535 (setq maxwidth (max maxwidth 10))
11536 (concat prefix
11537 (if prefix (or separator "/"))
11538 (mapconcat
11539 (lambda (h)
11540 (setq n (1+ n))
11541 (if (and (= n nsteps) (< maxwidth 10000))
11542 (setq maxwidth (- total-width total)))
11543 (if (< (length h) maxwidth)
11544 (progn (setq total (+ total (length h) 1)) h)
11545 (setq h (substring h 0 (- maxwidth 2))
11546 total (+ total maxwidth 1))
11547 (if (string-match "[ \t]+\\'" h)
11548 (setq h (substring h 0 (match-beginning 0))))
11549 (setq h (concat h "..")))
11550 (org-add-props h nil 'face
11551 (nth (% (1- n) org-n-level-faces)
11552 org-level-faces))
11554 path (or separator "/"))))))
11556 (defun org-display-outline-path (&optional file current separator just-return-string)
11557 "Display the current outline path in the echo area.
11559 If FILE is non-nil, prepend the output with the file name.
11560 If CURRENT is non-nil, append the current heading to the output.
11561 SEPARATOR is passed through to `org-format-outline-path'. It separates
11562 the different parts of the path and defaults to \"/\".
11563 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11564 (interactive "P")
11565 (let* (case-fold-search
11566 (bfn (buffer-file-name (buffer-base-buffer)))
11567 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11568 res)
11569 (if current (setq path (append path
11570 (save-excursion
11571 (org-back-to-heading t)
11572 (if (looking-at org-complex-heading-regexp)
11573 (list (match-string 4)))))))
11574 (setq res
11575 (org-format-outline-path
11576 path
11577 (1- (frame-width))
11578 (and file bfn (concat (file-name-nondirectory bfn) separator))
11579 separator))
11580 (if just-return-string
11581 (org-no-properties res)
11582 (org-unlogged-message "%s" res))))
11584 (defvar org-refile-history nil
11585 "History for refiling operations.")
11587 (defvar org-after-refile-insert-hook nil
11588 "Hook run after `org-refile' has inserted its stuff at the new location.
11589 Note that this is still *before* the stuff will be removed from
11590 the *old* location.")
11592 (defvar org-capture-last-stored-marker)
11593 (defvar org-refile-keep nil
11594 "Non-nil means `org-refile' will copy instead of refile.")
11596 (defun org-copy ()
11597 "Like `org-refile', but copy."
11598 (interactive)
11599 (let ((org-refile-keep t))
11600 (funcall 'org-refile nil nil nil "Copy")))
11602 (defun org-refile (&optional arg default-buffer rfloc msg)
11603 "Move the entry or entries at point to another heading.
11604 The list of target headings is compiled using the information in
11605 `org-refile-targets', which see.
11607 At the target location, the entry is filed as a subitem of the
11608 target heading. Depending on `org-reverse-note-order', the new
11609 subitem will either be the first or the last subitem.
11611 If there is an active region, all entries in that region will be
11612 refiled. However, the region must fulfill the requirement that
11613 the first heading sets the top-level of the moved text.
11615 With prefix arg ARG, the command will only visit the target
11616 location and not actually move anything.
11618 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11619 refiling operation has put the subtree.
11621 With a numeric prefix argument of `2', refile to the running clock.
11623 With a numeric prefix argument of `3', emulate `org-refile-keep'
11624 being set to `t' and copy to the target location, don't move it.
11625 Beware that keeping refiled entries may result in duplicated ID
11626 properties.
11628 RFLOC can be a refile location obtained in a different way.
11630 MSG is a string to replace \"Refile\" in the default prompt with
11631 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11633 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11635 If you are using target caching (see `org-refile-use-cache'), you
11636 have to clear the target cache in order to find new targets.
11637 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11638 prefix argument (`C-u C-u C-u C-c C-w')."
11639 (interactive "P")
11640 (if (member arg '(0 (64)))
11641 (org-refile-cache-clear)
11642 (let* ((actionmsg (cond (msg msg)
11643 ((equal arg 3) "Refile (and keep)")
11644 (t "Refile")))
11645 (cbuf (current-buffer))
11646 (regionp (org-region-active-p))
11647 (region-start (and regionp (region-beginning)))
11648 (region-end (and regionp (region-end)))
11649 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11650 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11651 pos it nbuf file re level reversed)
11652 (setq last-command nil)
11653 (when regionp
11654 (goto-char region-start)
11655 (or (bolp) (goto-char (point-at-bol)))
11656 (setq region-start (point))
11657 (unless (or (org-kill-is-subtree-p
11658 (buffer-substring region-start region-end))
11659 (prog1 org-refile-active-region-within-subtree
11660 (let ((s (point-at-eol)))
11661 (org-toggle-heading)
11662 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11663 (user-error "The region is not a (sequence of) subtree(s)")))
11664 (if (equal arg '(16))
11665 (org-refile-goto-last-stored)
11666 (when (or
11667 (and (equal arg 2)
11668 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11669 (prog1
11670 (setq it (list (or org-clock-heading "running clock")
11671 (buffer-file-name
11672 (marker-buffer org-clock-hd-marker))
11674 (marker-position org-clock-hd-marker)))
11675 (setq arg nil)))
11676 (setq it (or rfloc
11677 (let (heading-text)
11678 (save-excursion
11679 (unless (and arg (listp arg))
11680 (org-back-to-heading t)
11681 (setq heading-text
11682 (replace-regexp-in-string
11683 org-bracket-link-regexp
11684 "\\3"
11685 (nth 4 (org-heading-components)))))
11686 (org-refile-get-location
11687 (cond ((and arg (listp arg)) "Goto")
11688 (regionp (concat actionmsg " region to"))
11689 (t (concat actionmsg " subtree \""
11690 heading-text "\" to")))
11691 default-buffer
11692 (and (not (equal '(4) arg))
11693 org-refile-allow-creating-parent-nodes)
11694 arg))))))
11695 (setq file (nth 1 it)
11696 re (nth 2 it)
11697 pos (nth 3 it))
11698 (if (and (not arg)
11700 (equal (buffer-file-name) file)
11701 (if regionp
11702 (and (>= pos region-start)
11703 (<= pos region-end))
11704 (and (>= pos (point))
11705 (< pos (save-excursion
11706 (org-end-of-subtree t t))))))
11707 (error "Cannot refile to position inside the tree or region"))
11708 (setq nbuf (or (find-buffer-visiting file)
11709 (find-file-noselect file)))
11710 (if (and arg (not (equal arg 3)))
11711 (progn
11712 (org-pop-to-buffer-same-window nbuf)
11713 (goto-char pos)
11714 (org-show-context 'org-goto))
11715 (if regionp
11716 (progn
11717 (org-kill-new (buffer-substring region-start region-end))
11718 (org-save-markers-in-region region-start region-end))
11719 (org-copy-subtree 1 nil t))
11720 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11721 (find-file-noselect file)))
11722 (setq reversed (org-notes-order-reversed-p))
11723 (save-excursion
11724 (save-restriction
11725 (widen)
11726 (if pos
11727 (progn
11728 (goto-char pos)
11729 (looking-at org-outline-regexp)
11730 (setq level (org-get-valid-level (funcall outline-level) 1))
11731 (goto-char
11732 (if reversed
11733 (or (outline-next-heading) (point-max))
11734 (or (save-excursion (org-get-next-sibling))
11735 (org-end-of-subtree t t)
11736 (point-max)))))
11737 (setq level 1)
11738 (if (not reversed)
11739 (goto-char (point-max))
11740 (goto-char (point-min))
11741 (or (outline-next-heading) (goto-char (point-max)))))
11742 (if (not (bolp)) (newline))
11743 (org-paste-subtree level)
11744 (when org-log-refile
11745 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11746 (unless (eq org-log-refile 'note)
11747 (save-excursion (org-add-log-note))))
11748 (and org-auto-align-tags
11749 (let ((org-loop-over-headlines-in-active-region nil))
11750 (org-set-tags nil t)))
11751 (let ((bookmark-name (plist-get org-bookmark-names-plist
11752 :last-refile)))
11753 (when bookmark-name
11754 (with-demoted-errors
11755 (bookmark-set bookmark-name))))
11756 ;; If we are refiling for capture, make sure that the
11757 ;; last-capture pointers point here
11758 (when (org-bound-and-true-p org-refile-for-capture)
11759 (let ((bookmark-name (plist-get org-bookmark-names-plist
11760 :last-capture-marker)))
11761 (when bookmark-name
11762 (with-demoted-errors
11763 (bookmark-set bookmark-name))))
11764 (move-marker org-capture-last-stored-marker (point)))
11765 (if (fboundp 'deactivate-mark) (deactivate-mark))
11766 (run-hooks 'org-after-refile-insert-hook))))
11767 (unless org-refile-keep
11768 (if regionp
11769 (delete-region (point) (+ (point) (- region-end region-start)))
11770 (delete-region
11771 (and (org-back-to-heading t) (point))
11772 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11773 (when (featurep 'org-inlinetask)
11774 (org-inlinetask-remove-END-maybe))
11775 (setq org-markers-to-move nil)
11776 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11778 (defun org-refile-goto-last-stored ()
11779 "Go to the location where the last refile was stored."
11780 (interactive)
11781 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11782 (message "This is the location of the last refile"))
11784 (defun org-refile--get-location (refloc tbl)
11785 "When user refile to REFLOC, find the associated target in TBL.
11786 Also check `org-refile-target-table'."
11787 (car (delq
11789 (mapcar
11790 (lambda (r) (or (assoc r tbl)
11791 (assoc r org-refile-target-table)))
11792 (list (replace-regexp-in-string "/$" "" refloc)
11793 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11795 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11796 no-exclude)
11797 "Prompt the user for a refile location, using PROMPT.
11798 PROMPT should not be suffixed with a colon and a space, because
11799 this function appends the default value from
11800 `org-refile-history' automatically, if that is not empty.
11801 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11802 this is used for the GOTO interface."
11803 (let ((org-refile-targets org-refile-targets)
11804 (org-refile-use-outline-path org-refile-use-outline-path)
11805 excluded-entries)
11806 (when (and (derived-mode-p 'org-mode)
11807 (not org-refile-use-cache)
11808 (not no-exclude))
11809 (org-map-tree
11810 (lambda()
11811 (setq excluded-entries
11812 (append excluded-entries (list (org-get-heading t t)))))))
11813 (setq org-refile-target-table
11814 (org-refile-get-targets default-buffer excluded-entries)))
11815 (unless org-refile-target-table
11816 (user-error "No refile targets"))
11817 (let* ((cbuf (current-buffer))
11818 (partial-completion-mode nil)
11819 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11820 (cfunc (if (and org-refile-use-outline-path
11821 org-outline-path-complete-in-steps)
11822 'org-olpath-completing-read
11823 'org-icompleting-read))
11824 (extra (if org-refile-use-outline-path "/" ""))
11825 (cbnex (concat (buffer-name) extra))
11826 (filename (and cfn (expand-file-name cfn)))
11827 (tbl (mapcar
11828 (lambda (x)
11829 (if (and (not (member org-refile-use-outline-path
11830 '(file full-file-path)))
11831 (not (equal filename (nth 1 x))))
11832 (cons (concat (car x) extra " ("
11833 (file-name-nondirectory (nth 1 x)) ")")
11834 (cdr x))
11835 (cons (concat (car x) extra) (cdr x))))
11836 org-refile-target-table))
11837 (completion-ignore-case t)
11838 cdef
11839 (prompt (concat prompt
11840 (or (and (car org-refile-history)
11841 (concat " (default " (car org-refile-history) ")"))
11842 (and (assoc cbnex tbl) (setq cdef cbnex)
11843 (concat " (default " cbnex ")"))) ": "))
11844 pa answ parent-target child parent old-hist)
11845 (setq old-hist org-refile-history)
11846 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11847 nil 'org-refile-history (or cdef (car org-refile-history))))
11848 (if (setq pa (org-refile--get-location answ tbl))
11849 (progn
11850 (org-refile-check-position pa)
11851 (when (or (not org-refile-history)
11852 (not (eq old-hist org-refile-history))
11853 (not (equal (car pa) (car org-refile-history))))
11854 (setq org-refile-history
11855 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11856 org-refile-history
11857 (cdr org-refile-history))))
11858 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11859 (pop org-refile-history)))
11861 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11862 (progn
11863 (setq parent (match-string 1 answ)
11864 child (match-string 2 answ))
11865 (setq parent-target (org-refile--get-location parent tbl))
11866 (when (and parent-target
11867 (or (eq new-nodes t)
11868 (and (eq new-nodes 'confirm)
11869 (y-or-n-p (format "Create new node \"%s\"? "
11870 child)))))
11871 (org-refile-new-child parent-target child)))
11872 (user-error "Invalid target location")))))
11874 (declare-function org-string-nw-p "org-macs" (s))
11875 (defun org-refile-check-position (refile-pointer)
11876 "Check if the refile pointer matches the headline to which it points."
11877 (let* ((file (nth 1 refile-pointer))
11878 (re (nth 2 refile-pointer))
11879 (pos (nth 3 refile-pointer))
11880 buffer)
11881 (if (and (not (markerp pos)) (not file))
11882 (if file
11883 (user-error "Please save the buffer to a file before refiling")
11884 (user-error "Please indicate a target file in the refile path"))
11885 (when (org-string-nw-p re)
11886 (setq buffer (if (markerp pos)
11887 (marker-buffer pos)
11888 (or (find-buffer-visiting file)
11889 (find-file-noselect file))))
11890 (with-current-buffer buffer
11891 (save-excursion
11892 (save-restriction
11893 (widen)
11894 (goto-char pos)
11895 (beginning-of-line 1)
11896 (unless (org-looking-at-p re)
11897 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11899 (defun org-refile-new-child (parent-target child)
11900 "Use refile target PARENT-TARGET to add new CHILD below it."
11901 (unless parent-target
11902 (error "Cannot find parent for new node"))
11903 (let ((file (nth 1 parent-target))
11904 (pos (nth 3 parent-target))
11905 level)
11906 (with-current-buffer (or (find-buffer-visiting file)
11907 (find-file-noselect file))
11908 (save-excursion
11909 (save-restriction
11910 (widen)
11911 (if pos
11912 (goto-char pos)
11913 (goto-char (point-max))
11914 (if (not (bolp)) (newline)))
11915 (when (looking-at org-outline-regexp)
11916 (setq level (funcall outline-level))
11917 (org-end-of-subtree t t))
11918 (org-back-over-empty-lines)
11919 (insert "\n" (make-string
11920 (if pos (org-get-valid-level level 1) 1) ?*)
11921 " " child "\n")
11922 (beginning-of-line 0)
11923 (list (concat (car parent-target) "/" child) file "" (point)))))))
11925 (defun org-olpath-completing-read (prompt collection &rest args)
11926 "Read an outline path like a file name."
11927 (let ((thetable collection)
11928 (org-completion-use-ido nil) ; does not work with ido.
11929 (org-completion-use-iswitchb nil)) ; or iswitchb
11930 (apply
11931 'org-icompleting-read prompt
11932 (lambda (string predicate &optional flag)
11933 (let (rtn r f (l (length string)))
11934 (cond
11935 ((eq flag nil)
11936 ;; try completion
11937 (try-completion string thetable))
11938 ((eq flag t)
11939 ;; all-completions
11940 (setq rtn (all-completions string thetable predicate))
11941 (mapcar
11942 (lambda (x)
11943 (setq r (substring x l))
11944 (if (string-match " ([^)]*)$" x)
11945 (setq f (match-string 0 x))
11946 (setq f ""))
11947 (if (string-match "/" r)
11948 (concat string (substring r 0 (match-end 0)) f)
11950 rtn))
11951 ((eq flag 'lambda)
11952 ;; exact match?
11953 (assoc string thetable)))))
11954 args)))
11956 ;;;; Dynamic blocks
11958 (defun org-find-dblock (name)
11959 "Find the first dynamic block with name NAME in the buffer.
11960 If not found, stay at current position and return nil."
11961 (let ((case-fold-search t) pos)
11962 (save-excursion
11963 (goto-char (point-min))
11964 (setq pos (and (re-search-forward
11965 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11966 (match-beginning 0))))
11967 (if pos (goto-char pos))
11968 pos))
11970 (defun org-create-dblock (plist)
11971 "Create a dynamic block section, with parameters taken from PLIST.
11972 PLIST must contain a :name entry which is used as the name of the block."
11973 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11974 (end-of-line 1)
11975 (newline))
11976 (let ((col (current-column))
11977 (name (plist-get plist :name)))
11978 (insert "#+BEGIN: " name)
11979 (while plist
11980 (if (eq (car plist) :name)
11981 (setq plist (cddr plist))
11982 (insert " " (prin1-to-string (pop plist)))))
11983 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11984 (beginning-of-line -2)))
11986 (defun org-prepare-dblock ()
11987 "Prepare dynamic block for refresh.
11988 This empties the block, puts the cursor at the insert position and returns
11989 the property list including an extra property :name with the block name."
11990 (unless (looking-at org-dblock-start-re)
11991 (user-error "Not at a dynamic block"))
11992 (let* ((begdel (1+ (match-end 0)))
11993 (name (org-no-properties (match-string 1)))
11994 (params (append (list :name name)
11995 (read (concat "(" (match-string 3) ")")))))
11996 (save-excursion
11997 (beginning-of-line 1)
11998 (skip-chars-forward " \t")
11999 (setq params (plist-put params :indentation-column (current-column))))
12000 (unless (re-search-forward org-dblock-end-re nil t)
12001 (error "Dynamic block not terminated"))
12002 (setq params
12003 (append params
12004 (list :content (buffer-substring
12005 begdel (match-beginning 0)))))
12006 (delete-region begdel (match-beginning 0))
12007 (goto-char begdel)
12008 (open-line 1)
12009 params))
12011 (defun org-map-dblocks (&optional command)
12012 "Apply COMMAND to all dynamic blocks in the current buffer.
12013 If COMMAND is not given, use `org-update-dblock'."
12014 (let ((cmd (or command 'org-update-dblock)))
12015 (save-excursion
12016 (goto-char (point-min))
12017 (while (re-search-forward org-dblock-start-re nil t)
12018 (goto-char (match-beginning 0))
12019 (save-excursion
12020 (condition-case nil
12021 (funcall cmd)
12022 (error (message "Error during update of dynamic block"))))
12023 (unless (re-search-forward org-dblock-end-re nil t)
12024 (error "Dynamic block not terminated"))))))
12026 (defun org-dblock-update (&optional arg)
12027 "User command for updating dynamic blocks.
12028 Update the dynamic block at point. With prefix ARG, update all dynamic
12029 blocks in the buffer."
12030 (interactive "P")
12031 (if arg
12032 (org-update-all-dblocks)
12033 (or (looking-at org-dblock-start-re)
12034 (org-beginning-of-dblock))
12035 (org-update-dblock)))
12037 (defun org-update-dblock ()
12038 "Update the dynamic block at point.
12039 This means to empty the block, parse for parameters and then call
12040 the correct writing function."
12041 (interactive)
12042 (save-excursion
12043 (let* ((win (selected-window))
12044 (pos (point))
12045 (line (org-current-line))
12046 (params (org-prepare-dblock))
12047 (name (plist-get params :name))
12048 (indent (plist-get params :indentation-column))
12049 (cmd (intern (concat "org-dblock-write:" name))))
12050 (message "Updating dynamic block `%s' at line %d..." name line)
12051 (funcall cmd params)
12052 (message "Updating dynamic block `%s' at line %d...done" name line)
12053 (goto-char pos)
12054 (when (and indent (> indent 0))
12055 (setq indent (make-string indent ?\ ))
12056 (save-excursion
12057 (select-window win)
12058 (org-beginning-of-dblock)
12059 (forward-line 1)
12060 (while (not (looking-at org-dblock-end-re))
12061 (insert indent)
12062 (beginning-of-line 2))
12063 (when (looking-at org-dblock-end-re)
12064 (and (looking-at "[ \t]+")
12065 (replace-match ""))
12066 (insert indent)))))))
12068 (defun org-beginning-of-dblock ()
12069 "Find the beginning of the dynamic block at point.
12070 Error if there is no such block at point."
12071 (let ((pos (point))
12072 beg)
12073 (end-of-line 1)
12074 (if (and (re-search-backward org-dblock-start-re nil t)
12075 (setq beg (match-beginning 0))
12076 (re-search-forward org-dblock-end-re nil t)
12077 (> (match-end 0) pos))
12078 (goto-char beg)
12079 (goto-char pos)
12080 (error "Not in a dynamic block"))))
12082 (defun org-update-all-dblocks ()
12083 "Update all dynamic blocks in the buffer.
12084 This function can be used in a hook."
12085 (interactive)
12086 (when (derived-mode-p 'org-mode)
12087 (org-map-dblocks 'org-update-dblock)))
12090 ;;;; Completion
12092 (declare-function org-export-backend-name "org-export" (cl-x))
12093 (declare-function org-export-backend-options "org-export" (cl-x))
12094 (defun org-get-export-keywords ()
12095 "Return a list of all currently understood export keywords.
12096 Export keywords include options, block names, attributes and
12097 keywords relative to each registered export back-end."
12098 (let (keywords)
12099 (dolist (backend
12100 (org-bound-and-true-p org-export--registered-backends)
12101 (delq nil keywords))
12102 ;; Back-end name (for keywords, like #+LATEX:)
12103 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12104 (dolist (option-entry (org-export-backend-options backend))
12105 ;; Back-end options.
12106 (push (nth 1 option-entry) keywords)))))
12108 (defconst org-options-keywords
12109 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12110 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12111 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12112 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12113 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12115 (defcustom org-structure-template-alist
12116 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12117 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12118 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12119 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12120 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12121 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12122 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12123 "<literal style=\"latex\">\n?\n</literal>")
12124 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12125 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12126 "<literal style=\"html\">\n?\n</literal>")
12127 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12128 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12129 ("A" "#+ASCII: " "")
12130 ("i" "#+INDEX: ?" "#+INDEX: ?")
12131 ("I" "#+INCLUDE: %file ?"
12132 "<include file=%file markup=\"?\">"))
12133 "Structure completion elements.
12134 This is a list of abbreviation keys and values. The value gets inserted
12135 if you type `<' followed by the key and then press the completion key,
12136 usually `M-TAB'. %file will be replaced by a file name after prompting
12137 for the file using completion. The cursor will be placed at the position
12138 of the `?` in the template.
12139 There are two templates for each key, the first uses the original Org syntax,
12140 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12141 the default when the /org-mtags.el/ module has been loaded. See also the
12142 variable `org-mtags-prefer-muse-templates'."
12143 :group 'org-completion
12144 :type '(repeat
12145 (list
12146 (string :tag "Key")
12147 (string :tag "Template")
12148 (string :tag "Muse Template"))))
12150 (defun org-try-structure-completion ()
12151 "Try to complete a structure template before point.
12152 This looks for strings like \"<e\" on an otherwise empty line and
12153 expands them."
12154 (let ((l (buffer-substring (point-at-bol) (point)))
12156 (when (and (looking-at "[ \t]*$")
12157 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12158 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12159 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12160 (match-beginning 1)) a)
12161 t)))
12163 (defun org-complete-expand-structure-template (start cell)
12164 "Expand a structure template."
12165 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12166 (rpl (nth (if musep 2 1) cell))
12167 (ind ""))
12168 (delete-region start (point))
12169 (when (string-match "\\`[ \t]*#\\+" rpl)
12170 (cond
12171 ((bolp))
12172 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12173 (setq ind (buffer-substring (point-at-bol) (point))))
12174 (t (newline))))
12175 (setq start (point))
12176 (if (string-match "%file" rpl)
12177 (setq rpl (replace-match
12178 (concat
12179 "\""
12180 (save-match-data
12181 (abbreviate-file-name (read-file-name "Include file: ")))
12182 "\"")
12183 t t rpl)))
12184 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12185 (concat "\n" ind)))
12186 (insert rpl)
12187 (if (re-search-backward "\\?" start t) (delete-char 1))))
12189 ;;;; TODO, DEADLINE, Comments
12191 (defun org-toggle-comment ()
12192 "Change the COMMENT state of an entry."
12193 (interactive)
12194 (save-excursion
12195 (org-back-to-heading)
12196 (looking-at org-complex-heading-regexp)
12197 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12198 (skip-chars-forward " \t")
12199 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12200 (if (org-in-commented-heading-p t)
12201 (delete-region (point)
12202 (progn (search-forward " " (line-end-position) 'move)
12203 (skip-chars-forward " \t")
12204 (point)))
12205 (insert org-comment-string)
12206 (unless (eolp) (insert " ")))))
12208 (defvar org-last-todo-state-is-todo nil
12209 "This is non-nil when the last TODO state change led to a TODO state.
12210 If the last change removed the TODO tag or switched to DONE, then
12211 this is nil.")
12213 (defvar org-setting-tags nil) ; dynamically skipped
12215 (defvar org-todo-setup-filter-hook nil
12216 "Hook for functions that pre-filter todo specs.
12217 Each function takes a todo spec and returns either nil or the spec
12218 transformed into canonical form." )
12220 (defvar org-todo-get-default-hook nil
12221 "Hook for functions that get a default item for todo.
12222 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12223 nil or a string to be used for the todo mark." )
12225 (defvar org-agenda-headline-snapshot-before-repeat)
12227 (defun org-current-effective-time ()
12228 "Return current time adjusted for `org-extend-today-until' variable."
12229 (let* ((ct (org-current-time))
12230 (dct (decode-time ct))
12231 (ct1
12232 (cond
12233 (org-use-last-clock-out-time-as-effective-time
12234 (or (org-clock-get-last-clock-out-time) ct))
12235 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12236 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12237 (t ct))))
12238 ct1))
12240 (defun org-todo-yesterday (&optional arg)
12241 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12242 (interactive "P")
12243 (if (eq major-mode 'org-agenda-mode)
12244 (apply 'org-agenda-todo-yesterday arg)
12245 (let* ((hour (third (decode-time
12246 (org-current-time))))
12247 (org-extend-today-until (1+ hour)))
12248 (org-todo arg))))
12250 (defvar org-block-entry-blocking ""
12251 "First entry preventing the TODO state change.")
12253 (defun org-cancel-repeater ()
12254 "Cancel a repeater by setting its numeric value to zero."
12255 (interactive)
12256 (save-excursion
12257 (org-back-to-heading t)
12258 (let ((bound1 (point))
12259 (bound0 (save-excursion (outline-next-heading) (point))))
12260 (when (re-search-forward
12261 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12262 org-deadline-time-regexp "\\)\\|\\("
12263 org-ts-regexp "\\)")
12264 bound0 t)
12265 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12266 (replace-match "0" t nil nil 1))))))
12268 (defun org-todo (&optional arg)
12269 "Change the TODO state of an item.
12270 The state of an item is given by a keyword at the start of the heading,
12271 like
12272 *** TODO Write paper
12273 *** DONE Call mom
12275 The different keywords are specified in the variable `org-todo-keywords'.
12276 By default the available states are \"TODO\" and \"DONE\".
12277 So for this example: when the item starts with TODO, it is changed to DONE.
12278 When it starts with DONE, the DONE is removed. And when neither TODO nor
12279 DONE are present, add TODO at the beginning of the heading.
12281 With \\[universal-argument] prefix arg, use completion to determine the new \
12282 state.
12283 With numeric prefix arg, switch to that state.
12284 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12285 keywords (nextset).
12286 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12287 With a numeric prefix arg of 0, inhibit note taking for the change.
12288 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12290 When called through ELisp, arg is also interpreted in the following way:
12291 'none -> empty state
12292 \"\"(empty string) -> switch to empty state
12293 'done -> switch to DONE
12294 'nextset -> switch to the next set of keywords
12295 'previousset -> switch to the previous set of keywords
12296 \"WAITING\" -> switch to the specified keyword, but only if it
12297 really is a member of `org-todo-keywords'."
12298 (interactive "P")
12299 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12300 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12301 'region-start-level 'region))
12302 org-loop-over-headlines-in-active-region)
12303 (org-map-entries
12304 `(org-todo ,arg)
12305 org-loop-over-headlines-in-active-region
12306 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12307 (if (equal arg '(16)) (setq arg 'nextset))
12308 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12309 (let ((org-blocker-hook org-blocker-hook)
12310 commentp
12311 case-fold-search)
12312 (when (equal arg '(64))
12313 (setq arg nil org-blocker-hook nil))
12314 (when (and org-blocker-hook
12315 (or org-inhibit-blocking
12316 (org-entry-get nil "NOBLOCKING")))
12317 (setq org-blocker-hook nil))
12318 (save-excursion
12319 (catch 'exit
12320 (org-back-to-heading t)
12321 (when (org-in-commented-heading-p t)
12322 (org-toggle-comment)
12323 (setq commentp t))
12324 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12325 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12326 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12327 (let* ((match-data (match-data))
12328 (startpos (point-at-bol))
12329 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12330 (org-log-done org-log-done)
12331 (org-log-repeat org-log-repeat)
12332 (org-todo-log-states org-todo-log-states)
12333 (org-inhibit-logging
12334 (if (equal arg 0)
12335 (progn (setq arg nil) 'note) org-inhibit-logging))
12336 (this (match-string 1))
12337 (hl-pos (match-beginning 0))
12338 (head (org-get-todo-sequence-head this))
12339 (ass (assoc head org-todo-kwd-alist))
12340 (interpret (nth 1 ass))
12341 (done-word (nth 3 ass))
12342 (final-done-word (nth 4 ass))
12343 (org-last-state (or this ""))
12344 (completion-ignore-case t)
12345 (member (member this org-todo-keywords-1))
12346 (tail (cdr member))
12347 (org-state (cond
12348 ((and org-todo-key-trigger
12349 (or (and (equal arg '(4))
12350 (eq org-use-fast-todo-selection 'prefix))
12351 (and (not arg) org-use-fast-todo-selection
12352 (not (eq org-use-fast-todo-selection
12353 'prefix)))))
12354 ;; Use fast selection
12355 (org-fast-todo-selection))
12356 ((and (equal arg '(4))
12357 (or (not org-use-fast-todo-selection)
12358 (not org-todo-key-trigger)))
12359 ;; Read a state with completion
12360 (org-icompleting-read
12361 "State: " (mapcar 'list org-todo-keywords-1)
12362 nil t))
12363 ((eq arg 'right)
12364 (if this
12365 (if tail (car tail) nil)
12366 (car org-todo-keywords-1)))
12367 ((eq arg 'left)
12368 (if (equal member org-todo-keywords-1)
12370 (if this
12371 (nth (- (length org-todo-keywords-1)
12372 (length tail) 2)
12373 org-todo-keywords-1)
12374 (org-last org-todo-keywords-1))))
12375 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12376 (setq arg nil))) ; hack to fall back to cycling
12377 (arg
12378 ;; user or caller requests a specific state
12379 (cond
12380 ((equal arg "") nil)
12381 ((eq arg 'none) nil)
12382 ((eq arg 'done) (or done-word (car org-done-keywords)))
12383 ((eq arg 'nextset)
12384 (or (car (cdr (member head org-todo-heads)))
12385 (car org-todo-heads)))
12386 ((eq arg 'previousset)
12387 (let ((org-todo-heads (reverse org-todo-heads)))
12388 (or (car (cdr (member head org-todo-heads)))
12389 (car org-todo-heads))))
12390 ((car (member arg org-todo-keywords-1)))
12391 ((stringp arg)
12392 (user-error "State `%s' not valid in this file" arg))
12393 ((nth (1- (prefix-numeric-value arg))
12394 org-todo-keywords-1))))
12395 ((null member) (or head (car org-todo-keywords-1)))
12396 ((equal this final-done-word) nil) ;; -> make empty
12397 ((null tail) nil) ;; -> first entry
12398 ((memq interpret '(type priority))
12399 (if (eq this-command last-command)
12400 (car tail)
12401 (if (> (length tail) 0)
12402 (or done-word (car org-done-keywords))
12403 nil)))
12405 (car tail))))
12406 (org-state (or
12407 (run-hook-with-args-until-success
12408 'org-todo-get-default-hook org-state org-last-state)
12409 org-state))
12410 (next (if org-state (concat " " org-state " ") " "))
12411 (change-plist (list :type 'todo-state-change :from this :to org-state
12412 :position startpos))
12413 dolog now-done-p)
12414 (when org-blocker-hook
12415 (setq org-last-todo-state-is-todo
12416 (not (member this org-done-keywords)))
12417 (unless (save-excursion
12418 (save-match-data
12419 (org-with-wide-buffer
12420 (run-hook-with-args-until-failure
12421 'org-blocker-hook change-plist))))
12422 (if (org-called-interactively-p 'interactive)
12423 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12424 this org-state org-block-entry-blocking)
12425 ;; fail silently
12426 (message "TODO state change from %s to %s blocked (by \"%s\")"
12427 this org-state org-block-entry-blocking)
12428 (throw 'exit nil))))
12429 (store-match-data match-data)
12430 (replace-match next t t)
12431 (unless (pos-visible-in-window-p hl-pos)
12432 (message "TODO state changed to %s" (org-trim next)))
12433 (unless head
12434 (setq head (org-get-todo-sequence-head org-state)
12435 ass (assoc head org-todo-kwd-alist)
12436 interpret (nth 1 ass)
12437 done-word (nth 3 ass)
12438 final-done-word (nth 4 ass)))
12439 (when (memq arg '(nextset previousset))
12440 (message "Keyword-Set %d/%d: %s"
12441 (- (length org-todo-sets) -1
12442 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12443 (length org-todo-sets)
12444 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12445 (setq org-last-todo-state-is-todo
12446 (not (member org-state org-done-keywords)))
12447 (setq now-done-p (and (member org-state org-done-keywords)
12448 (not (member this org-done-keywords))))
12449 (and logging (org-local-logging logging))
12450 (when (and (or org-todo-log-states org-log-done)
12451 (not (eq org-inhibit-logging t))
12452 (not (memq arg '(nextset previousset))))
12453 ;; we need to look at recording a time and note
12454 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12455 (nth 2 (assoc this org-todo-log-states))))
12456 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12457 (setq dolog 'time))
12458 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12459 (and org-state
12460 (member org-state org-not-done-keywords)
12461 (not (member this org-not-done-keywords))))
12462 ;; This is now a todo state and was not one before
12463 ;; If there was a CLOSED time stamp, get rid of it.
12464 (org-add-planning-info nil nil 'closed))
12465 (when (and now-done-p org-log-done)
12466 ;; It is now done, and it was not done before
12467 (org-add-planning-info 'closed (org-current-effective-time))
12468 (if (and (not dolog) (eq 'note org-log-done))
12469 (org-add-log-setup 'done org-state this 'findpos 'note)))
12470 (when (and org-state dolog)
12471 ;; This is a non-nil state, and we need to log it
12472 (org-add-log-setup 'state org-state this 'findpos dolog)))
12473 ;; Fixup tag positioning
12474 (org-todo-trigger-tag-changes org-state)
12475 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12476 (when org-provide-todo-statistics
12477 (org-update-parent-todo-statistics))
12478 (run-hooks 'org-after-todo-state-change-hook)
12479 (if (and arg (not (member org-state org-done-keywords)))
12480 (setq head (org-get-todo-sequence-head org-state)))
12481 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12482 ;; Do we need to trigger a repeat?
12483 (when now-done-p
12484 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12485 ;; This is for the agenda, take a snapshot of the headline.
12486 (save-match-data
12487 (setq org-agenda-headline-snapshot-before-repeat
12488 (org-get-heading))))
12489 (org-auto-repeat-maybe org-state))
12490 ;; Fixup cursor location if close to the keyword
12491 (if (and (outline-on-heading-p)
12492 (not (bolp))
12493 (save-excursion (beginning-of-line 1)
12494 (looking-at org-todo-line-regexp))
12495 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12496 (progn
12497 (goto-char (or (match-end 2) (match-end 1)))
12498 (and (looking-at " ") (just-one-space))))
12499 (when org-trigger-hook
12500 (save-excursion
12501 (run-hook-with-args 'org-trigger-hook change-plist)))
12502 (when commentp (org-toggle-comment))))))))
12504 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12505 "Block turning an entry into a TODO, using the hierarchy.
12506 This checks whether the current task should be blocked from state
12507 changes. Such blocking occurs when:
12509 1. The task has children which are not all in a completed state.
12511 2. A task has a parent with the property :ORDERED:, and there
12512 are siblings prior to the current task with incomplete
12513 status.
12515 3. The parent of the task is blocked because it has siblings that should
12516 be done first, or is child of a block grandparent TODO entry."
12518 (if (not org-enforce-todo-dependencies)
12519 t ; if locally turned off don't block
12520 (catch 'dont-block
12521 ;; If this is not a todo state change, or if this entry is already DONE,
12522 ;; do not block
12523 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12524 (member (plist-get change-plist :from)
12525 (cons 'done org-done-keywords))
12526 (member (plist-get change-plist :to)
12527 (cons 'todo org-not-done-keywords))
12528 (not (plist-get change-plist :to)))
12529 (throw 'dont-block t))
12530 ;; If this task has children, and any are undone, it's blocked
12531 (save-excursion
12532 (org-back-to-heading t)
12533 (let ((this-level (funcall outline-level)))
12534 (outline-next-heading)
12535 (let ((child-level (funcall outline-level)))
12536 (while (and (not (eobp))
12537 (> child-level this-level))
12538 ;; this todo has children, check whether they are all
12539 ;; completed
12540 (if (and (not (org-entry-is-done-p))
12541 (org-entry-is-todo-p))
12542 (progn (setq org-block-entry-blocking (org-get-heading))
12543 (throw 'dont-block nil)))
12544 (outline-next-heading)
12545 (setq child-level (funcall outline-level))))))
12546 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12547 ;; any previous siblings are undone, it's blocked
12548 (save-excursion
12549 (org-back-to-heading t)
12550 (let* ((pos (point))
12551 (parent-pos (and (org-up-heading-safe) (point))))
12552 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12553 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12554 (forward-line 1)
12555 (re-search-forward org-not-done-heading-regexp pos t))
12556 (setq org-block-entry-blocking (match-string 0))
12557 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12558 ;; Search further up the hierarchy, to see if an ancestor is blocked
12559 (while t
12560 (goto-char parent-pos)
12561 (if (not (looking-at org-not-done-heading-regexp))
12562 (throw 'dont-block t)) ; do not block, parent is not a TODO
12563 (setq pos (point))
12564 (setq parent-pos (and (org-up-heading-safe) (point)))
12565 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12566 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12567 (forward-line 1)
12568 (re-search-forward org-not-done-heading-regexp pos t)
12569 (setq org-block-entry-blocking (org-get-heading)))
12570 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12572 (defcustom org-track-ordered-property-with-tag nil
12573 "Should the ORDERED property also be shown as a tag?
12574 The ORDERED property decides if an entry should require subtasks to be
12575 completed in sequence. Since a property is not very visible, setting
12576 this option means that toggling the ORDERED property with the command
12577 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12578 not relevant for the behavior, but it makes things more visible.
12580 Note that toggling the tag with tags commands will not change the property
12581 and therefore not influence behavior!
12583 This can be t, meaning the tag ORDERED should be used, It can also be a
12584 string to select a different tag for this task."
12585 :group 'org-todo
12586 :type '(choice
12587 (const :tag "No tracking" nil)
12588 (const :tag "Track with ORDERED tag" t)
12589 (string :tag "Use other tag")))
12591 (defun org-toggle-ordered-property ()
12592 "Toggle the ORDERED property of the current entry.
12593 For better visibility, you can track the value of this property with a tag.
12594 See variable `org-track-ordered-property-with-tag'."
12595 (interactive)
12596 (let* ((t1 org-track-ordered-property-with-tag)
12597 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12598 (save-excursion
12599 (org-back-to-heading)
12600 (if (org-entry-get nil "ORDERED")
12601 (progn
12602 (org-delete-property "ORDERED")
12603 (and tag (org-toggle-tag tag 'off))
12604 (message "Subtasks can be completed in arbitrary order"))
12605 (org-entry-put nil "ORDERED" "t")
12606 (and tag (org-toggle-tag tag 'on))
12607 (message "Subtasks must be completed in sequence")))))
12609 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12610 (defun org-block-todo-from-checkboxes (change-plist)
12611 "Block turning an entry into a TODO, using checkboxes.
12612 This checks whether the current task should be blocked from state
12613 changes because there are unchecked boxes in this entry."
12614 (if (not org-enforce-todo-checkbox-dependencies)
12615 t ; if locally turned off don't block
12616 (catch 'dont-block
12617 ;; If this is not a todo state change, or if this entry is already DONE,
12618 ;; do not block
12619 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12620 (member (plist-get change-plist :from)
12621 (cons 'done org-done-keywords))
12622 (member (plist-get change-plist :to)
12623 (cons 'todo org-not-done-keywords))
12624 (not (plist-get change-plist :to)))
12625 (throw 'dont-block t))
12626 ;; If this task has checkboxes that are not checked, it's blocked
12627 (save-excursion
12628 (org-back-to-heading t)
12629 (let ((beg (point)) end)
12630 (outline-next-heading)
12631 (setq end (point))
12632 (goto-char beg)
12633 (if (org-list-search-forward
12634 (concat (org-item-beginning-re)
12635 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12636 "\\[[- ]\\]")
12637 end t)
12638 (progn
12639 (if (boundp 'org-blocked-by-checkboxes)
12640 (setq org-blocked-by-checkboxes t))
12641 (throw 'dont-block nil)))))
12642 t))) ; do not block
12644 (defun org-entry-blocked-p ()
12645 "Is the current entry blocked?"
12646 (org-with-silent-modifications
12647 (if (org-entry-get nil "NOBLOCKING")
12648 nil ;; Never block this entry
12649 (not (run-hook-with-args-until-failure
12650 'org-blocker-hook
12651 (list :type 'todo-state-change
12652 :position (point)
12653 :from 'todo
12654 :to 'done))))))
12656 (defun org-update-statistics-cookies (all)
12657 "Update the statistics cookie, either from TODO or from checkboxes.
12658 This should be called with the cursor in a line with a statistics cookie."
12659 (interactive "P")
12660 (if all
12661 (progn
12662 (org-update-checkbox-count 'all)
12663 (org-map-entries 'org-update-parent-todo-statistics))
12664 (if (not (org-at-heading-p))
12665 (org-update-checkbox-count)
12666 (let ((pos (point-marker))
12667 end l1 l2)
12668 (ignore-errors (org-back-to-heading t))
12669 (if (not (org-at-heading-p))
12670 (org-update-checkbox-count)
12671 (setq l1 (org-outline-level))
12672 (setq end (save-excursion
12673 (outline-next-heading)
12674 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12675 (point)))
12676 (if (and (save-excursion
12677 (re-search-forward
12678 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12679 (not (save-excursion (re-search-forward
12680 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12681 (org-update-checkbox-count)
12682 (if (and l2 (> l2 l1))
12683 (progn
12684 (goto-char end)
12685 (org-update-parent-todo-statistics))
12686 (goto-char pos)
12687 (beginning-of-line 1)
12688 (while (re-search-forward
12689 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12690 (point-at-eol) t)
12691 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12692 (goto-char pos)
12693 (move-marker pos nil)))))
12695 (defvar org-entry-property-inherited-from) ;; defined below
12696 (defun org-update-parent-todo-statistics ()
12697 "Update any statistics cookie in the parent of the current headline.
12698 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12699 the entire subtree and this will travel up the hierarchy and update
12700 statistics everywhere."
12701 (let* ((prop (save-excursion (org-up-heading-safe)
12702 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12703 (recursive (or (not org-hierarchical-todo-statistics)
12704 (and prop (string-match "\\<recursive\\>" prop))))
12705 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12707 (first t)
12708 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12709 level ltoggle l1 new ndel
12710 (cnt-all 0) (cnt-done 0) is-percent kwd
12711 checkbox-beg ov ovs ove cookie-present)
12712 (catch 'exit
12713 (save-excursion
12714 (beginning-of-line 1)
12715 (setq ltoggle (funcall outline-level))
12716 ;; Three situations are to consider:
12718 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12719 ;; to the top-level ancestor on the headline;
12721 ;; 2. If parent has "recursive" property, repeat up to the
12722 ;; headline setting that property, taking inheritance into
12723 ;; account;
12725 ;; 3. Else, move up to direct parent and proceed only once.
12726 (while (and (setq level (org-up-heading-safe))
12727 (or recursive first)
12728 (>= (point) lim))
12729 (setq first nil cookie-present nil)
12730 (unless (and level
12731 (not (string-match
12732 "\\<checkbox\\>"
12733 (downcase (or (org-entry-get nil "COOKIE_DATA")
12734 "")))))
12735 (throw 'exit nil))
12736 (while (re-search-forward box-re (point-at-eol) t)
12737 (setq cnt-all 0 cnt-done 0 cookie-present t)
12738 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12739 (save-match-data
12740 (unless (outline-next-heading) (throw 'exit nil))
12741 (while (and (looking-at org-complex-heading-regexp)
12742 (> (setq l1 (length (match-string 1))) level))
12743 (setq kwd (and (or recursive (= l1 ltoggle))
12744 (match-string 2)))
12745 (if (or (eq org-provide-todo-statistics 'all-headlines)
12746 (and (eq org-provide-todo-statistics t)
12747 (or (member kwd org-done-keywords)))
12748 (and (listp org-provide-todo-statistics)
12749 (stringp (car org-provide-todo-statistics))
12750 (or (member kwd org-provide-todo-statistics)
12751 (member kwd org-done-keywords)))
12752 (and (listp org-provide-todo-statistics)
12753 (listp (car org-provide-todo-statistics))
12754 (or (member kwd (car org-provide-todo-statistics))
12755 (and (member kwd org-done-keywords)
12756 (member kwd (cadr org-provide-todo-statistics))))))
12757 (setq cnt-all (1+ cnt-all))
12758 (if (eq org-provide-todo-statistics t)
12759 (and kwd (setq cnt-all (1+ cnt-all)))))
12760 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12761 (member kwd org-done-keywords))
12762 (and (listp org-provide-todo-statistics)
12763 (listp (car org-provide-todo-statistics))
12764 (member kwd org-done-keywords)
12765 (member kwd (cadr org-provide-todo-statistics)))
12766 (and (listp org-provide-todo-statistics)
12767 (stringp (car org-provide-todo-statistics))
12768 (member kwd org-done-keywords)))
12769 (setq cnt-done (1+ cnt-done)))
12770 (outline-next-heading)))
12771 (setq new
12772 (if is-percent
12773 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12774 (format "[%d/%d]" cnt-done cnt-all))
12775 ndel (- (match-end 0) checkbox-beg))
12776 ;; handle overlays when updating cookie from column view
12777 (when (setq ov (car (overlays-at checkbox-beg)))
12778 (setq ovs (overlay-start ov) ove (overlay-end ov))
12779 (delete-overlay ov))
12780 (goto-char checkbox-beg)
12781 (insert new)
12782 (delete-region (point) (+ (point) ndel))
12783 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12784 (when ov (move-overlay ov ovs ove)))
12785 (when cookie-present
12786 (run-hook-with-args 'org-after-todo-statistics-hook
12787 cnt-done (- cnt-all cnt-done))))))
12788 (run-hooks 'org-todo-statistics-hook)))
12790 (defvar org-after-todo-statistics-hook nil
12791 "Hook that is called after a TODO statistics cookie has been updated.
12792 Each function is called with two arguments: the number of not-done entries
12793 and the number of done entries.
12795 For example, the following function, when added to this hook, will switch
12796 an entry to DONE when all children are done, and back to TODO when new
12797 entries are set to a TODO status. Note that this hook is only called
12798 when there is a statistics cookie in the headline!
12800 (defun org-summary-todo (n-done n-not-done)
12801 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12802 (let (org-log-done org-log-states) ; turn off logging
12803 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12806 (defvar org-todo-statistics-hook nil
12807 "Hook that is run whenever Org thinks TODO statistics should be updated.
12808 This hook runs even if there is no statistics cookie present, in which case
12809 `org-after-todo-statistics-hook' would not run.")
12811 (defun org-todo-trigger-tag-changes (state)
12812 "Apply the changes defined in `org-todo-state-tags-triggers'."
12813 (let ((l org-todo-state-tags-triggers)
12814 changes)
12815 (when (or (not state) (equal state ""))
12816 (setq changes (append changes (cdr (assoc "" l)))))
12817 (when (and (stringp state) (> (length state) 0))
12818 (setq changes (append changes (cdr (assoc state l)))))
12819 (when (member state org-not-done-keywords)
12820 (setq changes (append changes (cdr (assoc 'todo l)))))
12821 (when (member state org-done-keywords)
12822 (setq changes (append changes (cdr (assoc 'done l)))))
12823 (dolist (c changes)
12824 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12826 (defun org-local-logging (value)
12827 "Get logging settings from a property VALUE."
12828 (let* (words w a)
12829 ;; directly set the variables, they are already local.
12830 (setq org-log-done nil
12831 org-log-repeat nil
12832 org-todo-log-states nil)
12833 (setq words (org-split-string value))
12834 (while (setq w (pop words))
12835 (cond
12836 ((setq a (assoc w org-startup-options))
12837 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12838 (set (nth 1 a) (nth 2 a))))
12839 ((setq a (org-extract-log-state-settings w))
12840 (and (member (car a) org-todo-keywords-1)
12841 (push a org-todo-log-states)))))))
12843 (defun org-get-todo-sequence-head (kwd)
12844 "Return the head of the TODO sequence to which KWD belongs.
12845 If KWD is not set, check if there is a text property remembering the
12846 right sequence."
12847 (let (p)
12848 (cond
12849 ((not kwd)
12850 (or (get-text-property (point-at-bol) 'org-todo-head)
12851 (progn
12852 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12853 nil (point-at-eol)))
12854 (get-text-property p 'org-todo-head))))
12855 ((not (member kwd org-todo-keywords-1))
12856 (car org-todo-keywords-1))
12857 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12859 (defun org-fast-todo-selection ()
12860 "Fast TODO keyword selection with single keys.
12861 Returns the new TODO keyword, or nil if no state change should occur."
12862 (let* ((fulltable org-todo-key-alist)
12863 (done-keywords org-done-keywords) ;; needed for the faces.
12864 (maxlen (apply 'max (mapcar
12865 (lambda (x)
12866 (if (stringp (car x)) (string-width (car x)) 0))
12867 fulltable)))
12868 (expert nil)
12869 (fwidth (+ maxlen 3 1 3))
12870 (ncol (/ (- (window-width) 4) fwidth))
12871 tg cnt e c tbl
12872 groups ingroup)
12873 (save-excursion
12874 (save-window-excursion
12875 (if expert
12876 (set-buffer (get-buffer-create " *Org todo*"))
12877 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12878 (erase-buffer)
12879 (org-set-local 'org-done-keywords done-keywords)
12880 (setq tbl fulltable cnt 0)
12881 (while (setq e (pop tbl))
12882 (cond
12883 ((equal e '(:startgroup))
12884 (push '() groups) (setq ingroup t)
12885 (when (not (= cnt 0))
12886 (setq cnt 0)
12887 (insert "\n"))
12888 (insert "{ "))
12889 ((equal e '(:endgroup))
12890 (setq ingroup nil cnt 0)
12891 (insert "}\n"))
12892 ((equal e '(:newline))
12893 (when (not (= cnt 0))
12894 (setq cnt 0)
12895 (insert "\n")
12896 (setq e (car tbl))
12897 (while (equal (car tbl) '(:newline))
12898 (insert "\n")
12899 (setq tbl (cdr tbl)))))
12901 (setq tg (car e) c (cdr e))
12902 (if ingroup (push tg (car groups)))
12903 (setq tg (org-add-props tg nil 'face
12904 (org-get-todo-face tg)))
12905 (if (and (= cnt 0) (not ingroup)) (insert " "))
12906 (insert "[" c "] " tg (make-string
12907 (- fwidth 4 (length tg)) ?\ ))
12908 (when (= (setq cnt (1+ cnt)) ncol)
12909 (insert "\n")
12910 (if ingroup (insert " "))
12911 (setq cnt 0)))))
12912 (insert "\n")
12913 (goto-char (point-min))
12914 (if (not expert) (org-fit-window-to-buffer))
12915 (message "[a-z..]:Set [SPC]:clear")
12916 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12917 (cond
12918 ((or (= c ?\C-g)
12919 (and (= c ?q) (not (rassoc c fulltable))))
12920 (setq quit-flag t))
12921 ((= c ?\ ) nil)
12922 ((setq e (rassoc c fulltable) tg (car e))
12924 (t (setq quit-flag t)))))))
12926 (defun org-entry-is-todo-p ()
12927 (member (org-get-todo-state) org-not-done-keywords))
12929 (defun org-entry-is-done-p ()
12930 (member (org-get-todo-state) org-done-keywords))
12932 (defun org-get-todo-state ()
12933 "Return the TODO keyword of the current subtree."
12934 (save-excursion
12935 (org-back-to-heading t)
12936 (and (looking-at org-todo-line-regexp)
12937 (match-end 2)
12938 (match-string 2))))
12940 (defun org-at-date-range-p (&optional inactive-ok)
12941 "Is the cursor inside a date range?"
12942 (interactive)
12943 (save-excursion
12944 (catch 'exit
12945 (let ((pos (point)))
12946 (skip-chars-backward "^[<\r\n")
12947 (skip-chars-backward "<[")
12948 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12949 (>= (match-end 0) pos)
12950 (throw 'exit t))
12951 (skip-chars-backward "^<[\r\n")
12952 (skip-chars-backward "<[")
12953 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12954 (>= (match-end 0) pos)
12955 (throw 'exit t)))
12956 nil)))
12958 (defun org-get-repeat (&optional tagline)
12959 "Check if there is a deadline/schedule with repeater in this entry."
12960 (save-match-data
12961 (save-excursion
12962 (org-back-to-heading t)
12963 (and (re-search-forward (if tagline
12964 (concat tagline "\\s-*" org-repeat-re)
12965 org-repeat-re)
12966 (org-entry-end-position) t)
12967 (match-string-no-properties 1)))))
12969 (defvar org-last-changed-timestamp)
12970 (defvar org-last-inserted-timestamp)
12971 (defvar org-log-post-message)
12972 (defvar org-log-note-purpose)
12973 (defvar org-log-note-how)
12974 (defvar org-log-note-extra)
12975 (defun org-auto-repeat-maybe (done-word)
12976 "Check if the current headline contains a repeated deadline/schedule.
12977 If yes, set TODO state back to what it was and change the base date
12978 of repeating deadline/scheduled time stamps to new date.
12979 This function is run automatically after each state change to a DONE state."
12980 ;; last-state is dynamically scoped into this function
12981 (let* ((repeat (org-get-repeat))
12982 (aa (assoc org-last-state org-todo-kwd-alist))
12983 (interpret (nth 1 aa))
12984 (head (nth 2 aa))
12985 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12986 (msg "Entry repeats: ")
12987 (org-log-done nil)
12988 (org-todo-log-states nil)
12989 re type n what ts time to-state)
12990 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12991 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12992 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12993 org-todo-repeat-to-state))
12994 (unless (and to-state (member to-state org-todo-keywords-1))
12995 (setq to-state (if (eq interpret 'type) org-last-state head)))
12996 (org-todo to-state)
12997 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12998 (org-entry-put nil "LAST_REPEAT" (format-time-string
12999 (org-time-stamp-format t t))))
13000 (when org-log-repeat
13001 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13002 (memq 'org-add-log-note post-command-hook))
13003 ;; OK, we are already setup for some record
13004 (if (eq org-log-repeat 'note)
13005 ;; make sure we take a note, not only a time stamp
13006 (setq org-log-note-how 'note))
13007 ;; Set up for taking a record
13008 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13009 org-last-state
13010 'findpos org-log-repeat)))
13011 (org-back-to-heading t)
13012 (org-add-planning-info nil nil 'closed)
13013 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13014 org-deadline-time-regexp "\\)\\|\\("
13015 org-ts-regexp "\\)"))
13016 (while (re-search-forward
13017 re (save-excursion (outline-next-heading) (point)) t)
13018 (setq type (if (match-end 1) org-scheduled-string
13019 (if (match-end 3) org-deadline-string "Plain:"))
13020 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13021 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13022 (setq n (string-to-number (match-string 2 ts))
13023 what (match-string 3 ts))
13024 (if (equal what "w") (setq n (* n 7) what "d"))
13025 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13026 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13027 ;; Preparation, see if we need to modify the start date for the change
13028 (when (match-end 1)
13029 (setq time (save-match-data (org-time-string-to-time ts)))
13030 (cond
13031 ((equal (match-string 1 ts) ".")
13032 ;; Shift starting date to today
13033 (org-timestamp-change
13034 (- (org-today) (time-to-days time))
13035 'day))
13036 ((equal (match-string 1 ts) "+")
13037 (let ((nshiftmax 10) (nshift 0))
13038 (while (or (= nshift 0)
13039 (<= (time-to-days time)
13040 (time-to-days (current-time))))
13041 (when (= (incf nshift) nshiftmax)
13042 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13043 (user-error "Abort")))
13044 (org-timestamp-change n (cdr (assoc what whata)))
13045 (org-at-timestamp-p t)
13046 (setq ts (match-string 1))
13047 (setq time (save-match-data (org-time-string-to-time ts)))))
13048 (org-timestamp-change (- n) (cdr (assoc what whata)))
13049 ;; rematch, so that we have everything in place for the real shift
13050 (org-at-timestamp-p t)
13051 (setq ts (match-string 1))
13052 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13053 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13054 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13055 (setq org-log-post-message msg)
13056 (message "%s" msg))))
13058 (defun org-show-todo-tree (arg)
13059 "Make a compact tree which shows all headlines marked with TODO.
13060 The tree will show the lines where the regexp matches, and all higher
13061 headlines above the match.
13062 With a \\[universal-argument] prefix, prompt for a regexp to match.
13063 With a numeric prefix N, construct a sparse tree for the Nth element
13064 of `org-todo-keywords-1'."
13065 (interactive "P")
13066 (let ((case-fold-search nil)
13067 (kwd-re
13068 (cond ((null arg) org-not-done-regexp)
13069 ((equal arg '(4))
13070 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13071 (mapcar 'list org-todo-keywords-1))))
13072 (concat "\\("
13073 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13074 "\\)\\>")))
13075 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13076 (regexp-quote (nth (1- (prefix-numeric-value arg))
13077 org-todo-keywords-1)))
13078 (t (user-error "Invalid prefix argument: %s" arg)))))
13079 (message "%d TODO entries found"
13080 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13082 (defun org-deadline (arg &optional time)
13083 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13084 With one universal prefix argument, remove any deadline from the item.
13085 With two universal prefix arguments, prompt for a warning delay.
13086 With argument TIME, set the deadline at the corresponding date. TIME
13087 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13088 (interactive "P")
13089 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13090 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13091 'region-start-level 'region))
13092 org-loop-over-headlines-in-active-region)
13093 (org-map-entries
13094 `(org-deadline ',arg ,time)
13095 org-loop-over-headlines-in-active-region
13096 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13097 (let* ((old-date (org-entry-get nil "DEADLINE"))
13098 (old-date-time (if old-date (org-time-string-to-time old-date)))
13099 (repeater (and old-date
13100 (string-match
13101 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13102 old-date)
13103 (match-string 1 old-date))))
13104 (cond
13105 ((equal arg '(4))
13106 (when (and old-date org-log-redeadline)
13107 (org-add-log-setup 'deldeadline nil old-date 'findpos
13108 org-log-redeadline))
13109 (org-remove-timestamp-with-keyword org-deadline-string)
13110 (message "Item no longer has a deadline."))
13111 ((equal arg '(16))
13112 (save-excursion
13113 (org-back-to-heading t)
13114 (if (re-search-forward
13115 org-deadline-time-regexp
13116 (save-excursion (outline-next-heading) (point)) t)
13117 (let* ((rpl0 (match-string 1))
13118 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13119 (replace-match
13120 (concat org-deadline-string
13121 " <" rpl
13122 (format " -%dd"
13123 (abs
13124 (- (time-to-days
13125 (save-match-data
13126 (org-read-date nil t nil "Warn starting from" old-date-time)))
13127 (time-to-days old-date-time))))
13128 ">") t t))
13129 (user-error "No deadline information to update"))))
13131 (org-add-planning-info 'deadline time 'closed)
13132 (when (and old-date org-log-redeadline
13133 (not (equal old-date
13134 (substring org-last-inserted-timestamp 1 -1))))
13135 (org-add-log-setup 'redeadline nil old-date 'findpos
13136 org-log-redeadline))
13137 (when repeater
13138 (save-excursion
13139 (org-back-to-heading t)
13140 (when (re-search-forward (concat org-deadline-string " "
13141 org-last-inserted-timestamp)
13142 (save-excursion
13143 (outline-next-heading) (point)) t)
13144 (goto-char (1- (match-end 0)))
13145 (insert " " repeater)
13146 (setq org-last-inserted-timestamp
13147 (concat (substring org-last-inserted-timestamp 0 -1)
13148 " " repeater
13149 (substring org-last-inserted-timestamp -1))))))
13150 (message "Deadline on %s" org-last-inserted-timestamp))))))
13152 (defun org-schedule (arg &optional time)
13153 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13154 With one universal prefix argument, remove any scheduling date from the item.
13155 With two universal prefix arguments, prompt for a delay cookie.
13156 With argument TIME, scheduled at the corresponding date. TIME can
13157 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13158 (interactive "P")
13159 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13160 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13161 'region-start-level 'region))
13162 org-loop-over-headlines-in-active-region)
13163 (org-map-entries
13164 `(org-schedule ',arg ,time)
13165 org-loop-over-headlines-in-active-region
13166 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13167 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13168 (old-date-time (if old-date (org-time-string-to-time old-date)))
13169 (repeater (and old-date
13170 (string-match
13171 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13172 old-date)
13173 (match-string 1 old-date))))
13174 (cond
13175 ((equal arg '(4))
13176 (progn
13177 (when (and old-date org-log-reschedule)
13178 (org-add-log-setup 'delschedule nil old-date 'findpos
13179 org-log-reschedule))
13180 (org-remove-timestamp-with-keyword org-scheduled-string)
13181 (message "Item is no longer scheduled.")))
13182 ((equal arg '(16))
13183 (save-excursion
13184 (org-back-to-heading t)
13185 (if (re-search-forward
13186 org-scheduled-time-regexp
13187 (save-excursion (outline-next-heading) (point)) t)
13188 (let* ((rpl0 (match-string 1))
13189 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13190 (replace-match
13191 (concat org-scheduled-string
13192 " <" rpl
13193 (format " -%dd"
13194 (abs
13195 (- (time-to-days
13196 (save-match-data
13197 (org-read-date nil t nil "Delay until" old-date-time)))
13198 (time-to-days old-date-time))))
13199 ">") t t))
13200 (user-error "No scheduled information to update"))))
13202 (org-add-planning-info 'scheduled time 'closed)
13203 (when (and old-date org-log-reschedule
13204 (not (equal old-date
13205 (substring org-last-inserted-timestamp 1 -1))))
13206 (org-add-log-setup 'reschedule nil old-date 'findpos
13207 org-log-reschedule))
13208 (when repeater
13209 (save-excursion
13210 (org-back-to-heading t)
13211 (when (re-search-forward (concat org-scheduled-string " "
13212 org-last-inserted-timestamp)
13213 (save-excursion
13214 (outline-next-heading) (point)) t)
13215 (goto-char (1- (match-end 0)))
13216 (insert " " repeater)
13217 (setq org-last-inserted-timestamp
13218 (concat (substring org-last-inserted-timestamp 0 -1)
13219 " " repeater
13220 (substring org-last-inserted-timestamp -1))))))
13221 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13223 (defun org-get-scheduled-time (pom &optional inherit)
13224 "Get the scheduled time as a time tuple, of a format suitable
13225 for calling org-schedule with, or if there is no scheduling,
13226 returns nil."
13227 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13228 (when time
13229 (apply 'encode-time (org-parse-time-string time)))))
13231 (defun org-get-deadline-time (pom &optional inherit)
13232 "Get the deadline as a time tuple, of a format suitable for
13233 calling org-deadline with, or if there is no scheduling, returns
13234 nil."
13235 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13236 (when time
13237 (apply 'encode-time (org-parse-time-string time)))))
13239 (defun org-remove-timestamp-with-keyword (keyword)
13240 "Remove all time stamps with KEYWORD in the current entry."
13241 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13242 beg)
13243 (save-excursion
13244 (org-back-to-heading t)
13245 (setq beg (point))
13246 (outline-next-heading)
13247 (while (re-search-backward re beg t)
13248 (replace-match "")
13249 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13250 (equal (char-before) ?\ ))
13251 (backward-delete-char 1)
13252 (if (string-match "^[ \t]*$" (buffer-substring
13253 (point-at-bol) (point-at-eol)))
13254 (delete-region (point-at-bol)
13255 (min (point-max) (1+ (point-at-eol))))))))))
13257 (defvar org-time-was-given) ; dynamically scoped parameter
13258 (defvar org-end-time-was-given) ; dynamically scoped parameter
13260 (defun org-add-planning-info (what &optional time &rest remove)
13261 "Insert new timestamp with keyword in the line directly after the headline.
13262 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13263 If non is given, the user is prompted for a date.
13264 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13265 be removed."
13266 (interactive)
13267 (let (org-time-was-given org-end-time-was-given ts
13268 end default-time default-input)
13270 (catch 'exit
13271 (when (and (memq what '(scheduled deadline))
13272 (or (not time)
13273 (and (stringp time)
13274 (string-match "^[-+]+[0-9]" time))))
13275 ;; Try to get a default date/time from existing timestamp
13276 (save-excursion
13277 (org-back-to-heading t)
13278 (setq end (save-excursion (outline-next-heading) (point)))
13279 (when (re-search-forward (if (eq what 'scheduled)
13280 org-scheduled-time-regexp
13281 org-deadline-time-regexp)
13282 end t)
13283 (setq ts (match-string 1)
13284 default-time
13285 (apply 'encode-time (org-parse-time-string ts))
13286 default-input (and ts (org-get-compact-tod ts))))))
13287 (when what
13288 (setq time
13289 (if (stringp time)
13290 ;; This is a string (relative or absolute), set proper date
13291 (apply 'encode-time
13292 (org-read-date-analyze
13293 time default-time (decode-time default-time)))
13294 ;; If necessary, get the time from the user
13295 (or time (org-read-date nil 'to-time nil nil
13296 default-time default-input)))))
13298 (when (and org-insert-labeled-timestamps-at-point
13299 (member what '(scheduled deadline)))
13300 (insert
13301 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13302 (org-insert-time-stamp time org-time-was-given
13303 nil nil nil (list org-end-time-was-given))
13304 (setq what nil))
13305 (save-excursion
13306 (save-restriction
13307 (let (col list elt ts buffer-invisibility-spec)
13308 (org-back-to-heading t)
13309 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13310 (goto-char (match-end 1))
13311 (setq col (current-column))
13312 (goto-char (match-end 0))
13313 (if (eobp) (insert "\n") (forward-char 1))
13314 (when (and (not what)
13315 (not (looking-at
13316 (concat "[ \t]*"
13317 org-keyword-time-not-clock-regexp))))
13318 ;; Nothing to add, nothing to remove...... :-)
13319 (throw 'exit nil))
13320 (if (and (not (looking-at org-outline-regexp))
13321 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13322 "[^\r\n]*"))
13323 (not (equal (match-string 1) org-clock-string)))
13324 (narrow-to-region (match-beginning 0) (match-end 0))
13325 (insert-before-markers "\n")
13326 (backward-char 1)
13327 (narrow-to-region (point) (point))
13328 (and org-adapt-indentation (org-indent-to-column col)))
13329 ;; Check if we have to remove something.
13330 (setq list (cons what remove))
13331 (while list
13332 (setq elt (pop list))
13333 (when (or (and (eq elt 'scheduled)
13334 (re-search-forward org-scheduled-time-regexp nil t))
13335 (and (eq elt 'deadline)
13336 (re-search-forward org-deadline-time-regexp nil t))
13337 (and (eq elt 'closed)
13338 (re-search-forward org-closed-time-regexp nil t)))
13339 (replace-match "")
13340 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13341 (and (looking-at "[ \t]+") (replace-match ""))
13342 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13343 (when what
13344 (insert
13345 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13346 (cond ((eq what 'scheduled) org-scheduled-string)
13347 ((eq what 'deadline) org-deadline-string)
13348 ((eq what 'closed) org-closed-string))
13349 " ")
13350 (setq ts (org-insert-time-stamp
13351 time
13352 (or org-time-was-given
13353 (and (eq what 'closed) org-log-done-with-time))
13354 (eq what 'closed)
13355 nil nil (list org-end-time-was-given)))
13356 (insert
13357 (if (not (or (bolp) (eq (char-before) ?\ )
13358 (memq (char-after) '(32 10))
13359 (eobp))) " " ""))
13360 (end-of-line 1))
13361 (goto-char (point-min))
13362 (widen)
13363 (if (and (looking-at "[ \t]*\n")
13364 (equal (char-before) ?\n))
13365 (delete-region (1- (point)) (point-at-eol)))
13366 ts))))))
13368 (defvar org-log-note-marker (make-marker))
13369 (defvar org-log-note-purpose nil)
13370 (defvar org-log-note-state nil)
13371 (defvar org-log-note-previous-state nil)
13372 (defvar org-log-note-how nil)
13373 (defvar org-log-note-extra nil)
13374 (defvar org-log-note-window-configuration nil)
13375 (defvar org-log-note-return-to (make-marker))
13376 (defvar org-log-note-effective-time nil
13377 "Remembered current time so that dynamically scoped
13378 `org-extend-today-until' affects tha timestamps in state change
13379 log")
13381 (defvar org-log-post-message nil
13382 "Message to be displayed after a log note has been stored.
13383 The auto-repeater uses this.")
13385 (defun org-add-note ()
13386 "Add a note to the current entry.
13387 This is done in the same way as adding a state change note."
13388 (interactive)
13389 (org-add-log-setup 'note nil nil 'findpos nil))
13391 (defvar org-property-end-re)
13392 (defun org-add-log-setup (&optional purpose state prev-state
13393 findpos how extra)
13394 "Set up the post command hook to take a note.
13395 If this is about to TODO state change, the new state is expected in STATE.
13396 When FINDPOS is non-nil, find the correct position for the note in
13397 the current entry. If not, assume that it can be inserted at point.
13398 HOW is an indicator what kind of note should be created.
13399 EXTRA is additional text that will be inserted into the notes buffer."
13400 (let* ((org-log-into-drawer (org-log-into-drawer))
13401 (drawer (cond ((stringp org-log-into-drawer)
13402 org-log-into-drawer)
13403 (org-log-into-drawer "LOGBOOK"))))
13404 (save-restriction
13405 (save-excursion
13406 (when findpos
13407 (org-back-to-heading t)
13408 (narrow-to-region (point) (save-excursion
13409 (outline-next-heading) (point)))
13410 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13411 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13412 "[^\r\n]*\\)?"))
13413 (goto-char (match-end 0))
13414 (cond
13415 (drawer
13416 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13417 nil t)
13418 (progn
13419 (goto-char (match-end 0))
13420 (or org-log-states-order-reversed
13421 (and (re-search-forward org-property-end-re nil t)
13422 (goto-char (1- (match-beginning 0))))))
13423 (insert "\n:" drawer ":\n:END:")
13424 (beginning-of-line 0)
13425 (org-indent-line)
13426 (beginning-of-line 2)
13427 (org-indent-line)
13428 (end-of-line 0)))
13429 ((and org-log-state-notes-insert-after-drawers
13430 (save-excursion
13431 (forward-line) (looking-at org-drawer-regexp)))
13432 (forward-line)
13433 (while (looking-at org-drawer-regexp)
13434 (goto-char (match-end 0))
13435 (re-search-forward org-property-end-re (point-max) t)
13436 (forward-line))
13437 (forward-line -1)))
13438 (unless org-log-states-order-reversed
13439 (and (= (char-after) ?\n) (forward-char 1))
13440 (org-skip-over-state-notes)
13441 (skip-chars-backward " \t\n\r")))
13442 (move-marker org-log-note-marker (point))
13443 (setq org-log-note-purpose purpose
13444 org-log-note-state state
13445 org-log-note-previous-state prev-state
13446 org-log-note-how how
13447 org-log-note-extra extra
13448 org-log-note-effective-time (org-current-effective-time))
13449 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13451 (defun org-skip-over-state-notes ()
13452 "Skip past the list of State notes in an entry."
13453 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13454 (when (ignore-errors (goto-char (org-in-item-p)))
13455 (let* ((struct (org-list-struct))
13456 (prevs (org-list-prevs-alist struct)))
13457 (while (looking-at "[ \t]*- State")
13458 (goto-char (or (org-list-get-next-item (point) struct prevs)
13459 (org-list-get-item-end (point) struct)))))))
13461 (defun org-add-log-note (&optional purpose)
13462 "Pop up a window for taking a note, and add this note later at point."
13463 (remove-hook 'post-command-hook 'org-add-log-note)
13464 (setq org-log-note-window-configuration (current-window-configuration))
13465 (delete-other-windows)
13466 (move-marker org-log-note-return-to (point))
13467 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13468 (goto-char org-log-note-marker)
13469 (org-switch-to-buffer-other-window "*Org Note*")
13470 (erase-buffer)
13471 (if (memq org-log-note-how '(time state))
13472 (let (current-prefix-arg) (org-store-log-note))
13473 (let ((org-inhibit-startup t)) (org-mode))
13474 (insert (format "# Insert note for %s.
13475 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13476 (cond
13477 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13478 ((eq org-log-note-purpose 'done) "closed todo item")
13479 ((eq org-log-note-purpose 'state)
13480 (format "state change from \"%s\" to \"%s\""
13481 (or org-log-note-previous-state "")
13482 (or org-log-note-state "")))
13483 ((eq org-log-note-purpose 'reschedule)
13484 "rescheduling")
13485 ((eq org-log-note-purpose 'delschedule)
13486 "no longer scheduled")
13487 ((eq org-log-note-purpose 'redeadline)
13488 "changing deadline")
13489 ((eq org-log-note-purpose 'deldeadline)
13490 "removing deadline")
13491 ((eq org-log-note-purpose 'refile)
13492 "refiling")
13493 ((eq org-log-note-purpose 'note)
13494 "this entry")
13495 (t (error "This should not happen")))))
13496 (if org-log-note-extra (insert org-log-note-extra))
13497 (org-set-local 'org-finish-function 'org-store-log-note)
13498 (run-hooks 'org-log-buffer-setup-hook)))
13500 (defvar org-note-abort nil) ; dynamically scoped
13501 (defun org-store-log-note ()
13502 "Finish taking a log note, and insert it to where it belongs."
13503 (let ((txt (buffer-string)))
13504 (kill-buffer (current-buffer))
13505 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13506 lines ind bul)
13507 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13508 (setq txt (replace-match "" t t txt)))
13509 (if (string-match "\\s-+\\'" txt)
13510 (setq txt (replace-match "" t t txt)))
13511 (setq lines (org-split-string txt "\n"))
13512 (when (and note (string-match "\\S-" note))
13513 (setq note
13514 (org-replace-escapes
13515 note
13516 (list (cons "%u" (user-login-name))
13517 (cons "%U" user-full-name)
13518 (cons "%t" (format-time-string
13519 (org-time-stamp-format 'long 'inactive)
13520 org-log-note-effective-time))
13521 (cons "%T" (format-time-string
13522 (org-time-stamp-format 'long nil)
13523 org-log-note-effective-time))
13524 (cons "%d" (format-time-string
13525 (org-time-stamp-format nil 'inactive)
13526 org-log-note-effective-time))
13527 (cons "%D" (format-time-string
13528 (org-time-stamp-format nil nil)
13529 org-log-note-effective-time))
13530 (cons "%s" (if org-log-note-state
13531 (concat "\"" org-log-note-state "\"")
13532 ""))
13533 (cons "%S" (if org-log-note-previous-state
13534 (concat "\"" org-log-note-previous-state "\"")
13535 "\"\"")))))
13536 (if lines (setq note (concat note " \\\\")))
13537 (push note lines))
13538 (when (or current-prefix-arg org-note-abort)
13539 (when org-log-into-drawer
13540 (org-remove-empty-drawer-at org-log-note-marker))
13541 (setq lines nil))
13542 (when lines
13543 (with-current-buffer (marker-buffer org-log-note-marker)
13544 (save-excursion
13545 (goto-char org-log-note-marker)
13546 (move-marker org-log-note-marker nil)
13547 (end-of-line 1)
13548 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13549 (setq ind (save-excursion
13550 (if (ignore-errors (goto-char (org-in-item-p)))
13551 (let ((struct (org-list-struct)))
13552 (org-list-get-ind
13553 (org-list-get-top-point struct) struct))
13554 (skip-chars-backward " \r\t\n")
13555 (cond
13556 ((and (org-at-heading-p)
13557 org-adapt-indentation)
13558 (1+ (org-current-level)))
13559 ((org-at-heading-p) 0)
13560 (t (org-get-indentation))))))
13561 (setq bul (org-list-bullet-string "-"))
13562 (org-indent-line-to ind)
13563 (insert bul (pop lines))
13564 (let ((ind-body (+ (length bul) ind)))
13565 (while lines
13566 (insert "\n")
13567 (org-indent-line-to ind-body)
13568 (insert (pop lines))))
13569 (message "Note stored")
13570 (org-back-to-heading t)
13571 (org-cycle-hide-drawers 'children))
13572 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13573 ;; from within `org-add-log-note' because `buffer-undo-list'
13574 ;; is then modified outside of `org-with-remote-undo'.
13575 (when (eq this-command 'org-agenda-todo)
13576 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13577 ;; Don't add undo information when called from `org-agenda-todo'
13578 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13579 (set-window-configuration org-log-note-window-configuration)
13580 (with-current-buffer (marker-buffer org-log-note-return-to)
13581 (goto-char org-log-note-return-to))
13582 (move-marker org-log-note-return-to nil)
13583 (and org-log-post-message (message "%s" org-log-post-message))))
13585 (defun org-remove-empty-drawer-at (pos)
13586 "Remove an empty drawer at position POS.
13587 POS may also be a marker."
13588 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13589 (org-with-wide-buffer
13590 (goto-char pos)
13591 (let ((drawer (org-element-at-point)))
13592 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13593 (not (org-element-property :contents-begin drawer)))
13594 (delete-region (org-element-property :begin drawer)
13595 (progn (goto-char (org-element-property :end drawer))
13596 (skip-chars-backward " \r\t\n")
13597 (forward-line)
13598 (point))))))))
13600 (defvar org-ts-type nil)
13601 (defun org-sparse-tree (&optional arg type)
13602 "Create a sparse tree, prompt for the details.
13603 This command can create sparse trees. You first need to select the type
13604 of match used to create the tree:
13606 t Show all TODO entries.
13607 T Show entries with a specific TODO keyword.
13608 m Show entries selected by a tags/property match.
13609 p Enter a property name and its value (both with completion on existing
13610 names/values) and show entries with that property.
13611 r Show entries matching a regular expression (`/' can be used as well).
13612 b Show deadlines and scheduled items before a date.
13613 a Show deadlines and scheduled items after a date.
13614 d Show deadlines due within `org-deadline-warning-days'.
13615 D Show deadlines and scheduled items between a date range."
13616 (interactive "P")
13617 (setq type (or type org-sparse-tree-default-date-type))
13618 (setq org-ts-type type)
13619 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13620 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13621 [c]ycle through date types: %s"
13622 (case type
13623 (all "all timestamps")
13624 (scheduled "only scheduled")
13625 (deadline "only deadline")
13626 (active "only active timestamps")
13627 (inactive "only inactive timestamps")
13628 (scheduled-or-deadline "scheduled/deadline")
13629 (closed "with a closed time-stamp")
13630 (otherwise "scheduled/deadline")))
13631 (let ((answer (read-char-exclusive)))
13632 (case answer
13634 (org-sparse-tree
13636 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13637 inactive closed)))))
13638 (?d (call-interactively #'org-check-deadlines))
13639 (?b (call-interactively #'org-check-before-date))
13640 (?a (call-interactively #'org-check-after-date))
13641 (?D (call-interactively #'org-check-dates-range))
13642 (?t (call-interactively #'org-show-todo-tree))
13643 (?T (org-show-todo-tree '(4)))
13644 (?m (call-interactively #'org-match-sparse-tree))
13645 ((?p ?P)
13646 (let* ((kwd (org-icompleting-read
13647 "Property: " (mapcar #'list (org-buffer-property-keys))))
13648 (value (org-icompleting-read
13649 "Value: " (mapcar #'list (org-property-values kwd)))))
13650 (unless (string-match "\\`{.*}\\'" value)
13651 (setq value (concat "\"" value "\"")))
13652 (org-match-sparse-tree arg (concat kwd "=" value))))
13653 ((?r ?R ?/) (call-interactively #'org-occur))
13654 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13656 (defvar org-occur-highlights nil
13657 "List of overlays used for occur matches.")
13658 (make-variable-buffer-local 'org-occur-highlights)
13659 (defvar org-occur-parameters nil
13660 "Parameters of the active org-occur calls.
13661 This is a list, each call to org-occur pushes as cons cell,
13662 containing the regular expression and the callback, onto the list.
13663 The list can contain several entries if `org-occur' has been called
13664 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13665 will only contain one set of parameters. When the highlights are
13666 removed (for example with `C-c C-c', or with the next edit (depending
13667 on `org-remove-highlights-with-change'), this variable is emptied
13668 as well.")
13669 (make-variable-buffer-local 'org-occur-parameters)
13671 (defun org-occur (regexp &optional keep-previous callback)
13672 "Make a compact tree which shows all matches of REGEXP.
13673 The tree will show the lines where the regexp matches, and all higher
13674 headlines above the match. It will also show the heading after the match,
13675 to make sure editing the matching entry is easy.
13676 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13677 call to `org-occur' will be kept, to allow stacking of calls to this
13678 command.
13679 If CALLBACK is non-nil, it is a function which is called to confirm
13680 that the match should indeed be shown."
13681 (interactive "sRegexp: \nP")
13682 (when (equal regexp "")
13683 (user-error "Regexp cannot be empty"))
13684 (unless keep-previous
13685 (org-remove-occur-highlights nil nil t))
13686 (push (cons regexp callback) org-occur-parameters)
13687 (let ((cnt 0))
13688 (save-excursion
13689 (goto-char (point-min))
13690 (if (or (not keep-previous) ; do not want to keep
13691 (not org-occur-highlights)) ; no previous matches
13692 ;; hide everything
13693 (org-overview))
13694 (while (re-search-forward regexp nil t)
13695 (when (or (not callback)
13696 (save-match-data (funcall callback)))
13697 (setq cnt (1+ cnt))
13698 (when org-highlight-sparse-tree-matches
13699 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13700 (org-show-context 'occur-tree))))
13701 (when org-remove-highlights-with-change
13702 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13703 nil 'local))
13704 (unless org-sparse-tree-open-archived-trees
13705 (org-hide-archived-subtrees (point-min) (point-max)))
13706 (run-hooks 'org-occur-hook)
13707 (if (org-called-interactively-p 'interactive)
13708 (message "%d match(es) for regexp %s" cnt regexp))
13709 cnt))
13711 (defun org-occur-next-match (&optional n reset)
13712 "Function for `next-error-function' to find sparse tree matches.
13713 N is the number of matches to move, when negative move backwards.
13714 RESET is entirely ignored - this function always goes back to the
13715 starting point when no match is found."
13716 (let* ((limit (if (< n 0) (point-min) (point-max)))
13717 (search-func (if (< n 0)
13718 'previous-single-char-property-change
13719 'next-single-char-property-change))
13720 (n (abs n))
13721 (pos (point))
13723 (catch 'exit
13724 (while (setq p1 (funcall search-func (point) 'org-type))
13725 (when (equal p1 limit)
13726 (goto-char pos)
13727 (user-error "No more matches"))
13728 (when (equal (get-char-property p1 'org-type) 'org-occur)
13729 (setq n (1- n))
13730 (when (= n 0)
13731 (goto-char p1)
13732 (throw 'exit (point))))
13733 (goto-char p1))
13734 (goto-char p1)
13735 (user-error "No more matches"))))
13737 (defun org-show-context (&optional key)
13738 "Make sure point and context are visible.
13739 How much context is shown depends upon the variables
13740 `org-show-hierarchy-above', `org-show-following-heading',
13741 `org-show-entry-below' and `org-show-siblings'."
13742 (let ((heading-p (org-at-heading-p t))
13743 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13744 (following-p (org-get-alist-option org-show-following-heading key))
13745 (entry-p (org-get-alist-option org-show-entry-below key))
13746 (siblings-p (org-get-alist-option org-show-siblings key)))
13747 ;; Show heading or entry text
13748 (if (and heading-p (not entry-p))
13749 (org-flag-heading nil) ; only show the heading
13750 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13751 (org-show-hidden-entry))) ; show entire entry
13752 (when following-p
13753 ;; Show next sibling, or heading below text
13754 (save-excursion
13755 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13756 (org-flag-heading nil))))
13757 (when siblings-p (org-show-siblings))
13758 (when hierarchy-p
13759 ;; show all higher headings, possibly with siblings
13760 (save-excursion
13761 (while (and (condition-case nil
13762 (progn (org-up-heading-all 1) t)
13763 (error nil))
13764 (not (bobp)))
13765 (org-flag-heading nil)
13766 (when siblings-p (org-show-siblings)))))
13767 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13769 (defvar org-reveal-start-hook nil
13770 "Hook run before revealing a location.")
13772 (defun org-reveal (&optional siblings)
13773 "Show current entry, hierarchy above it, and the following headline.
13774 This can be used to show a consistent set of context around locations
13775 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13776 not t for the search context.
13778 With optional argument SIBLINGS, on each level of the hierarchy all
13779 siblings are shown. This repairs the tree structure to what it would
13780 look like when opened with hierarchical calls to `org-cycle'.
13781 With double optional argument \\[universal-argument] \\[universal-argument], \
13782 go to the parent and show the
13783 entire tree."
13784 (interactive "P")
13785 (run-hooks 'org-reveal-start-hook)
13786 (let ((org-show-hierarchy-above t)
13787 (org-show-following-heading t)
13788 (org-show-siblings (if siblings t org-show-siblings)))
13789 (org-show-context nil))
13790 (when (equal siblings '(16))
13791 (save-excursion
13792 (when (org-up-heading-safe)
13793 (org-show-subtree)
13794 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13796 (defun org-highlight-new-match (beg end)
13797 "Highlight from BEG to END and mark the highlight is an occur headline."
13798 (let ((ov (make-overlay beg end)))
13799 (overlay-put ov 'face 'secondary-selection)
13800 (overlay-put ov 'org-type 'org-occur)
13801 (push ov org-occur-highlights)))
13803 (defun org-remove-occur-highlights (&optional beg end noremove)
13804 "Remove the occur highlights from the buffer.
13805 BEG and END are ignored. If NOREMOVE is nil, remove this function
13806 from the `before-change-functions' in the current buffer."
13807 (interactive)
13808 (unless org-inhibit-highlight-removal
13809 (mapc 'delete-overlay org-occur-highlights)
13810 (setq org-occur-highlights nil)
13811 (setq org-occur-parameters nil)
13812 (unless noremove
13813 (remove-hook 'before-change-functions
13814 'org-remove-occur-highlights 'local))))
13816 ;;;; Priorities
13818 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13819 "Regular expression matching the priority indicator.")
13821 (defvar org-remove-priority-next-time nil)
13823 (defun org-priority-up ()
13824 "Increase the priority of the current item."
13825 (interactive)
13826 (org-priority 'up))
13828 (defun org-priority-down ()
13829 "Decrease the priority of the current item."
13830 (interactive)
13831 (org-priority 'down))
13833 (defun org-priority (&optional action show)
13834 "Change the priority of an item.
13835 ACTION can be `set', `up', `down', or a character."
13836 (interactive "P")
13837 (if (equal action '(4))
13838 (org-show-priority)
13839 (unless org-enable-priority-commands
13840 (user-error "Priority commands are disabled"))
13841 (setq action (or action 'set))
13842 (let (current new news have remove)
13843 (save-excursion
13844 (org-back-to-heading t)
13845 (if (looking-at org-priority-regexp)
13846 (setq current (string-to-char (match-string 2))
13847 have t))
13848 (cond
13849 ((eq action 'remove)
13850 (setq remove t new ?\ ))
13851 ((or (eq action 'set)
13852 (if (featurep 'xemacs) (characterp action) (integerp action)))
13853 (if (not (eq action 'set))
13854 (setq new action)
13855 (message "Priority %c-%c, SPC to remove: "
13856 org-highest-priority org-lowest-priority)
13857 (save-match-data
13858 (setq new (read-char-exclusive))))
13859 (if (and (= (upcase org-highest-priority) org-highest-priority)
13860 (= (upcase org-lowest-priority) org-lowest-priority))
13861 (setq new (upcase new)))
13862 (cond ((equal new ?\ ) (setq remove t))
13863 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13864 (user-error "Priority must be between `%c' and `%c'"
13865 org-highest-priority org-lowest-priority))))
13866 ((eq action 'up)
13867 (setq new (if have
13868 (1- current) ; normal cycling
13869 ;; last priority was empty
13870 (if (eq last-command this-command)
13871 org-lowest-priority ; wrap around empty to lowest
13872 ;; default
13873 (if org-priority-start-cycle-with-default
13874 org-default-priority
13875 (1- org-default-priority))))))
13876 ((eq action 'down)
13877 (setq new (if have
13878 (1+ current) ; normal cycling
13879 ;; last priority was empty
13880 (if (eq last-command this-command)
13881 org-highest-priority ; wrap around empty to highest
13882 ;; default
13883 (if org-priority-start-cycle-with-default
13884 org-default-priority
13885 (1+ org-default-priority))))))
13886 (t (user-error "Invalid action")))
13887 (if (or (< (upcase new) org-highest-priority)
13888 (> (upcase new) org-lowest-priority))
13889 (if (and (memq action '(up down))
13890 (not have) (not (eq last-command this-command)))
13891 ;; `new' is from default priority
13892 (error
13893 "The default can not be set, see `org-default-priority' why")
13894 ;; normal cycling: `new' is beyond highest/lowest priority
13895 ;; and is wrapped around to the empty priority
13896 (setq remove t)))
13897 (setq news (format "%c" new))
13898 (if have
13899 (if remove
13900 (replace-match "" t t nil 1)
13901 (replace-match news t t nil 2))
13902 (if remove
13903 (user-error "No priority cookie found in line")
13904 (let ((case-fold-search nil))
13905 (looking-at org-todo-line-regexp))
13906 (if (match-end 2)
13907 (progn
13908 (goto-char (match-end 2))
13909 (insert " [#" news "]"))
13910 (goto-char (match-beginning 3))
13911 (insert "[#" news "] "))))
13912 (org-set-tags nil 'align))
13913 (if remove
13914 (message "Priority removed")
13915 (message "Priority of current item set to %s" news)))))
13917 (defun org-show-priority ()
13918 "Show the priority of the current item.
13919 This priority is composed of the main priority given with the [#A] cookies,
13920 and by additional input from the age of a schedules or deadline entry."
13921 (interactive)
13922 (let ((pri (if (eq major-mode 'org-agenda-mode)
13923 (org-get-at-bol 'priority)
13924 (save-excursion
13925 (save-match-data
13926 (beginning-of-line)
13927 (and (looking-at org-heading-regexp)
13928 (org-get-priority (match-string 0))))))))
13929 (message "Priority is %d" (if pri pri -1000))))
13931 (defun org-get-priority (s)
13932 "Find priority cookie and return priority."
13933 (save-match-data
13934 (if (functionp org-get-priority-function)
13935 (funcall org-get-priority-function)
13936 (if (not (string-match org-priority-regexp s))
13937 (* 1000 (- org-lowest-priority org-default-priority))
13938 (* 1000 (- org-lowest-priority
13939 (string-to-char (match-string 2 s))))))))
13941 ;;;; Tags
13943 (defvar org-agenda-archives-mode)
13944 (defvar org-map-continue-from nil
13945 "Position from where mapping should continue.
13946 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13948 (defvar org-scanner-tags nil
13949 "The current tag list while the tags scanner is running.")
13950 (defvar org-trust-scanner-tags nil
13951 "Should `org-get-tags-at' use the tags for the scanner.
13952 This is for internal dynamical scoping only.
13953 When this is non-nil, the function `org-get-tags-at' will return the value
13954 of `org-scanner-tags' instead of building the list by itself. This
13955 can lead to large speed-ups when the tags scanner is used in a file with
13956 many entries, and when the list of tags is retrieved, for example to
13957 obtain a list of properties. Building the tags list for each entry in such
13958 a file becomes an N^2 operation - but with this variable set, it scales
13959 as N.")
13961 (defun org-scan-tags (action matcher todo-only &optional start-level)
13962 "Sca headline tags with inheritance and produce output ACTION.
13964 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13965 or `agenda' to produce an entry list for an agenda view. It can also be
13966 a Lisp form or a function that should be called at each matched headline, in
13967 this case the return value is a list of all return values from these calls.
13969 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13970 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13971 only lines with a not-done TODO keyword are included in the output.
13972 This should be the same variable that was scoped into
13973 and set by `org-make-tags-matcher' when it constructed MATCHER.
13975 START-LEVEL can be a string with asterisks, reducing the scope to
13976 headlines matching this string."
13977 (require 'org-agenda)
13978 (let* ((re (concat "^"
13979 (if start-level
13980 ;; Get the correct level to match
13981 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13982 org-outline-regexp)
13983 " *\\(\\<\\("
13984 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13985 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13986 (props (list 'face 'default
13987 'done-face 'org-agenda-done
13988 'undone-face 'default
13989 'mouse-face 'highlight
13990 'org-not-done-regexp org-not-done-regexp
13991 'org-todo-regexp org-todo-regexp
13992 'org-complex-heading-regexp org-complex-heading-regexp
13993 'help-echo
13994 (format "mouse-2 or RET jump to org file %s"
13995 (abbreviate-file-name
13996 (or (buffer-file-name (buffer-base-buffer))
13997 (buffer-name (buffer-base-buffer)))))))
13998 (org-map-continue-from nil)
13999 lspos tags tags-list
14000 (tags-alist (list (cons 0 org-file-tags)))
14001 (llast 0) rtn rtn1 level category i txt
14002 todo marker entry priority)
14003 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14004 (setq action (list 'lambda nil action)))
14005 (save-excursion
14006 (goto-char (point-min))
14007 (when (eq action 'sparse-tree)
14008 (org-overview)
14009 (org-remove-occur-highlights))
14010 (while (let (case-fold-search)
14011 (re-search-forward re nil t))
14012 (setq org-map-continue-from nil)
14013 (catch :skip
14014 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14015 tags (if (match-end 4) (org-match-string-no-properties 4)))
14016 (goto-char (setq lspos (match-beginning 0)))
14017 (setq level (org-reduced-level (org-outline-level))
14018 category (org-get-category))
14019 (setq i llast llast level)
14020 ;; remove tag lists from same and sublevels
14021 (while (>= i level)
14022 (when (setq entry (assoc i tags-alist))
14023 (setq tags-alist (delete entry tags-alist)))
14024 (setq i (1- i)))
14025 ;; add the next tags
14026 (when tags
14027 (setq tags (org-split-string tags ":")
14028 tags-alist
14029 (cons (cons level tags) tags-alist)))
14030 ;; compile tags for current headline
14031 (setq tags-list
14032 (if org-use-tag-inheritance
14033 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14034 tags)
14035 org-scanner-tags tags-list)
14036 (when org-use-tag-inheritance
14037 (setcdr (car tags-alist)
14038 (mapcar (lambda (x)
14039 (setq x (copy-sequence x))
14040 (org-add-prop-inherited x))
14041 (cdar tags-alist))))
14042 (when (and tags org-use-tag-inheritance
14043 (or (not (eq t org-use-tag-inheritance))
14044 org-tags-exclude-from-inheritance))
14045 ;; selective inheritance, remove uninherited ones
14046 (setcdr (car tags-alist)
14047 (org-remove-uninherited-tags (cdar tags-alist))))
14048 (when (and
14050 ;; eval matcher only when the todo condition is OK
14051 (and (or (not todo-only) (member todo org-not-done-keywords))
14052 (let ((case-fold-search t) (org-trust-scanner-tags t))
14053 (eval matcher)))
14055 ;; Call the skipper, but return t if it does not skip,
14056 ;; so that the `and' form continues evaluating
14057 (progn
14058 (unless (eq action 'sparse-tree) (org-agenda-skip))
14061 ;; Check if timestamps are deselecting this entry
14062 (or (not todo-only)
14063 (and (member todo org-not-done-keywords)
14064 (or (not org-agenda-tags-todo-honor-ignore-options)
14065 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14067 ;; select this headline
14068 (cond
14069 ((eq action 'sparse-tree)
14070 (and org-highlight-sparse-tree-matches
14071 (org-get-heading) (match-end 0)
14072 (org-highlight-new-match
14073 (match-beginning 1) (match-end 1)))
14074 (org-show-context 'tags-tree))
14075 ((eq action 'agenda)
14076 (setq txt (org-agenda-format-item
14078 (concat
14079 (if (eq org-tags-match-list-sublevels 'indented)
14080 (make-string (1- level) ?.) "")
14081 (org-get-heading))
14082 level category
14083 tags-list)
14084 priority (org-get-priority txt))
14085 (goto-char lspos)
14086 (setq marker (org-agenda-new-marker))
14087 (org-add-props txt props
14088 'org-marker marker 'org-hd-marker marker 'org-category category
14089 'todo-state todo
14090 'priority priority 'type "tagsmatch")
14091 (push txt rtn))
14092 ((functionp action)
14093 (setq org-map-continue-from nil)
14094 (save-excursion
14095 (setq rtn1 (funcall action))
14096 (push rtn1 rtn)))
14097 (t (user-error "Invalid action")))
14099 ;; if we are to skip sublevels, jump to end of subtree
14100 (unless org-tags-match-list-sublevels
14101 (org-end-of-subtree t)
14102 (backward-char 1))))
14103 ;; Get the correct position from where to continue
14104 (if org-map-continue-from
14105 (goto-char org-map-continue-from)
14106 (and (= (point) lspos) (end-of-line 1)))))
14107 (when (and (eq action 'sparse-tree)
14108 (not org-sparse-tree-open-archived-trees))
14109 (org-hide-archived-subtrees (point-min) (point-max)))
14110 (nreverse rtn)))
14112 (defun org-remove-uninherited-tags (tags)
14113 "Remove all tags that are not inherited from the list TAGS."
14114 (cond
14115 ((eq org-use-tag-inheritance t)
14116 (if org-tags-exclude-from-inheritance
14117 (org-delete-all org-tags-exclude-from-inheritance tags)
14118 tags))
14119 ((not org-use-tag-inheritance) nil)
14120 ((stringp org-use-tag-inheritance)
14121 (delq nil (mapcar
14122 (lambda (x)
14123 (if (and (string-match org-use-tag-inheritance x)
14124 (not (member x org-tags-exclude-from-inheritance)))
14125 x nil))
14126 tags)))
14127 ((listp org-use-tag-inheritance)
14128 (delq nil (mapcar
14129 (lambda (x)
14130 (if (member x org-use-tag-inheritance) x nil))
14131 tags)))))
14133 (defun org-match-sparse-tree (&optional todo-only match)
14134 "Create a sparse tree according to tags string MATCH.
14135 MATCH can contain positive and negative selection of tags, like
14136 \"+WORK+URGENT-WITHBOSS\".
14137 If optional argument TODO-ONLY is non-nil, only select lines that are
14138 also TODO lines."
14139 (interactive "P")
14140 (org-agenda-prepare-buffers (list (current-buffer)))
14141 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14143 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14145 (defvar org-cached-props nil)
14146 (defun org-cached-entry-get (pom property)
14147 (if (or (eq t org-use-property-inheritance)
14148 (and (stringp org-use-property-inheritance)
14149 (string-match org-use-property-inheritance property))
14150 (and (listp org-use-property-inheritance)
14151 (member property org-use-property-inheritance)))
14152 ;; Caching is not possible, check it directly
14153 (org-entry-get pom property 'inherit)
14154 ;; Get all properties, so that we can do complicated checks easily
14155 (cdr (assoc property (or org-cached-props
14156 (setq org-cached-props
14157 (org-entry-properties pom)))))))
14159 (defun org-global-tags-completion-table (&optional files)
14160 "Return the list of all tags in all agenda buffer/files.
14161 Optional FILES argument is a list of files which can be used
14162 instead of the agenda files."
14163 (save-excursion
14164 (org-uniquify
14165 (delq nil
14166 (apply 'append
14167 (mapcar
14168 (lambda (file)
14169 (set-buffer (find-file-noselect file))
14170 (append (org-get-buffer-tags)
14171 (mapcar (lambda (x) (if (stringp (car-safe x))
14172 (list (car-safe x)) nil))
14173 org-tag-alist)))
14174 (if (and files (car files))
14175 files
14176 (org-agenda-files))))))))
14178 (defun org-make-tags-matcher (match)
14179 "Create the TAGS/TODO matcher form for the selection string MATCH.
14181 The variable `todo-only' is scoped dynamically into this function.
14182 It will be set to t if the matcher restricts matching to TODO entries,
14183 otherwise will not be touched.
14185 Returns a cons of the selection string MATCH and the constructed
14186 lisp form implementing the matcher. The matcher is to be evaluated
14187 at an Org entry, with point on the headline, and returns t if the
14188 entry matches the selection string MATCH. The returned lisp form
14189 references two variables with information about the entry, which
14190 must be bound around the form's evaluation: todo, the TODO keyword
14191 at the entry (or nil of none); and tags-list, the list of all tags
14192 at the entry including inherited ones. Additionally, the category
14193 of the entry (if any) must be specified as the text property
14194 'org-category on the headline.
14196 See also `org-scan-tags'.
14198 (declare (special todo-only))
14199 (unless (boundp 'todo-only)
14200 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14201 (unless match
14202 ;; Get a new match request, with completion against the global
14203 ;; tags table and the local tags in current buffer
14204 (let ((org-last-tags-completion-table
14205 (org-uniquify
14206 (delq nil (append (org-get-buffer-tags)
14207 (org-global-tags-completion-table))))))
14208 (setq match (org-completing-read-no-i
14209 "Match: " 'org-tags-completion-function nil nil nil
14210 'org-tags-history))))
14212 ;; Parse the string and create a lisp form
14213 (let ((match0 match)
14214 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14215 minus tag mm
14216 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14217 orterms term orlist re-p str-p level-p level-op time-p
14218 prop-p pn pv po gv rest (start 0) (ss 0))
14219 ;; Expand group tags
14220 (setq match (org-tags-expand match))
14222 ;; Check if there is a TODO part of this match, which would be the
14223 ;; part after a "/". TO make sure that this slash is not part of
14224 ;; a property value to be matched against, we also check that there
14225 ;; is no " after that slash.
14226 ;; First, find the last slash
14227 (while (string-match "/+" match ss)
14228 (setq start (match-beginning 0) ss (match-end 0)))
14229 (if (and (string-match "/+" match start)
14230 (not (save-match-data (string-match "\"" match start))))
14231 ;; match contains also a todo-matching request
14232 (progn
14233 (setq tagsmatch (substring match 0 (match-beginning 0))
14234 todomatch (substring match (match-end 0)))
14235 (if (string-match "^!" todomatch)
14236 (setq todo-only t todomatch (substring todomatch 1)))
14237 (if (string-match "^\\s-*$" todomatch)
14238 (setq todomatch nil)))
14239 ;; only matching tags
14240 (setq tagsmatch match todomatch nil))
14242 ;; Make the tags matcher
14243 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14244 (setq tagsmatcher t)
14245 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14246 (while (setq term (pop orterms))
14247 (while (and (equal (substring term -1) "\\") orterms)
14248 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14249 (while (string-match re term)
14250 (setq rest (substring term (match-end 0))
14251 minus (and (match-end 1)
14252 (equal (match-string 1 term) "-"))
14253 tag (save-match-data (replace-regexp-in-string
14254 "\\\\-" "-"
14255 (match-string 2 term)))
14256 re-p (equal (string-to-char tag) ?{)
14257 level-p (match-end 4)
14258 prop-p (match-end 5)
14259 mm (cond
14260 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14261 (level-p
14262 (setq level-op (org-op-to-function (match-string 3 term)))
14263 `(,level-op level ,(string-to-number
14264 (match-string 4 term))))
14265 (prop-p
14266 (setq pn (match-string 5 term)
14267 po (match-string 6 term)
14268 pv (match-string 7 term)
14269 re-p (equal (string-to-char pv) ?{)
14270 str-p (equal (string-to-char pv) ?\")
14271 time-p (save-match-data
14272 (string-match "^\"[[<].*[]>]\"$" pv))
14273 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14274 (if time-p (setq pv (org-matcher-time pv)))
14275 (setq po (org-op-to-function po (if time-p 'time str-p)))
14276 (cond
14277 ((equal pn "CATEGORY")
14278 (setq gv '(get-text-property (point) 'org-category)))
14279 ((equal pn "TODO")
14280 (setq gv 'todo))
14282 (setq gv `(org-cached-entry-get nil ,pn))))
14283 (if re-p
14284 (if (eq po 'org<>)
14285 `(not (string-match ,pv (or ,gv "")))
14286 `(string-match ,pv (or ,gv "")))
14287 (if str-p
14288 `(,po (or ,gv "") ,pv)
14289 `(,po (string-to-number (or ,gv ""))
14290 ,(string-to-number pv) ))))
14291 (t `(member ,tag tags-list)))
14292 mm (if minus (list 'not mm) mm)
14293 term rest)
14294 (push mm tagsmatcher))
14295 (push (if (> (length tagsmatcher) 1)
14296 (cons 'and tagsmatcher)
14297 (car tagsmatcher))
14298 orlist)
14299 (setq tagsmatcher nil))
14300 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14301 (setq tagsmatcher
14302 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14303 ;; Make the todo matcher
14304 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14305 (setq todomatcher t)
14306 (setq orterms (org-split-string todomatch "|") orlist nil)
14307 (while (setq term (pop orterms))
14308 (while (string-match re term)
14309 (setq minus (and (match-end 1)
14310 (equal (match-string 1 term) "-"))
14311 kwd (match-string 2 term)
14312 re-p (equal (string-to-char kwd) ?{)
14313 term (substring term (match-end 0))
14314 mm (if re-p
14315 `(string-match ,(substring kwd 1 -1) todo)
14316 (list 'equal 'todo kwd))
14317 mm (if minus (list 'not mm) mm))
14318 (push mm todomatcher))
14319 (push (if (> (length todomatcher) 1)
14320 (cons 'and todomatcher)
14321 (car todomatcher))
14322 orlist)
14323 (setq todomatcher nil))
14324 (setq todomatcher (if (> (length orlist) 1)
14325 (cons 'or orlist) (car orlist))))
14327 ;; Return the string and lisp forms of the matcher
14328 (setq matcher (if todomatcher
14329 (list 'and tagsmatcher todomatcher)
14330 tagsmatcher))
14331 (when todo-only
14332 (setq matcher (list 'and '(member todo org-not-done-keywords)
14333 matcher)))
14334 (cons match0 matcher)))
14336 (defun org-tags-expand (match &optional single-as-list downcased)
14337 "Expand group tags in MATCH.
14339 This replaces every group tag in MATCH with a regexp tag search.
14340 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14341 will be replaced like this:
14343 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14344 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14345 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14347 Replacing by a regexp preserves the structure of the match.
14348 E.g., this expansion
14350 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14352 will match anything tagged with \"Lab\" and \"Home\", or tagged
14353 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14355 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14356 assumed to be a single group tag, and the function will return
14357 the list of tags in this group.
14359 When DOWNCASE is non-nil, expand downcased TAGS."
14360 (if org-group-tags
14361 (let* ((case-fold-search t)
14362 (stable org-mode-syntax-table)
14363 (tal (or org-tag-groups-alist-for-agenda
14364 org-tag-groups-alist))
14365 (tal (if downcased
14366 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14367 (tml (mapcar 'car tal))
14368 (rtnmatch match) rpl)
14369 ;; @ and _ are allowed as word-components in tags
14370 (modify-syntax-entry ?@ "w" stable)
14371 (modify-syntax-entry ?_ "w" stable)
14372 (while (and tml
14373 (with-syntax-table stable
14374 (string-match
14375 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14376 (regexp-opt tml) "\\>\\)") rtnmatch)))
14377 (let* ((dir (match-string 1 rtnmatch))
14378 (tag (match-string 2 rtnmatch))
14379 (tag (if downcased (downcase tag) tag)))
14380 (setq tml (delete tag tml))
14381 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14382 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14383 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14384 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14385 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14386 (if single-as-list
14387 (or (reverse rpl) (list rtnmatch))
14388 rtnmatch))
14389 (if single-as-list (list (if downcased (downcase match) match))
14390 match)))
14392 (defun org-op-to-function (op &optional stringp)
14393 "Turn an operator into the appropriate function."
14394 (setq op
14395 (cond
14396 ((equal op "<" ) '(< string< org-time<))
14397 ((equal op ">" ) '(> org-string> org-time>))
14398 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14399 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14400 ((member op '("=" "==")) '(= string= org-time=))
14401 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14402 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14404 (defun org<> (a b) (not (= a b)))
14405 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14406 (defun org-string>= (a b) (not (string< a b)))
14407 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14408 (defun org-string<> (a b) (not (string= a b)))
14409 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14410 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14411 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14412 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14413 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14414 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14415 (defun org-2ft (s)
14416 "Convert S to a floating point time.
14417 If S is already a number, just return it. If it is a string, parse
14418 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14419 (cond
14420 ((numberp s) s)
14421 ((stringp s)
14422 (condition-case nil
14423 (float-time (apply 'encode-time (org-parse-time-string s)))
14424 (error 0.)))
14425 (t 0.)))
14427 (defun org-time-today ()
14428 "Time in seconds today at 0:00.
14429 Returns the float number of seconds since the beginning of the
14430 epoch to the beginning of today (00:00)."
14431 (float-time (apply 'encode-time
14432 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14434 (defun org-matcher-time (s)
14435 "Interpret a time comparison value."
14436 (save-match-data
14437 (cond
14438 ((string= s "<now>") (float-time))
14439 ((string= s "<today>") (org-time-today))
14440 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14441 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14442 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14443 (+ (org-time-today)
14444 (* (string-to-number (match-string 1 s))
14445 (cdr (assoc (match-string 2 s)
14446 '(("d" . 86400.0) ("w" . 604800.0)
14447 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14448 (t (org-2ft s)))))
14450 (defun org-match-any-p (re list)
14451 "Does re match any element of list?"
14452 (setq list (mapcar (lambda (x) (string-match re x)) list))
14453 (delq nil list))
14455 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14456 (defvar org-tags-overlay (make-overlay 1 1))
14457 (org-detach-overlay org-tags-overlay)
14459 (defun org-get-local-tags-at (&optional pos)
14460 "Get a list of tags defined in the current headline."
14461 (org-get-tags-at pos 'local))
14463 (defun org-get-local-tags ()
14464 "Get a list of tags defined in the current headline."
14465 (org-get-tags-at nil 'local))
14467 (defun org-get-tags-at (&optional pos local)
14468 "Get a list of all headline tags applicable at POS.
14469 POS defaults to point. If tags are inherited, the list contains
14470 the targets in the same sequence as the headlines appear, i.e.
14471 the tags of the current headline come last.
14472 When LOCAL is non-nil, only return tags from the current headline,
14473 ignore inherited ones."
14474 (interactive)
14475 (if (and org-trust-scanner-tags
14476 (or (not pos) (equal pos (point)))
14477 (not local))
14478 org-scanner-tags
14479 (let (tags ltags lastpos parent)
14480 (save-excursion
14481 (save-restriction
14482 (widen)
14483 (goto-char (or pos (point)))
14484 (save-match-data
14485 (catch 'done
14486 (condition-case nil
14487 (progn
14488 (org-back-to-heading t)
14489 (while (not (equal lastpos (point)))
14490 (setq lastpos (point))
14491 (when (looking-at
14492 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14493 (setq ltags (org-split-string
14494 (org-match-string-no-properties 1) ":"))
14495 (when parent
14496 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14497 (setq tags (append
14498 (if parent
14499 (org-remove-uninherited-tags ltags)
14500 ltags)
14501 tags)))
14502 (or org-use-tag-inheritance (throw 'done t))
14503 (if local (throw 'done t))
14504 (or (org-up-heading-safe) (error nil))
14505 (setq parent t)))
14506 (error nil)))))
14507 (if local
14508 tags
14509 (reverse (delete-dups
14510 (reverse (append
14511 (org-remove-uninherited-tags
14512 org-file-tags) tags)))))))))
14514 (defun org-add-prop-inherited (s)
14515 (add-text-properties 0 (length s) '(inherited t) s)
14518 (defun org-toggle-tag (tag &optional onoff)
14519 "Toggle the tag TAG for the current line.
14520 If ONOFF is `on' or `off', don't toggle but set to this state."
14521 (let (res current)
14522 (save-excursion
14523 (org-back-to-heading t)
14524 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14525 (point-at-eol) t)
14526 (progn
14527 (setq current (match-string 1))
14528 (replace-match ""))
14529 (setq current ""))
14530 (setq current (nreverse (org-split-string current ":")))
14531 (cond
14532 ((eq onoff 'on)
14533 (setq res t)
14534 (or (member tag current) (push tag current)))
14535 ((eq onoff 'off)
14536 (or (not (member tag current)) (setq current (delete tag current))))
14537 (t (if (member tag current)
14538 (setq current (delete tag current))
14539 (setq res t)
14540 (push tag current))))
14541 (end-of-line 1)
14542 (if current
14543 (progn
14544 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14545 (org-set-tags nil t))
14546 (delete-horizontal-space))
14547 (run-hooks 'org-after-tags-change-hook))
14548 res))
14550 (defun org-align-tags-here (to-col)
14551 ;; Assumes that this is a headline
14552 "Align tags on the current headline to TO-COL."
14553 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14554 (beginning-of-line 1)
14555 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14556 (< pos (match-beginning 2)))
14557 (progn
14558 (setq tags-l (- (match-end 2) (match-beginning 2)))
14559 (goto-char (match-beginning 1))
14560 (insert " ")
14561 (delete-region (point) (1+ (match-beginning 2)))
14562 (setq ncol (max (current-column)
14563 (1+ col)
14564 (if (> to-col 0)
14565 to-col
14566 (- (abs to-col) tags-l))))
14567 (setq p (point))
14568 (insert (make-string (- ncol (current-column)) ?\ ))
14569 (setq ncol (current-column))
14570 (when indent-tabs-mode (tabify p (point-at-eol)))
14571 (org-move-to-column (min ncol col)))
14572 (goto-char pos))))
14574 (defun org-set-tags-command (&optional arg just-align)
14575 "Call the set-tags command for the current entry."
14576 (interactive "P")
14577 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14578 (org-set-tags arg just-align)
14579 (save-excursion
14580 (unless (and (org-region-active-p)
14581 org-loop-over-headlines-in-active-region)
14582 (org-back-to-heading t))
14583 (org-set-tags arg just-align))))
14585 (defun org-set-tags-to (data)
14586 "Set the tags of the current entry to DATA, replacing the current tags.
14587 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14588 If DATA is nil or the empty string, any tags will be removed."
14589 (interactive "sTags: ")
14590 (setq data
14591 (cond
14592 ((eq data nil) "")
14593 ((equal data "") "")
14594 ((stringp data)
14595 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14596 ":"))
14597 ((listp data)
14598 (concat ":" (mapconcat 'identity data ":") ":"))))
14599 (when data
14600 (save-excursion
14601 (org-back-to-heading t)
14602 (when (looking-at org-complex-heading-regexp)
14603 (if (match-end 5)
14604 (progn
14605 (goto-char (match-beginning 5))
14606 (insert data)
14607 (delete-region (point) (point-at-eol))
14608 (org-set-tags nil 'align))
14609 (goto-char (point-at-eol))
14610 (insert " " data)
14611 (org-set-tags nil 'align)))
14612 (beginning-of-line 1)
14613 (if (looking-at ".*?\\([ \t]+\\)$")
14614 (delete-region (match-beginning 1) (match-end 1))))))
14616 (defun org-align-all-tags ()
14617 "Align the tags i all headings."
14618 (interactive)
14619 (save-excursion
14620 (or (ignore-errors (org-back-to-heading t))
14621 (outline-next-heading))
14622 (if (org-at-heading-p)
14623 (org-set-tags t)
14624 (message "No headings"))))
14626 (defvar org-indent-indentation-per-level)
14627 (defun org-set-tags (&optional arg just-align)
14628 "Set the tags for the current headline.
14629 With prefix ARG, realign all tags in headings in the current buffer.
14630 When JUST-ALIGN is non-nil, only align tags."
14631 (interactive "P")
14632 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14633 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14634 'region-start-level 'region))
14635 org-loop-over-headlines-in-active-region)
14636 (org-map-entries
14637 ;; We don't use ARG and JUST-ALIGN here because these args
14638 ;; are not useful when looping over headlines.
14639 `(org-set-tags)
14640 org-loop-over-headlines-in-active-region
14641 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14642 (let* ((re org-outline-regexp-bol)
14643 (current (unless arg (org-get-tags-string)))
14644 (col (current-column))
14645 (org-setting-tags t)
14646 table current-tags inherited-tags ; computed below when needed
14647 tags p0 c0 c1 rpl di tc level)
14648 (if arg
14649 (save-excursion
14650 (goto-char (point-min))
14651 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14652 (while (re-search-forward re nil t)
14653 (org-set-tags nil t)
14654 (end-of-line 1)))
14655 (message "All tags realigned to column %d" org-tags-column))
14656 (if just-align
14657 (setq tags current)
14658 ;; Get a new set of tags from the user
14659 (save-excursion
14660 (setq table (append org-tag-persistent-alist
14661 (or org-tag-alist (org-get-buffer-tags))
14662 (and
14663 org-complete-tags-always-offer-all-agenda-tags
14664 (org-global-tags-completion-table
14665 (org-agenda-files))))
14666 org-last-tags-completion-table table
14667 current-tags (org-split-string current ":")
14668 inherited-tags (nreverse
14669 (nthcdr (length current-tags)
14670 (nreverse (org-get-tags-at))))
14671 tags
14672 (if (or (eq t org-use-fast-tag-selection)
14673 (and org-use-fast-tag-selection
14674 (delq nil (mapcar 'cdr table))))
14675 (org-fast-tag-selection
14676 current-tags inherited-tags table
14677 (if org-fast-tag-selection-include-todo
14678 org-todo-key-alist))
14679 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14680 (org-trim
14681 (org-icompleting-read "Tags: "
14682 'org-tags-completion-function
14683 nil nil current 'org-tags-history))))))
14684 (while (string-match "[-+&]+" tags)
14685 ;; No boolean logic, just a list
14686 (setq tags (replace-match ":" t t tags))))
14688 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14690 (if org-tags-sort-function
14691 (setq tags (mapconcat 'identity
14692 (sort (org-split-string
14693 tags (org-re "[^[:alnum:]_@#%]+"))
14694 org-tags-sort-function) ":")))
14696 (if (string-match "\\`[\t ]*\\'" tags)
14697 (setq tags "")
14698 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14699 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14701 ;; Insert new tags at the correct column
14702 (beginning-of-line 1)
14703 (setq level (or (and (looking-at org-outline-regexp)
14704 (- (match-end 0) (point) 1))
14706 (cond
14707 ((and (equal current "") (equal tags "")))
14708 ((re-search-forward
14709 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14710 (point-at-eol) t)
14711 (if (equal tags "")
14712 (setq rpl "")
14713 (goto-char (match-beginning 0))
14714 (setq c0 (current-column)
14715 ;; compute offset for the case of org-indent-mode active
14716 di (if (org-bound-and-true-p org-indent-mode)
14717 (* (1- org-indent-indentation-per-level) (1- level))
14719 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14720 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14721 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14722 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14723 (replace-match rpl t t)
14724 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14725 tags)
14726 (t (error "Tags alignment failed")))
14727 (org-move-to-column col)
14728 (unless just-align
14729 (run-hooks 'org-after-tags-change-hook))))))
14731 (defun org-change-tag-in-region (beg end tag off)
14732 "Add or remove TAG for each entry in the region.
14733 This works in the agenda, and also in an org-mode buffer."
14734 (interactive
14735 (list (region-beginning) (region-end)
14736 (let ((org-last-tags-completion-table
14737 (if (derived-mode-p 'org-mode)
14738 (org-uniquify
14739 (delq nil (append (org-get-buffer-tags)
14740 (org-global-tags-completion-table))))
14741 (org-global-tags-completion-table))))
14742 (org-icompleting-read
14743 "Tag: " 'org-tags-completion-function nil nil nil
14744 'org-tags-history))
14745 (progn
14746 (message "[s]et or [r]emove? ")
14747 (equal (read-char-exclusive) ?r))))
14748 (if (fboundp 'deactivate-mark) (deactivate-mark))
14749 (let ((agendap (equal major-mode 'org-agenda-mode))
14750 l1 l2 m buf pos newhead (cnt 0))
14751 (goto-char end)
14752 (setq l2 (1- (org-current-line)))
14753 (goto-char beg)
14754 (setq l1 (org-current-line))
14755 (loop for l from l1 to l2 do
14756 (org-goto-line l)
14757 (setq m (get-text-property (point) 'org-hd-marker))
14758 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14759 (and agendap m))
14760 (setq buf (if agendap (marker-buffer m) (current-buffer))
14761 pos (if agendap m (point)))
14762 (with-current-buffer buf
14763 (save-excursion
14764 (save-restriction
14765 (goto-char pos)
14766 (setq cnt (1+ cnt))
14767 (org-toggle-tag tag (if off 'off 'on))
14768 (setq newhead (org-get-heading)))))
14769 (and agendap (org-agenda-change-all-lines newhead m))))
14770 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14772 (defun org-tags-completion-function (string predicate &optional flag)
14773 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14774 (confirm (lambda (x) (stringp (car x)))))
14775 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14776 (setq s1 (match-string 1 string)
14777 s2 (match-string 2 string))
14778 (setq s1 "" s2 string))
14779 (cond
14780 ((eq flag nil)
14781 ;; try completion
14782 (setq rtn (try-completion s2 ctable confirm))
14783 (if (stringp rtn)
14784 (setq rtn
14785 (concat s1 s2 (substring rtn (length s2))
14786 (if (and org-add-colon-after-tag-completion
14787 (assoc rtn ctable))
14788 ":" ""))))
14789 rtn)
14790 ((eq flag t)
14791 ;; all-completions
14792 (all-completions s2 ctable confirm))
14793 ((eq flag 'lambda)
14794 ;; exact match?
14795 (assoc s2 ctable)))))
14797 (defun org-fast-tag-insert (kwd tags face &optional end)
14798 "Insert KDW, and the TAGS, the latter with face FACE.
14799 Also insert END."
14800 (insert (format "%-12s" (concat kwd ":"))
14801 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14802 (or end "")))
14804 (defun org-fast-tag-show-exit (flag)
14805 (save-excursion
14806 (org-goto-line 3)
14807 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14808 (replace-match ""))
14809 (when flag
14810 (end-of-line 1)
14811 (org-move-to-column (- (window-width) 19) t)
14812 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14814 (defun org-set-current-tags-overlay (current prefix)
14815 "Add an overlay to CURRENT tag with PREFIX."
14816 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14817 (if (featurep 'xemacs)
14818 (org-overlay-display org-tags-overlay (concat prefix s)
14819 'secondary-selection)
14820 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14821 (org-overlay-display org-tags-overlay (concat prefix s)))))
14823 (defvar org-last-tag-selection-key nil)
14824 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14825 "Fast tag selection with single keys.
14826 CURRENT is the current list of tags in the headline, INHERITED is the
14827 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14828 possibly with grouping information. TODO-TABLE is a similar table with
14829 TODO keywords, should these have keys assigned to them.
14830 If the keys are nil, a-z are automatically assigned.
14831 Returns the new tags string, or nil to not change the current settings."
14832 (let* ((fulltable (append table todo-table))
14833 (maxlen (apply 'max (mapcar
14834 (lambda (x)
14835 (if (stringp (car x)) (string-width (car x)) 0))
14836 fulltable)))
14837 (buf (current-buffer))
14838 (expert (eq org-fast-tag-selection-single-key 'expert))
14839 (buffer-tags nil)
14840 (fwidth (+ maxlen 3 1 3))
14841 (ncol (/ (- (window-width) 4) fwidth))
14842 (i-face 'org-done)
14843 (c-face 'org-todo)
14844 tg cnt e c char c1 c2 ntable tbl rtn
14845 ov-start ov-end ov-prefix
14846 (exit-after-next org-fast-tag-selection-single-key)
14847 (done-keywords org-done-keywords)
14848 groups ingroup)
14849 (save-excursion
14850 (beginning-of-line 1)
14851 (if (looking-at
14852 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14853 (setq ov-start (match-beginning 1)
14854 ov-end (match-end 1)
14855 ov-prefix "")
14856 (setq ov-start (1- (point-at-eol))
14857 ov-end (1+ ov-start))
14858 (skip-chars-forward "^\n\r")
14859 (setq ov-prefix
14860 (concat
14861 (buffer-substring (1- (point)) (point))
14862 (if (> (current-column) org-tags-column)
14864 (make-string (- org-tags-column (current-column)) ?\ ))))))
14865 (move-overlay org-tags-overlay ov-start ov-end)
14866 (save-window-excursion
14867 (if expert
14868 (set-buffer (get-buffer-create " *Org tags*"))
14869 (delete-other-windows)
14870 (split-window-vertically)
14871 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14872 (erase-buffer)
14873 (org-set-local 'org-done-keywords done-keywords)
14874 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14875 (org-fast-tag-insert "Current" current c-face "\n\n")
14876 (org-fast-tag-show-exit exit-after-next)
14877 (org-set-current-tags-overlay current ov-prefix)
14878 (setq tbl fulltable char ?a cnt 0)
14879 (while (setq e (pop tbl))
14880 (cond
14881 ((equal (car e) :startgroup)
14882 (push '() groups) (setq ingroup t)
14883 (when (not (= cnt 0))
14884 (setq cnt 0)
14885 (insert "\n"))
14886 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14887 ((equal (car e) :endgroup)
14888 (setq ingroup nil cnt 0)
14889 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14890 ((equal e '(:newline))
14891 (when (not (= cnt 0))
14892 (setq cnt 0)
14893 (insert "\n")
14894 (setq e (car tbl))
14895 (while (equal (car tbl) '(:newline))
14896 (insert "\n")
14897 (setq tbl (cdr tbl)))))
14898 ((equal e '(:grouptags)) nil)
14900 (setq tg (copy-sequence (car e)) c2 nil)
14901 (if (cdr e)
14902 (setq c (cdr e))
14903 ;; automatically assign a character.
14904 (setq c1 (string-to-char
14905 (downcase (substring
14906 tg (if (= (string-to-char tg) ?@) 1 0)))))
14907 (if (or (rassoc c1 ntable) (rassoc c1 table))
14908 (while (or (rassoc char ntable) (rassoc char table))
14909 (setq char (1+ char)))
14910 (setq c2 c1))
14911 (setq c (or c2 char)))
14912 (if ingroup (push tg (car groups)))
14913 (setq tg (org-add-props tg nil 'face
14914 (cond
14915 ((not (assoc tg table))
14916 (org-get-todo-face tg))
14917 ((member tg current) c-face)
14918 ((member tg inherited) i-face))))
14919 (if (equal (caar tbl) :grouptags)
14920 (org-add-props tg nil 'face 'org-tag-group))
14921 (if (and (= cnt 0) (not ingroup)) (insert " "))
14922 (insert "[" c "] " tg (make-string
14923 (- fwidth 4 (length tg)) ?\ ))
14924 (push (cons tg c) ntable)
14925 (when (= (setq cnt (1+ cnt)) ncol)
14926 (insert "\n")
14927 (if ingroup (insert " "))
14928 (setq cnt 0)))))
14929 (setq ntable (nreverse ntable))
14930 (insert "\n")
14931 (goto-char (point-min))
14932 (if (not expert) (org-fit-window-to-buffer))
14933 (setq rtn
14934 (catch 'exit
14935 (while t
14936 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14937 (if (not groups) "no " "")
14938 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14939 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14940 (setq org-last-tag-selection-key c)
14941 (cond
14942 ((= c ?\r) (throw 'exit t))
14943 ((= c ?!)
14944 (setq groups (not groups))
14945 (goto-char (point-min))
14946 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14947 ((= c ?\C-c)
14948 (if (not expert)
14949 (org-fast-tag-show-exit
14950 (setq exit-after-next (not exit-after-next)))
14951 (setq expert nil)
14952 (delete-other-windows)
14953 (set-window-buffer (split-window-vertically) " *Org tags*")
14954 (org-switch-to-buffer-other-window " *Org tags*")
14955 (org-fit-window-to-buffer)))
14956 ((or (= c ?\C-g)
14957 (and (= c ?q) (not (rassoc c ntable))))
14958 (org-detach-overlay org-tags-overlay)
14959 (setq quit-flag t))
14960 ((= c ?\ )
14961 (setq current nil)
14962 (if exit-after-next (setq exit-after-next 'now)))
14963 ((= c ?\t)
14964 (condition-case nil
14965 (setq tg (org-icompleting-read
14966 "Tag: "
14967 (or buffer-tags
14968 (with-current-buffer buf
14969 (org-get-buffer-tags)))))
14970 (quit (setq tg "")))
14971 (when (string-match "\\S-" tg)
14972 (add-to-list 'buffer-tags (list tg))
14973 (if (member tg current)
14974 (setq current (delete tg current))
14975 (push tg current)))
14976 (if exit-after-next (setq exit-after-next 'now)))
14977 ((setq e (rassoc c todo-table) tg (car e))
14978 (with-current-buffer buf
14979 (save-excursion (org-todo tg)))
14980 (if exit-after-next (setq exit-after-next 'now)))
14981 ((setq e (rassoc c ntable) tg (car e))
14982 (if (member tg current)
14983 (setq current (delete tg current))
14984 (loop for g in groups do
14985 (if (member tg g)
14986 (mapc (lambda (x)
14987 (setq current (delete x current)))
14988 g)))
14989 (push tg current))
14990 (if exit-after-next (setq exit-after-next 'now))))
14992 ;; Create a sorted list
14993 (setq current
14994 (sort current
14995 (lambda (a b)
14996 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14997 (if (eq exit-after-next 'now) (throw 'exit t))
14998 (goto-char (point-min))
14999 (beginning-of-line 2)
15000 (delete-region (point) (point-at-eol))
15001 (org-fast-tag-insert "Current" current c-face)
15002 (org-set-current-tags-overlay current ov-prefix)
15003 (while (re-search-forward
15004 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15005 (setq tg (match-string 1))
15006 (add-text-properties
15007 (match-beginning 1) (match-end 1)
15008 (list 'face
15009 (cond
15010 ((member tg current) c-face)
15011 ((member tg inherited) i-face)
15012 (t (get-text-property (match-beginning 1) 'face))))))
15013 (goto-char (point-min)))))
15014 (org-detach-overlay org-tags-overlay)
15015 (if rtn
15016 (mapconcat 'identity current ":")
15017 nil))))
15019 (defun org-get-tags-string ()
15020 "Get the TAGS string in the current headline."
15021 (unless (org-at-heading-p t)
15022 (user-error "Not on a heading"))
15023 (save-excursion
15024 (beginning-of-line 1)
15025 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15026 (org-match-string-no-properties 1)
15027 "")))
15029 (defun org-get-tags ()
15030 "Get the list of tags specified in the current headline."
15031 (org-split-string (org-get-tags-string) ":"))
15033 (defun org-get-buffer-tags ()
15034 "Get a table of all tags used in the buffer, for completion."
15035 (let (tags)
15036 (save-excursion
15037 (goto-char (point-min))
15038 (while (re-search-forward
15039 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15040 (when (equal (char-after (point-at-bol 0)) ?*)
15041 (mapc (lambda (x) (add-to-list 'tags x))
15042 (org-split-string (org-match-string-no-properties 1) ":")))))
15043 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15044 (mapcar 'list tags)))
15046 ;;;; The mapping API
15048 (defun org-map-entries (func &optional match scope &rest skip)
15049 "Call FUNC at each headline selected by MATCH in SCOPE.
15051 FUNC is a function or a lisp form. The function will be called without
15052 arguments, with the cursor positioned at the beginning of the headline.
15053 The return values of all calls to the function will be collected and
15054 returned as a list.
15056 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15057 does not need to preserve point. After evaluation, the cursor will be
15058 moved to the end of the line (presumably of the headline of the
15059 processed entry) and search continues from there. Under some
15060 circumstances, this may not produce the wanted results. For example,
15061 if you have removed (e.g. archived) the current (sub)tree it could
15062 mean that the next entry will be skipped entirely. In such cases, you
15063 can specify the position from where search should continue by making
15064 FUNC set the variable `org-map-continue-from' to the desired buffer
15065 position.
15067 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15068 Only headlines that are matched by this query will be considered during
15069 the iteration. When MATCH is nil or t, all headlines will be
15070 visited by the iteration.
15072 SCOPE determines the scope of this command. It can be any of:
15074 nil The current buffer, respecting the restriction if any
15075 tree The subtree started with the entry at point
15076 region The entries within the active region, if any
15077 region-start-level
15078 The entries within the active region, but only those at
15079 the same level than the first one.
15080 file The current buffer, without restriction
15081 file-with-archives
15082 The current buffer, and any archives associated with it
15083 agenda All agenda files
15084 agenda-with-archives
15085 All agenda files with any archive files associated with them
15086 \(file1 file2 ...)
15087 If this is a list, all files in the list will be scanned
15089 The remaining args are treated as settings for the skipping facilities of
15090 the scanner. The following items can be given here:
15092 archive skip trees with the archive tag
15093 comment skip trees with the COMMENT keyword
15094 function or Emacs Lisp form:
15095 will be used as value for `org-agenda-skip-function', so
15096 whenever the function returns a position, FUNC will not be
15097 called for that entry and search will continue from the
15098 position returned
15100 If your function needs to retrieve the tags including inherited tags
15101 at the *current* entry, you can use the value of the variable
15102 `org-scanner-tags' which will be much faster than getting the value
15103 with `org-get-tags-at'. If your function gets properties with
15104 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15105 to t around the call to `org-entry-properties' to get the same speedup.
15106 Note that if your function moves around to retrieve tags and properties at
15107 a *different* entry, you cannot use these techniques."
15108 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15109 (not (org-region-active-p)))
15110 (let* ((org-agenda-archives-mode nil) ; just to make sure
15111 (org-agenda-skip-archived-trees (memq 'archive skip))
15112 (org-agenda-skip-comment-trees (memq 'comment skip))
15113 (org-agenda-skip-function
15114 (car (org-delete-all '(comment archive) skip)))
15115 (org-tags-match-list-sublevels t)
15116 (start-level (eq scope 'region-start-level))
15117 matcher file res
15118 org-todo-keywords-for-agenda
15119 org-done-keywords-for-agenda
15120 org-todo-keyword-alist-for-agenda
15121 org-tag-alist-for-agenda
15122 todo-only)
15124 (cond
15125 ((eq match t) (setq matcher t))
15126 ((eq match nil) (setq matcher t))
15127 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15129 (save-excursion
15130 (save-restriction
15131 (cond ((eq scope 'tree)
15132 (org-back-to-heading t)
15133 (org-narrow-to-subtree)
15134 (setq scope nil))
15135 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15136 (org-region-active-p))
15137 ;; If needed, set start-level to a string like "2"
15138 (when start-level
15139 (save-excursion
15140 (goto-char (region-beginning))
15141 (unless (org-at-heading-p) (outline-next-heading))
15142 (setq start-level (org-current-level))))
15143 (narrow-to-region (region-beginning)
15144 (save-excursion
15145 (goto-char (region-end))
15146 (unless (and (bolp) (org-at-heading-p))
15147 (outline-next-heading))
15148 (point)))
15149 (setq scope nil)))
15151 (if (not scope)
15152 (progn
15153 (org-agenda-prepare-buffers
15154 (list (buffer-file-name (current-buffer))))
15155 (setq res (org-scan-tags func matcher todo-only start-level)))
15156 ;; Get the right scope
15157 (cond
15158 ((and scope (listp scope) (symbolp (car scope)))
15159 (setq scope (eval scope)))
15160 ((eq scope 'agenda)
15161 (setq scope (org-agenda-files t)))
15162 ((eq scope 'agenda-with-archives)
15163 (setq scope (org-agenda-files t))
15164 (setq scope (org-add-archive-files scope)))
15165 ((eq scope 'file)
15166 (setq scope (list (buffer-file-name))))
15167 ((eq scope 'file-with-archives)
15168 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15169 (org-agenda-prepare-buffers scope)
15170 (while (setq file (pop scope))
15171 (with-current-buffer (org-find-base-buffer-visiting file)
15172 (save-excursion
15173 (save-restriction
15174 (widen)
15175 (goto-char (point-min))
15176 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15177 res)))
15179 ;;;; Properties
15181 ;;; Setting and retrieving properties
15183 (defconst org-special-properties
15184 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15185 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15186 "The special properties valid in Org-mode.
15188 These are properties that are not defined in the property drawer,
15189 but in some other way.")
15191 (defconst org-default-properties
15192 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15193 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15194 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15195 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15196 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15197 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15198 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15199 "Some properties that are used by Org-mode for various purposes.
15200 Being in this list makes sure that they are offered for completion.")
15202 (defun org-property-action ()
15203 "Do an action on properties."
15204 (interactive)
15205 (let (c)
15206 (org-at-property-p)
15207 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15208 (setq c (read-char-exclusive))
15209 (cond
15210 ((equal c ?s)
15211 (call-interactively 'org-set-property))
15212 ((equal c ?d)
15213 (call-interactively 'org-delete-property))
15214 ((equal c ?D)
15215 (call-interactively 'org-delete-property-globally))
15216 ((equal c ?c)
15217 (call-interactively 'org-compute-property-at-point))
15218 (t (user-error "No such property action %c" c)))))
15220 (defun org-inc-effort ()
15221 "Increment the value of the effort property in the current entry."
15222 (interactive)
15223 (org-set-effort nil t))
15225 (defvar org-clock-effort) ;; Defined in org-clock.el
15226 (defvar org-clock-current-task) ;; Defined in org-clock.el
15227 (defun org-set-effort (&optional value increment)
15228 "Set the effort property of the current entry.
15229 With numerical prefix arg, use the nth allowed value, 0 stands for the
15230 10th allowed value.
15232 When INCREMENT is non-nil, set the property to the next allowed value."
15233 (interactive "P")
15234 (if (equal value 0) (setq value 10))
15235 (let* ((completion-ignore-case t)
15236 (prop org-effort-property)
15237 (cur (org-entry-get nil prop))
15238 (allowed (org-property-get-allowed-values nil prop 'table))
15239 (existing (mapcar 'list (org-property-values prop)))
15240 (heading (nth 4 (org-heading-components)))
15242 (val (cond
15243 ((stringp value) value)
15244 ((and allowed (integerp value))
15245 (or (car (nth (1- value) allowed))
15246 (car (org-last allowed))))
15247 ((and allowed increment)
15248 (or (caadr (member (list cur) allowed))
15249 (user-error "Allowed effort values are not set")))
15250 (allowed
15251 (message "Select 1-9,0, [RET%s]: %s"
15252 (if cur (concat "=" cur) "")
15253 (mapconcat 'car allowed " "))
15254 (setq rpl (read-char-exclusive))
15255 (if (equal rpl ?\r)
15257 (setq rpl (- rpl ?0))
15258 (if (equal rpl 0) (setq rpl 10))
15259 (if (and (> rpl 0) (<= rpl (length allowed)))
15260 (car (nth (1- rpl) allowed))
15261 (org-completing-read "Effort: " allowed nil))))
15263 (let (org-completion-use-ido org-completion-use-iswitchb)
15264 (org-completing-read
15265 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15266 (concat "[" cur "]") "")
15267 ": ")
15268 existing nil nil "" nil cur))))))
15269 (unless (equal (org-entry-get nil prop) val)
15270 (org-entry-put nil prop val))
15271 (save-excursion
15272 (org-back-to-heading t)
15273 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15274 (when (string= heading org-clock-current-task)
15275 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15276 (org-clock-update-mode-line))
15277 (message "%s is now %s" prop val)))
15279 (defun org-at-property-p ()
15280 "Is cursor inside a property drawer?"
15281 (save-excursion
15282 (when (equal 'node-property (car (org-element-at-point)))
15283 (beginning-of-line 1)
15284 (looking-at org-property-re))))
15286 (defun org-get-property-block (&optional beg end force)
15287 "Return the (beg . end) range of the body of the property drawer.
15288 BEG and END are the beginning and end of the current subtree, or of
15289 the part before the first headline. If they are not given, they will
15290 be found. If the drawer does not exist and FORCE is non-nil, create
15291 the drawer."
15292 (catch 'exit
15293 (save-excursion
15294 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15295 (progn (org-back-to-heading t) (point))))
15296 (end (or end (and (not (outline-next-heading)) (point-max))
15297 (point))))
15298 (goto-char beg)
15299 (if (re-search-forward org-property-start-re end t)
15300 (setq beg (1+ (match-end 0)))
15301 (if force
15302 (save-excursion
15303 (org-insert-property-drawer)
15304 (setq end (progn (outline-next-heading) (point))))
15305 (throw 'exit nil))
15306 (goto-char beg)
15307 (if (re-search-forward org-property-start-re end t)
15308 (setq beg (1+ (match-end 0)))))
15309 (if (re-search-forward org-property-end-re end t)
15310 (setq end (match-beginning 0))
15311 (or force (throw 'exit nil))
15312 (goto-char beg)
15313 (setq end beg)
15314 (org-indent-line)
15315 (insert ":END:\n"))
15316 (cons beg end)))))
15318 (defun org-entry-properties (&optional pom which specific)
15319 "Get all properties of the entry at point-or-marker POM.
15320 This includes the TODO keyword, the tags, time strings for deadline,
15321 scheduled, and clocking, and any additional properties defined in the
15322 entry. The return value is an alist, keys may occur multiple times
15323 if the property key was used several times.
15324 POM may also be nil, in which case the current entry is used.
15325 If WHICH is nil or `all', get all properties. If WHICH is
15326 `special' or `standard', only get that subclass. If WHICH
15327 is a string only get exactly this property. SPECIFIC can be a string, the
15328 specific property we are interested in. Specifying it can speed
15329 things up because then unnecessary parsing is avoided."
15330 (setq which (or which 'all))
15331 (org-with-wide-buffer
15332 (org-with-point-at pom
15333 (let ((clockstr (substring org-clock-string 0 -1))
15334 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15335 (case-fold-search nil)
15336 beg end range props sum-props key key1 value string clocksum clocksumt)
15337 (when (and (derived-mode-p 'org-mode)
15338 (ignore-errors (org-back-to-heading t)))
15339 (setq beg (point))
15340 (setq sum-props (get-text-property (point) 'org-summaries))
15341 (setq clocksum (get-text-property (point) :org-clock-minutes)
15342 clocksumt (get-text-property (point) :org-clock-minutes-today))
15343 (outline-next-heading)
15344 (setq end (point))
15345 (when (memq which '(all special))
15346 ;; Get the special properties, like TODO and tags
15347 (goto-char beg)
15348 (when (and (or (not specific) (string= specific "TODO"))
15349 (looking-at org-todo-line-regexp) (match-end 2))
15350 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15351 (when (and (or (not specific) (string= specific "PRIORITY"))
15352 (looking-at org-priority-regexp))
15353 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15354 (when (or (not specific) (string= specific "FILE"))
15355 (push (cons "FILE" buffer-file-name) props))
15356 (when (and (or (not specific) (string= specific "TAGS"))
15357 (setq value (org-get-tags-string))
15358 (string-match "\\S-" value))
15359 (push (cons "TAGS" value) props))
15360 (when (and (or (not specific) (string= specific "ALLTAGS"))
15361 (setq value (org-get-tags-at)))
15362 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15363 ":"))
15364 props))
15365 (when (or (not specific) (string= specific "BLOCKED"))
15366 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15367 (when (or (not specific)
15368 (member specific
15369 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15370 "TIMESTAMP" "TIMESTAMP_IA")))
15371 (catch 'match
15372 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15373 (setq key (if (match-end 1)
15374 (substring (org-match-string-no-properties 1)
15375 0 -1))
15376 string (if (equal key clockstr)
15377 (org-trim
15378 (buffer-substring-no-properties
15379 (match-beginning 3) (goto-char
15380 (point-at-eol))))
15381 (substring (org-match-string-no-properties 3)
15382 1 -1)))
15383 ;; Get the correct property name from the key. This is
15384 ;; necessary if the user has configured time keywords.
15385 (setq key1 (concat key ":"))
15386 (cond
15387 ((not key)
15388 (setq key
15389 (if (= (char-after (match-beginning 3)) ?\[)
15390 "TIMESTAMP_IA" "TIMESTAMP")))
15391 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15392 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15393 ((equal key1 org-closed-string) (setq key "CLOSED"))
15394 ((equal key1 org-clock-string) (setq key "CLOCK")))
15395 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15396 (progn
15397 (push (cons key string) props)
15398 ;; no need to search further if match is found
15399 (throw 'match t))
15400 (when (or (equal key "CLOCK") (not (assoc key props)))
15401 (push (cons key string) props)))))))
15403 (when (memq which '(all standard))
15404 ;; Get the standard properties, like :PROP: ...
15405 (setq range (org-get-property-block beg end))
15406 (when range
15407 (goto-char (car range))
15408 (while (re-search-forward org-property-re
15409 (cdr range) t)
15410 (setq key (org-match-string-no-properties 2)
15411 value (org-trim (or (org-match-string-no-properties 3) "")))
15412 (unless (member key excluded)
15413 (push (cons key (or value "")) props)))))
15414 (if clocksum
15415 (push (cons "CLOCKSUM"
15416 (org-columns-number-to-string (/ (float clocksum) 60.)
15417 'add_times))
15418 props))
15419 (if clocksumt
15420 (push (cons "CLOCKSUM_T"
15421 (org-columns-number-to-string (/ (float clocksumt) 60.)
15422 'add_times))
15423 props))
15424 (unless (assoc "CATEGORY" props)
15425 (push (cons "CATEGORY" (org-get-category)) props))
15426 (append sum-props (nreverse props)))))))
15428 (defun org-entry-get (pom property &optional inherit literal-nil)
15429 "Get value of PROPERTY for entry or content at point-or-marker POM.
15430 If INHERIT is non-nil and the entry does not have the property,
15431 then also check higher levels of the hierarchy.
15432 If INHERIT is the symbol `selective', use inheritance only if the setting
15433 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15434 If the property is present but empty, the return value is the empty string.
15435 If the property is not present at all, nil is returned.
15437 Return the value as a string.
15439 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15440 do not interpret it as the list atom nil. This is used for inheritance
15441 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15442 (org-with-point-at pom
15443 (if (and inherit (if (eq inherit 'selective)
15444 (org-property-inherit-p property)
15446 (org-entry-get-with-inheritance property literal-nil)
15447 (if (member property org-special-properties)
15448 ;; We need a special property. Use `org-entry-properties'
15449 ;; to retrieve it, but specify the wanted property
15450 (cdr (assoc property (org-entry-properties nil 'special property)))
15451 (org-with-wide-buffer
15452 (let ((range (org-get-property-block)))
15453 (when (and range (not (eq (car range) (cdr range)))
15454 (save-excursion
15455 (goto-char (car range))
15456 (re-search-forward
15457 (concat (org-re-property property) "\\|"
15458 (org-re-property (concat property "+")))
15459 (cdr range) t)))
15460 (let* ((props
15461 (list (or (assoc property org-file-properties)
15462 (assoc property org-global-properties)
15463 (assoc property org-global-properties-fixed))))
15464 (ap (lambda (key)
15465 (when (re-search-forward
15466 (org-re-property key) (cdr range) t)
15467 (setq props
15468 (org-update-property-plist
15470 (if (match-end 3)
15471 (org-match-string-no-properties 3) "")
15472 props)))))
15473 val)
15474 (goto-char (car range))
15475 (funcall ap property)
15476 (goto-char (car range))
15477 (while (funcall ap (concat property "+")))
15478 (setq val (cdr (assoc property props)))
15479 (when val (if literal-nil val (org-not-nil val)))))))))))
15481 (defun org-property-or-variable-value (var &optional inherit)
15482 "Check if there is a property fixing the value of VAR.
15483 If yes, return this value. If not, return the current value of the variable."
15484 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15485 (if (and prop (stringp prop) (string-match "\\S-" prop))
15486 (read prop)
15487 (symbol-value var))))
15489 (defun org-entry-delete (pom property)
15490 "Delete the property PROPERTY from entry at point-or-marker POM."
15491 (unless (member property org-special-properties)
15492 (org-with-point-at pom
15493 (let ((range (org-get-property-block)))
15494 (if (and range
15495 (goto-char (car range))
15496 (re-search-forward
15497 (org-re-property property)
15498 (cdr range) t))
15499 (progn
15500 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15501 (org-remove-empty-drawer-at (car range))
15503 nil)))))
15505 ;; Multi-values properties are properties that contain multiple values
15506 ;; These values are assumed to be single words, separated by whitespace.
15507 (defun org-entry-add-to-multivalued-property (pom property value)
15508 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15509 (let* ((old (org-entry-get pom property))
15510 (values (and old (org-split-string old "[ \t]"))))
15511 (setq value (org-entry-protect-space value))
15512 (unless (member value values)
15513 (setq values (append values (list value)))
15514 (org-entry-put pom property
15515 (mapconcat 'identity values " ")))))
15517 (defun org-entry-remove-from-multivalued-property (pom property value)
15518 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15519 (let* ((old (org-entry-get pom property))
15520 (values (and old (org-split-string old "[ \t]"))))
15521 (setq value (org-entry-protect-space value))
15522 (when (member value values)
15523 (setq values (delete value values))
15524 (org-entry-put pom property
15525 (mapconcat 'identity values " ")))))
15527 (defun org-entry-member-in-multivalued-property (pom property value)
15528 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15529 (let* ((old (org-entry-get pom property))
15530 (values (and old (org-split-string old "[ \t]"))))
15531 (setq value (org-entry-protect-space value))
15532 (member value values)))
15534 (defun org-entry-get-multivalued-property (pom property)
15535 "Return a list of values in a multivalued property."
15536 (let* ((value (org-entry-get pom property))
15537 (values (and value (org-split-string value "[ \t]"))))
15538 (mapcar 'org-entry-restore-space values)))
15540 (defun org-entry-put-multivalued-property (pom property &rest values)
15541 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15542 VALUES should be a list of strings. Spaces will be protected."
15543 (org-entry-put pom property
15544 (mapconcat 'org-entry-protect-space values " "))
15545 (let* ((value (org-entry-get pom property))
15546 (values (and value (org-split-string value "[ \t]"))))
15547 (mapcar 'org-entry-restore-space values)))
15549 (defun org-entry-protect-space (s)
15550 "Protect spaces and newline in string S."
15551 (while (string-match " " s)
15552 (setq s (replace-match "%20" t t s)))
15553 (while (string-match "\n" s)
15554 (setq s (replace-match "%0A" t t s)))
15557 (defun org-entry-restore-space (s)
15558 "Restore spaces and newline in string S."
15559 (while (string-match "%20" s)
15560 (setq s (replace-match " " t t s)))
15561 (while (string-match "%0A" s)
15562 (setq s (replace-match "\n" t t s)))
15565 (defvar org-entry-property-inherited-from (make-marker)
15566 "Marker pointing to the entry from where a property was inherited.
15567 Each call to `org-entry-get-with-inheritance' will set this marker to the
15568 location of the entry where the inheritance search matched. If there was
15569 no match, the marker will point nowhere.
15570 Note that also `org-entry-get' calls this function, if the INHERIT flag
15571 is set.")
15573 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15574 "Get PROPERTY of entry or content at point, search higher levels if needed.
15575 The search will stop at the first ancestor which has the property defined.
15576 If the value found is \"nil\", return nil to show that the property
15577 should be considered as undefined (this is the meaning of nil here).
15578 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15579 (move-marker org-entry-property-inherited-from nil)
15580 (let (tmp)
15581 (save-excursion
15582 (save-restriction
15583 (widen)
15584 (catch 'ex
15585 (while t
15586 (when (setq tmp (org-entry-get nil property nil literal-nil))
15587 (or (ignore-errors (org-back-to-heading t))
15588 (goto-char (point-min)))
15589 (move-marker org-entry-property-inherited-from (point))
15590 (throw 'ex tmp))
15591 (or (ignore-errors (org-up-heading-safe))
15592 (throw 'ex nil))))))
15593 (setq tmp (or tmp
15594 (cdr (assoc property org-file-properties))
15595 (cdr (assoc property org-global-properties))
15596 (cdr (assoc property org-global-properties-fixed))))
15597 (if literal-nil tmp (org-not-nil tmp))))
15599 (defvar org-property-changed-functions nil
15600 "Hook called when the value of a property has changed.
15601 Each hook function should accept two arguments, the name of the property
15602 and the new value.")
15604 (defun org-entry-put (pom property value)
15605 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15606 If the value is `nil', it is converted to the empty string.
15607 If it is not a string, an error is raised."
15608 (cond ((null value) (setq value ""))
15609 ((not (stringp value))
15610 (error "Properties values should be strings.")))
15611 (org-with-point-at pom
15612 (org-back-to-heading t)
15613 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15614 range)
15615 (cond
15616 ((equal property "TODO")
15617 (when (and (string-match "\\S-" value)
15618 (not (member value org-todo-keywords-1)))
15619 (user-error "\"%s\" is not a valid TODO state" value))
15620 (if (or (not value)
15621 (not (string-match "\\S-" value)))
15622 (setq value 'none))
15623 (org-todo value)
15624 (org-set-tags nil 'align))
15625 ((equal property "PRIORITY")
15626 (org-priority (if (and value (string-match "\\S-" value))
15627 (string-to-char value) ?\ ))
15628 (org-set-tags nil 'align))
15629 ((equal property "CLOCKSUM")
15630 (if (not (re-search-forward
15631 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15632 (error "Cannot find a clock log")
15633 (goto-char (- (match-end 1) 2))
15634 (cond
15635 ((eq value 'earlier) (org-timestamp-down))
15636 ((eq value 'later) (org-timestamp-up)))
15637 (org-clock-sum-current-item)))
15638 ((equal property "SCHEDULED")
15639 (if (re-search-forward org-scheduled-time-regexp end t)
15640 (cond
15641 ((eq value 'earlier) (org-timestamp-change -1 'day))
15642 ((eq value 'later) (org-timestamp-change 1 'day))
15643 (t (call-interactively 'org-schedule)))
15644 (call-interactively 'org-schedule)))
15645 ((equal property "DEADLINE")
15646 (if (re-search-forward org-deadline-time-regexp end t)
15647 (cond
15648 ((eq value 'earlier) (org-timestamp-change -1 'day))
15649 ((eq value 'later) (org-timestamp-change 1 'day))
15650 (t (call-interactively 'org-deadline)))
15651 (call-interactively 'org-deadline)))
15652 ((member property org-special-properties)
15653 (error "The %s property can not yet be set with `org-entry-put'"
15654 property))
15655 (t ; a non-special property
15656 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15657 (setq range (org-get-property-block beg end 'force))
15658 (goto-char (car range))
15659 (if (re-search-forward
15660 (org-re-property property) (cdr range) t)
15661 (progn
15662 (delete-region (match-beginning 0) (match-end 0))
15663 (goto-char (match-beginning 0)))
15664 (goto-char (cdr range))
15665 (insert "\n")
15666 (backward-char 1)
15667 (org-indent-line))
15668 (insert ":" property ":")
15669 (and value (insert " " value))
15670 (org-indent-line)))))
15671 (run-hook-with-args 'org-property-changed-functions property value)))
15673 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15674 "Get all property keys in the current buffer.
15675 With INCLUDE-SPECIALS, also list the special properties that reflect things
15676 like tags and TODO state.
15677 With INCLUDE-DEFAULTS, also include properties that has special meaning
15678 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15679 and others.
15680 With INCLUDE-COLUMNS, also include property names given in COLUMN
15681 formats in the current buffer."
15682 (let (rtn range cfmt s p)
15683 (save-excursion
15684 (save-restriction
15685 (widen)
15686 (goto-char (point-min))
15687 (while (re-search-forward org-property-start-re nil t)
15688 (setq range (org-get-property-block))
15689 (goto-char (car range))
15690 (while (re-search-forward org-property-re
15691 (cdr range) t)
15692 (add-to-list 'rtn (org-match-string-no-properties 2)))
15693 (outline-next-heading))))
15695 (when include-specials
15696 (setq rtn (append org-special-properties rtn)))
15698 (when include-defaults
15699 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15700 (add-to-list 'rtn org-effort-property))
15702 (when include-columns
15703 (save-excursion
15704 (save-restriction
15705 (widen)
15706 (goto-char (point-min))
15707 (while (re-search-forward
15708 "^[ \t]*\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15709 nil t)
15710 (setq cfmt (match-string 2) s 0)
15711 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15712 cfmt s)
15713 (setq s (match-end 0)
15714 p (match-string 1 cfmt))
15715 (unless (or (equal p "ITEM")
15716 (member p org-special-properties))
15717 (add-to-list 'rtn (match-string 1 cfmt))))))))
15719 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15721 (defun org-property-values (key)
15722 "Return a list of all values of property KEY in the current buffer."
15723 (save-excursion
15724 (save-restriction
15725 (widen)
15726 (goto-char (point-min))
15727 (let ((re (org-re-property key))
15728 values)
15729 (while (re-search-forward re nil t)
15730 (add-to-list 'values (org-trim (match-string 3))))
15731 (delete "" values)))))
15733 (defun org-insert-property-drawer ()
15734 "Insert a property drawer into the current entry."
15735 (org-back-to-heading t)
15736 (looking-at org-outline-regexp)
15737 (let ((indent (if org-adapt-indentation
15738 (- (match-end 0) (match-beginning 0))
15740 (beg (point))
15741 (re (concat "^[ \t]*" org-keyword-time-regexp))
15742 end hiddenp)
15743 (outline-next-heading)
15744 (setq end (point))
15745 (goto-char beg)
15746 (while (re-search-forward re end t))
15747 (setq hiddenp (outline-invisible-p))
15748 (end-of-line 1)
15749 (and (equal (char-after) ?\n) (forward-char 1))
15750 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15751 (if (member (match-string 1) '("CLOCK:" ":END:"))
15752 ;; just skip this line
15753 (beginning-of-line 2)
15754 ;; Drawer start, find the end
15755 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15756 (beginning-of-line 1)))
15757 (org-skip-over-state-notes)
15758 (skip-chars-backward " \t\n\r")
15759 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15760 (forward-char 1))
15761 (goto-char (point-at-eol))
15762 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15763 (beginning-of-line 0)
15764 (org-indent-to-column indent)
15765 (beginning-of-line 2)
15766 (org-indent-to-column indent)
15767 (beginning-of-line 0)
15768 (if hiddenp
15769 (save-excursion
15770 (org-back-to-heading t)
15771 (hide-entry))
15772 (org-flag-drawer t))))
15774 (defun org-insert-drawer (&optional arg drawer)
15775 "Insert a drawer at point.
15777 Optional argument DRAWER, when non-nil, is a string representing
15778 drawer's name. Otherwise, the user is prompted for a name.
15780 If a region is active, insert the drawer around that region
15781 instead.
15783 Point is left between drawer's boundaries."
15784 (interactive "P")
15785 (let* ((drawer (if arg "PROPERTIES"
15786 (or drawer (read-from-minibuffer "Drawer: ")))))
15787 (cond
15788 ;; With C-u, fall back on `org-insert-property-drawer'
15789 (arg (org-insert-property-drawer))
15791 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15792 (user-error "Invalid drawer name"))
15793 ;; With an active region, insert a drawer at point.
15794 ((not (org-region-active-p))
15795 (progn
15796 (unless (bolp) (insert "\n"))
15797 (insert (format ":%s:\n\n:END:\n" drawer))
15798 (forward-line -2)))
15799 ;; Otherwise, insert the drawer at point
15801 (let ((rbeg (region-beginning))
15802 (rend (copy-marker (region-end))))
15803 (unwind-protect
15804 (progn
15805 (goto-char rbeg)
15806 (beginning-of-line)
15807 (when (save-excursion
15808 (re-search-forward org-outline-regexp-bol rend t))
15809 (user-error "Drawers cannot contain headlines"))
15810 ;; Position point at the beginning of the first
15811 ;; non-blank line in region. Insert drawer's opening
15812 ;; there, then indent it.
15813 (org-skip-whitespace)
15814 (beginning-of-line)
15815 (insert ":" drawer ":\n")
15816 (forward-line -1)
15817 (indent-for-tab-command)
15818 ;; Move point to the beginning of the first blank line
15819 ;; after the last non-blank line in region. Insert
15820 ;; drawer's closing, then indent it.
15821 (goto-char rend)
15822 (skip-chars-backward " \r\t\n")
15823 (insert "\n:END:")
15824 (deactivate-mark t)
15825 (indent-for-tab-command)
15826 (unless (eolp) (insert "\n")))
15827 ;; Clear marker, whatever the outcome of insertion is.
15828 (set-marker rend nil)))))))
15830 (defvar org-property-set-functions-alist nil
15831 "Property set function alist.
15832 Each entry should have the following format:
15834 (PROPERTY . READ-FUNCTION)
15836 The read function will be called with the same argument as
15837 `org-completing-read'.")
15839 (defun org-set-property-function (property)
15840 "Get the function that should be used to set PROPERTY.
15841 This is computed according to `org-property-set-functions-alist'."
15842 (or (cdr (assoc property org-property-set-functions-alist))
15843 'org-completing-read))
15845 (defun org-read-property-value (property)
15846 "Read PROPERTY value from user."
15847 (let* ((completion-ignore-case t)
15848 (allowed (org-property-get-allowed-values nil property 'table))
15849 (cur (org-entry-get nil property))
15850 (prompt (concat property " value"
15851 (if (and cur (string-match "\\S-" cur))
15852 (concat " [" cur "]") "") ": "))
15853 (set-function (org-set-property-function property))
15854 (val (if allowed
15855 (funcall set-function prompt allowed nil
15856 (not (get-text-property 0 'org-unrestricted
15857 (caar allowed))))
15858 (let (org-completion-use-ido org-completion-use-iswitchb)
15859 (funcall set-function prompt
15860 (mapcar 'list (org-property-values property))
15861 nil nil "" nil cur)))))
15862 (if (equal val "")
15864 val)))
15866 (defvar org-last-set-property nil)
15867 (defvar org-last-set-property-value nil)
15868 (defun org-read-property-name ()
15869 "Read a property name."
15870 (let* ((completion-ignore-case t)
15871 (keys (org-buffer-property-keys nil t t))
15872 (default-prop (or (save-excursion
15873 (save-match-data
15874 (beginning-of-line)
15875 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15876 (null (string= (match-string 1) "END"))
15877 (match-string 1))))
15878 org-last-set-property))
15879 (property (org-icompleting-read
15880 (concat "Property"
15881 (if default-prop (concat " [" default-prop "]") "")
15882 ": ")
15883 (mapcar 'list keys)
15884 nil nil nil nil
15885 default-prop)))
15886 (if (member property keys)
15887 property
15888 (or (cdr (assoc (downcase property)
15889 (mapcar (lambda (x) (cons (downcase x) x))
15890 keys)))
15891 property))))
15893 (defun org-set-property-and-value (use-last)
15894 "Allow to set [PROPERTY]: [value] direction from prompt.
15895 When use-default, don't even ask, just use the last
15896 \"[PROPERTY]: [value]\" string from the history."
15897 (interactive "P")
15898 (let* ((completion-ignore-case t)
15899 (pv (or (and use-last org-last-set-property-value)
15900 (org-completing-read
15901 "Enter a \"[Property]: [value]\" pair: "
15902 nil nil nil nil nil
15903 org-last-set-property-value)))
15904 prop val)
15905 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15906 (setq prop (match-string 1 pv)
15907 val (match-string 2 pv))
15908 (org-set-property prop val))))
15910 (defun org-set-property (property value)
15911 "In the current entry, set PROPERTY to VALUE.
15912 When called interactively, this will prompt for a property name, offering
15913 completion on existing and default properties. And then it will prompt
15914 for a value, offering completion either on allowed values (via an inherited
15915 xxx_ALL property) or on existing values in other instances of this property
15916 in the current file."
15917 (interactive (list nil nil))
15918 (let* ((property (or property (org-read-property-name)))
15919 (value (or value (org-read-property-value property)))
15920 (fn (cdr (assoc property org-properties-postprocess-alist))))
15921 (setq org-last-set-property property)
15922 (setq org-last-set-property-value (concat property ": " value))
15923 ;; Possibly postprocess the inserted value:
15924 (when fn (setq value (funcall fn value)))
15925 (unless (equal (org-entry-get nil property) value)
15926 (org-entry-put nil property value))))
15928 (defun org-delete-property (property)
15929 "In the current entry, delete PROPERTY."
15930 (interactive
15931 (let* ((completion-ignore-case t)
15932 (cat (org-entry-get (point) "CATEGORY"))
15933 (props0 (org-entry-properties nil 'standard))
15934 (props (if cat props0
15935 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15936 (prop (if (< 1 (length props))
15937 (org-icompleting-read "Property: " props nil t)
15938 (caar props))))
15939 (list prop)))
15940 (if (org-entry-delete nil property)
15941 (message "Property %s deleted" property)))
15943 (defun org-delete-property-globally (property)
15944 "Remove PROPERTY globally, from all entries."
15945 (interactive
15946 (let* ((completion-ignore-case t)
15947 (prop (org-icompleting-read
15948 "Globally remove property: "
15949 (mapcar 'list (org-buffer-property-keys)))))
15950 (list prop)))
15951 (save-excursion
15952 (save-restriction
15953 (widen)
15954 (goto-char (point-min))
15955 (let ((cnt 0))
15956 (while (re-search-forward
15957 (org-re-property property)
15958 nil t)
15959 (setq cnt (1+ cnt))
15960 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15961 (message "Property \"%s\" removed from %d entries" property cnt)))))
15963 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15965 (defun org-compute-property-at-point ()
15966 "Compute the property at point.
15967 This looks for an enclosing column format, extracts the operator and
15968 then applies it to the property in the column format's scope."
15969 (interactive)
15970 (unless (org-at-property-p)
15971 (user-error "Not at a property"))
15972 (let ((prop (org-match-string-no-properties 2)))
15973 (org-columns-get-format-and-top-level)
15974 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15975 (user-error "No operator defined for property %s" prop))
15976 (org-columns-compute prop)))
15978 (defvar org-property-allowed-value-functions nil
15979 "Hook for functions supplying allowed values for a specific property.
15980 The functions must take a single argument, the name of the property, and
15981 return a flat list of allowed values. If \":ETC\" is one of
15982 the values, this means that these values are intended as defaults for
15983 completion, but that other values should be allowed too.
15984 The functions must return nil if they are not responsible for this
15985 property.")
15987 (defun org-property-get-allowed-values (pom property &optional table)
15988 "Get allowed values for the property PROPERTY.
15989 When TABLE is non-nil, return an alist that can directly be used for
15990 completion."
15991 (let (vals)
15992 (cond
15993 ((equal property "TODO")
15994 (setq vals (org-with-point-at pom
15995 (append org-todo-keywords-1 '("")))))
15996 ((equal property "PRIORITY")
15997 (let ((n org-lowest-priority))
15998 (while (>= n org-highest-priority)
15999 (push (char-to-string n) vals)
16000 (setq n (1- n)))))
16001 ((member property org-special-properties))
16002 ((setq vals (run-hook-with-args-until-success
16003 'org-property-allowed-value-functions property)))
16005 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16006 (when (and vals (string-match "\\S-" vals))
16007 (setq vals (car (read-from-string (concat "(" vals ")"))))
16008 (setq vals (mapcar (lambda (x)
16009 (cond ((stringp x) x)
16010 ((numberp x) (number-to-string x))
16011 ((symbolp x) (symbol-name x))
16012 (t "???")))
16013 vals)))))
16014 (when (member ":ETC" vals)
16015 (setq vals (remove ":ETC" vals))
16016 (org-add-props (car vals) '(org-unrestricted t)))
16017 (if table (mapcar 'list vals) vals)))
16019 (defun org-property-previous-allowed-value (&optional previous)
16020 "Switch to the next allowed value for this property."
16021 (interactive)
16022 (org-property-next-allowed-value t))
16024 (defun org-property-next-allowed-value (&optional previous)
16025 "Switch to the next allowed value for this property."
16026 (interactive)
16027 (unless (org-at-property-p)
16028 (user-error "Not at a property"))
16029 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16030 (key (match-string 2))
16031 (value (match-string 3))
16032 (allowed (or (org-property-get-allowed-values (point) key)
16033 (and (member value '("[ ]" "[-]" "[X]"))
16034 '("[ ]" "[X]"))))
16035 (heading (save-match-data (nth 4 (org-heading-components))))
16036 nval)
16037 (unless allowed
16038 (user-error "Allowed values for this property have not been defined"))
16039 (if previous (setq allowed (reverse allowed)))
16040 (if (member value allowed)
16041 (setq nval (car (cdr (member value allowed)))))
16042 (setq nval (or nval (car allowed)))
16043 (if (equal nval value)
16044 (user-error "Only one allowed value for this property"))
16045 (org-at-property-p)
16046 (replace-match (concat " :" key ": " nval) t t)
16047 (org-indent-line)
16048 (beginning-of-line 1)
16049 (skip-chars-forward " \t")
16050 (when (equal prop org-effort-property)
16051 (save-excursion
16052 (org-back-to-heading t)
16053 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
16054 (when (string= org-clock-current-task heading)
16055 (setq org-clock-effort nval)
16056 (org-clock-update-mode-line)))
16057 (run-hook-with-args 'org-property-changed-functions key nval)))
16059 (defun org-find-olp (path &optional this-buffer)
16060 "Return a marker pointing to the entry at outline path OLP.
16061 If anything goes wrong, throw an error.
16062 You can wrap this call to catch the error like this:
16064 (condition-case msg
16065 (org-mobile-locate-entry (match-string 4))
16066 (error (nth 1 msg)))
16068 The return value will then be either a string with the error message,
16069 or a marker if everything is OK.
16071 If THIS-BUFFER is set, the outline path does not contain a file,
16072 only headings."
16073 (let* ((file (if this-buffer buffer-file-name (pop path)))
16074 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16075 (level 1)
16076 (lmin 1)
16077 (lmax 1)
16078 limit re end found pos heading cnt flevel)
16079 (unless buffer (error "File not found :%s" file))
16080 (with-current-buffer buffer
16081 (save-excursion
16082 (save-restriction
16083 (widen)
16084 (setq limit (point-max))
16085 (goto-char (point-min))
16086 (while (setq heading (pop path))
16087 (setq re (format org-complex-heading-regexp-format
16088 (regexp-quote heading)))
16089 (setq cnt 0 pos (point))
16090 (while (re-search-forward re end t)
16091 (setq level (- (match-end 1) (match-beginning 1)))
16092 (if (and (>= level lmin) (<= level lmax))
16093 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16094 (when (= cnt 0) (error "Heading not found on level %d: %s"
16095 lmax heading))
16096 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16097 lmax heading))
16098 (goto-char found)
16099 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16100 (setq end (save-excursion (org-end-of-subtree t t))))
16101 (when (org-at-heading-p)
16102 (point-marker)))))))
16104 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16105 "Find node HEADING in BUFFER.
16106 Return a marker to the heading if it was found, or nil if not.
16107 If POS-ONLY is set, return just the position instead of a marker.
16109 The heading text must match exact, but it may have a TODO keyword,
16110 a priority cookie and tags in the standard locations."
16111 (with-current-buffer (or buffer (current-buffer))
16112 (save-excursion
16113 (save-restriction
16114 (widen)
16115 (goto-char (point-min))
16116 (let (case-fold-search)
16117 (if (re-search-forward
16118 (format org-complex-heading-regexp-format
16119 (regexp-quote heading)) nil t)
16120 (if pos-only
16121 (match-beginning 0)
16122 (move-marker (make-marker) (match-beginning 0)))))))))
16124 (defun org-find-exact-heading-in-directory (heading &optional dir)
16125 "Find Org node headline HEADING in all .org files in directory DIR.
16126 When the target headline is found, return a marker to this location."
16127 (let ((files (directory-files (or dir default-directory)
16128 nil "\\`[^.#].*\\.org\\'"))
16129 file visiting m buffer)
16130 (catch 'found
16131 (while (setq file (pop files))
16132 (message "trying %s" file)
16133 (setq visiting (org-find-base-buffer-visiting file))
16134 (setq buffer (or visiting (find-file-noselect file)))
16135 (setq m (org-find-exact-headline-in-buffer
16136 heading buffer))
16137 (when (and (not m) (not visiting)) (kill-buffer buffer))
16138 (and m (throw 'found m))))))
16140 (defun org-find-entry-with-id (ident)
16141 "Locate the entry that contains the ID property with exact value IDENT.
16142 IDENT can be a string, a symbol or a number, this function will search for
16143 the string representation of it.
16144 Return the position where this entry starts, or nil if there is no such entry."
16145 (interactive "sID: ")
16146 (let ((id (cond
16147 ((stringp ident) ident)
16148 ((symbol-name ident) (symbol-name ident))
16149 ((numberp ident) (number-to-string ident))
16150 (t (error "IDENT %s must be a string, symbol or number" ident))))
16151 (case-fold-search nil))
16152 (save-excursion
16153 (save-restriction
16154 (widen)
16155 (goto-char (point-min))
16156 (when (re-search-forward
16157 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16158 nil t)
16159 (org-back-to-heading t)
16160 (point))))))
16162 ;;;; Timestamps
16164 (defvar org-last-changed-timestamp nil)
16165 (defvar org-last-inserted-timestamp nil
16166 "The last time stamp inserted with `org-insert-time-stamp'.")
16167 (defvar org-ts-what) ; dynamically scoped parameter
16169 (defun org-time-stamp (arg &optional inactive)
16170 "Prompt for a date/time and insert a time stamp.
16171 If the user specifies a time like HH:MM or if this command is
16172 called with at least one prefix argument, the time stamp contains
16173 the date and the time. Otherwise, only the date is be included.
16175 All parts of a date not specified by the user is filled in from
16176 the current date/time. So if you just press return without
16177 typing anything, the time stamp will represent the current
16178 date/time.
16180 If there is already a timestamp at the cursor, it will be
16181 modified.
16183 With two universal prefix arguments, insert an active timestamp
16184 with the current time without prompting the user.
16186 When called from lisp, the timestamp is inactive if INACTIVE is
16187 non-nil."
16188 (interactive "P")
16189 (let* ((ts nil)
16190 (default-time
16191 ;; Default time is either today, or, when entering a range,
16192 ;; the range start.
16193 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16194 (save-excursion
16195 (re-search-backward
16196 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16197 (- (point) 20) t)))
16198 (apply 'encode-time (org-parse-time-string (match-string 1)))
16199 (current-time)))
16200 (default-input (and ts (org-get-compact-tod ts)))
16201 (repeater (save-excursion
16202 (save-match-data
16203 (beginning-of-line)
16204 (when (re-search-forward
16205 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16206 (save-excursion (progn (end-of-line) (point))) t)
16207 (match-string 0)))))
16208 org-time-was-given org-end-time-was-given time)
16209 (cond
16210 ((and (org-at-timestamp-p t)
16211 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16212 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16213 (insert "--")
16214 (setq time (let ((this-command this-command))
16215 (org-read-date arg 'totime nil nil
16216 default-time default-input inactive)))
16217 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16218 ((org-at-timestamp-p t)
16219 (setq time (let ((this-command this-command))
16220 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16221 (when (org-at-timestamp-p t) ; just to get the match data
16222 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16223 (replace-match "")
16224 (setq org-last-changed-timestamp
16225 (org-insert-time-stamp
16226 time (or org-time-was-given arg)
16227 inactive nil nil (list org-end-time-was-given)))
16228 (when repeater (goto-char (1- (point))) (insert " " repeater)
16229 (setq org-last-changed-timestamp
16230 (concat (substring org-last-inserted-timestamp 0 -1)
16231 " " repeater ">"))))
16232 (message "Timestamp updated"))
16233 ((equal arg '(16))
16234 (org-insert-time-stamp (current-time) t inactive))
16236 (setq time (let ((this-command this-command))
16237 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16238 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16239 nil nil (list org-end-time-was-given))))))
16241 ;; FIXME: can we use this for something else, like computing time differences?
16242 (defun org-get-compact-tod (s)
16243 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16244 (let* ((t1 (match-string 1 s))
16245 (h1 (string-to-number (match-string 2 s)))
16246 (m1 (string-to-number (match-string 3 s)))
16247 (t2 (and (match-end 4) (match-string 5 s)))
16248 (h2 (and t2 (string-to-number (match-string 6 s))))
16249 (m2 (and t2 (string-to-number (match-string 7 s))))
16250 dh dm)
16251 (if (not t2)
16253 (setq dh (- h2 h1) dm (- m2 m1))
16254 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16255 (concat t1 "+" (number-to-string dh)
16256 (and (/= 0 dm) (format ":%02d" dm)))))))
16258 (defun org-time-stamp-inactive (&optional arg)
16259 "Insert an inactive time stamp.
16260 An inactive time stamp is enclosed in square brackets instead of angle
16261 brackets. It is inactive in the sense that it does not trigger agenda entries,
16262 does not link to the calendar and cannot be changed with the S-cursor keys.
16263 So these are more for recording a certain time/date."
16264 (interactive "P")
16265 (org-time-stamp arg 'inactive))
16267 (defvar org-date-ovl (make-overlay 1 1))
16268 (overlay-put org-date-ovl 'face 'org-date-selected)
16269 (org-detach-overlay org-date-ovl)
16271 (defvar org-ans1) ; dynamically scoped parameter
16272 (defvar org-ans2) ; dynamically scoped parameter
16274 (defvar org-plain-time-of-day-regexp) ; defined below
16276 (defvar org-overriding-default-time nil) ; dynamically scoped
16277 (defvar org-read-date-overlay nil)
16278 (defvar org-dcst nil) ; dynamically scoped
16279 (defvar org-read-date-history nil)
16280 (defvar org-read-date-final-answer nil)
16281 (defvar org-read-date-analyze-futurep nil)
16282 (defvar org-read-date-analyze-forced-year nil)
16283 (defvar org-read-date-inactive)
16285 (defvar org-read-date-minibuffer-local-map
16286 (let* ((org-replace-disputed-keys nil)
16287 (map (make-sparse-keymap)))
16288 (set-keymap-parent map minibuffer-local-map)
16289 (org-defkey map (kbd ".")
16290 (lambda () (interactive)
16291 ;; Are we at the beginning of the prompt?
16292 (if (looking-back "^[^:]+: ")
16293 (org-eval-in-calendar '(calendar-goto-today))
16294 (insert "."))))
16295 (org-defkey map (kbd "C-.")
16296 (lambda () (interactive)
16297 (org-eval-in-calendar '(calendar-goto-today))))
16298 (org-defkey map [(meta shift left)]
16299 (lambda () (interactive)
16300 (org-eval-in-calendar '(calendar-backward-month 1))))
16301 (org-defkey map [(meta shift right)]
16302 (lambda () (interactive)
16303 (org-eval-in-calendar '(calendar-forward-month 1))))
16304 (org-defkey map [(meta shift up)]
16305 (lambda () (interactive)
16306 (org-eval-in-calendar '(calendar-backward-year 1))))
16307 (org-defkey map [(meta shift down)]
16308 (lambda () (interactive)
16309 (org-eval-in-calendar '(calendar-forward-year 1))))
16310 (org-defkey map [?\e (shift left)]
16311 (lambda () (interactive)
16312 (org-eval-in-calendar '(calendar-backward-month 1))))
16313 (org-defkey map [?\e (shift right)]
16314 (lambda () (interactive)
16315 (org-eval-in-calendar '(calendar-forward-month 1))))
16316 (org-defkey map [?\e (shift up)]
16317 (lambda () (interactive)
16318 (org-eval-in-calendar '(calendar-backward-year 1))))
16319 (org-defkey map [?\e (shift down)]
16320 (lambda () (interactive)
16321 (org-eval-in-calendar '(calendar-forward-year 1))))
16322 (org-defkey map [(shift up)]
16323 (lambda () (interactive)
16324 (org-eval-in-calendar '(calendar-backward-week 1))))
16325 (org-defkey map [(shift down)]
16326 (lambda () (interactive)
16327 (org-eval-in-calendar '(calendar-forward-week 1))))
16328 (org-defkey map [(shift left)]
16329 (lambda () (interactive)
16330 (org-eval-in-calendar '(calendar-backward-day 1))))
16331 (org-defkey map [(shift right)]
16332 (lambda () (interactive)
16333 (org-eval-in-calendar '(calendar-forward-day 1))))
16334 (org-defkey map "!"
16335 (lambda () (interactive)
16336 (org-eval-in-calendar '(diary-view-entries))
16337 (message "")))
16338 (org-defkey map ">"
16339 (lambda () (interactive)
16340 (org-eval-in-calendar '(scroll-calendar-left 1))))
16341 (org-defkey map "<"
16342 (lambda () (interactive)
16343 (org-eval-in-calendar '(scroll-calendar-right 1))))
16344 (org-defkey map "\C-v"
16345 (lambda () (interactive)
16346 (org-eval-in-calendar
16347 '(calendar-scroll-left-three-months 1))))
16348 (org-defkey map "\M-v"
16349 (lambda () (interactive)
16350 (org-eval-in-calendar
16351 '(calendar-scroll-right-three-months 1))))
16352 map)
16353 "Keymap for minibuffer commands when using `org-read-date'.")
16355 (defvar org-def)
16356 (defvar org-defdecode)
16357 (defvar org-with-time)
16359 (defun org-read-date (&optional org-with-time to-time from-string prompt
16360 default-time default-input inactive)
16361 "Read a date, possibly a time, and make things smooth for the user.
16362 The prompt will suggest to enter an ISO date, but you can also enter anything
16363 which will at least partially be understood by `parse-time-string'.
16364 Unrecognized parts of the date will default to the current day, month, year,
16365 hour and minute. If this command is called to replace a timestamp at point,
16366 or to enter the second timestamp of a range, the default time is taken
16367 from the existing stamp. Furthermore, the command prefers the future,
16368 so if you are giving a date where the year is not given, and the day-month
16369 combination is already past in the current year, it will assume you
16370 mean next year. For details, see the manual. A few examples:
16372 3-2-5 --> 2003-02-05
16373 feb 15 --> currentyear-02-15
16374 2/15 --> currentyear-02-15
16375 sep 12 9 --> 2009-09-12
16376 12:45 --> today 12:45
16377 22 sept 0:34 --> currentyear-09-22 0:34
16378 12 --> currentyear-currentmonth-12
16379 Fri --> nearest Friday after today
16380 -Tue --> last Tuesday
16381 etc.
16383 Furthermore you can specify a relative date by giving, as the *first* thing
16384 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16385 change in days weeks, months, years.
16386 With a single plus or minus, the date is relative to today. With a double
16387 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16388 +4d --> four days from today
16389 +4 --> same as above
16390 +2w --> two weeks from today
16391 ++5 --> five days from default date
16393 The function understands only English month and weekday abbreviations.
16395 While prompting, a calendar is popped up - you can also select the
16396 date with the mouse (button 1). The calendar shows a period of three
16397 months. To scroll it to other months, use the keys `>' and `<'.
16398 If you don't like the calendar, turn it off with
16399 \(setq org-read-date-popup-calendar nil)
16401 With optional argument TO-TIME, the date will immediately be converted
16402 to an internal time.
16403 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16404 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16405 still enter a time, and this function will inform the calling routine
16406 about this change. The calling routine may then choose to change the
16407 format used to insert the time stamp into the buffer to include the time.
16408 With optional argument FROM-STRING, read from this string instead from
16409 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16410 the time/date that is used for everything that is not specified by the
16411 user."
16412 (require 'parse-time)
16413 (let* ((org-time-stamp-rounding-minutes
16414 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16415 (org-dcst org-display-custom-times)
16416 (ct (org-current-time))
16417 (org-def (or org-overriding-default-time default-time ct))
16418 (org-defdecode (decode-time org-def))
16419 (dummy (progn
16420 (when (< (nth 2 org-defdecode) org-extend-today-until)
16421 (setcar (nthcdr 2 org-defdecode) -1)
16422 (setcar (nthcdr 1 org-defdecode) 59)
16423 (setq org-def (apply 'encode-time org-defdecode)
16424 org-defdecode (decode-time org-def)))))
16425 (mouse-autoselect-window nil) ; Don't let the mouse jump
16426 (calendar-frame-setup nil)
16427 (calendar-setup nil)
16428 (calendar-move-hook nil)
16429 (calendar-view-diary-initially-flag nil)
16430 (calendar-view-holidays-initially-flag nil)
16431 (timestr (format-time-string
16432 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16433 (prompt (concat (if prompt (concat prompt " ") "")
16434 (format "Date+time [%s]: " timestr)))
16435 ans (org-ans0 "") org-ans1 org-ans2 final)
16437 (cond
16438 (from-string (setq ans from-string))
16439 (org-read-date-popup-calendar
16440 (save-excursion
16441 (save-window-excursion
16442 (calendar)
16443 (org-eval-in-calendar '(setq cursor-type nil) t)
16444 (unwind-protect
16445 (progn
16446 (calendar-forward-day (- (time-to-days org-def)
16447 (calendar-absolute-from-gregorian
16448 (calendar-current-date))))
16449 (org-eval-in-calendar nil t)
16450 (let* ((old-map (current-local-map))
16451 (map (copy-keymap calendar-mode-map))
16452 (minibuffer-local-map
16453 (copy-keymap org-read-date-minibuffer-local-map)))
16454 (org-defkey map (kbd "RET") 'org-calendar-select)
16455 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16456 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16457 (unwind-protect
16458 (progn
16459 (use-local-map map)
16460 (setq org-read-date-inactive inactive)
16461 (add-hook 'post-command-hook 'org-read-date-display)
16462 (setq org-ans0 (read-string prompt default-input
16463 'org-read-date-history nil))
16464 ;; org-ans0: from prompt
16465 ;; org-ans1: from mouse click
16466 ;; org-ans2: from calendar motion
16467 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16468 (remove-hook 'post-command-hook 'org-read-date-display)
16469 (use-local-map old-map)
16470 (when org-read-date-overlay
16471 (delete-overlay org-read-date-overlay)
16472 (setq org-read-date-overlay nil)))))
16473 (bury-buffer "*Calendar*")))))
16475 (t ; Naked prompt only
16476 (unwind-protect
16477 (setq ans (read-string prompt default-input
16478 'org-read-date-history timestr))
16479 (when org-read-date-overlay
16480 (delete-overlay org-read-date-overlay)
16481 (setq org-read-date-overlay nil)))))
16483 (setq final (org-read-date-analyze ans org-def org-defdecode))
16485 (when org-read-date-analyze-forced-year
16486 (message "Year was forced into %s"
16487 (if org-read-date-force-compatible-dates
16488 "compatible range (1970-2037)"
16489 "range representable on this machine"))
16490 (ding))
16492 ;; One round trip to get rid of 34th of August and stuff like that....
16493 (setq final (decode-time (apply 'encode-time final)))
16495 (setq org-read-date-final-answer ans)
16497 (if to-time
16498 (apply 'encode-time final)
16499 (if (and (boundp 'org-time-was-given) org-time-was-given)
16500 (format "%04d-%02d-%02d %02d:%02d"
16501 (nth 5 final) (nth 4 final) (nth 3 final)
16502 (nth 2 final) (nth 1 final))
16503 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16505 (defun org-read-date-display ()
16506 "Display the current date prompt interpretation in the minibuffer."
16507 (when org-read-date-display-live
16508 (when org-read-date-overlay
16509 (delete-overlay org-read-date-overlay))
16510 (when (minibufferp (current-buffer))
16511 (save-excursion
16512 (end-of-line 1)
16513 (while (not (equal (buffer-substring
16514 (max (point-min) (- (point) 4)) (point))
16515 " "))
16516 (insert " ")))
16517 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16518 " " (or org-ans1 org-ans2)))
16519 (org-end-time-was-given nil)
16520 (f (org-read-date-analyze ans org-def org-defdecode))
16521 (fmts (if org-dcst
16522 org-time-stamp-custom-formats
16523 org-time-stamp-formats))
16524 (fmt (if (or org-with-time
16525 (and (boundp 'org-time-was-given) org-time-was-given))
16526 (cdr fmts)
16527 (car fmts)))
16528 (txt (format-time-string fmt (apply 'encode-time f)))
16529 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16530 (txt (concat "=> " txt)))
16531 (when (and org-end-time-was-given
16532 (string-match org-plain-time-of-day-regexp txt))
16533 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16534 org-end-time-was-given
16535 (substring txt (match-end 0)))))
16536 (when org-read-date-analyze-futurep
16537 (setq txt (concat txt " (=>F)")))
16538 (setq org-read-date-overlay
16539 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16540 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16542 (defun org-read-date-analyze (ans org-def org-defdecode)
16543 "Analyze the combined answer of the date prompt."
16544 ;; FIXME: cleanup and comment
16545 (let ((nowdecode (decode-time (current-time)))
16546 delta deltan deltaw deltadef year month day
16547 hour minute second wday pm h2 m2 tl wday1
16548 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16549 (setq org-read-date-analyze-futurep nil
16550 org-read-date-analyze-forced-year nil)
16551 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16552 (setq ans "+0"))
16554 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16555 (setq ans (replace-match "" t t ans)
16556 deltan (car delta)
16557 deltaw (nth 1 delta)
16558 deltadef (nth 2 delta)))
16560 ;; Check if there is an iso week date in there. If yes, store the
16561 ;; info and postpone interpreting it until the rest of the parsing
16562 ;; is done.
16563 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16564 (setq iso-year (if (match-end 1)
16565 (org-small-year-to-year
16566 (string-to-number (match-string 1 ans))))
16567 iso-weekday (if (match-end 3)
16568 (string-to-number (match-string 3 ans)))
16569 iso-week (string-to-number (match-string 2 ans)))
16570 (setq ans (replace-match "" t t ans)))
16572 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16573 (when (string-match
16574 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16575 (setq year (if (match-end 2)
16576 (string-to-number (match-string 2 ans))
16577 (progn (setq kill-year t)
16578 (string-to-number (format-time-string "%Y"))))
16579 month (string-to-number (match-string 3 ans))
16580 day (string-to-number (match-string 4 ans)))
16581 (if (< year 100) (setq year (+ 2000 year)))
16582 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16583 t nil ans)))
16585 ;; Help matching dotted european dates
16586 (when (string-match
16587 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16588 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16589 (setq kill-year t)
16590 (string-to-number (format-time-string "%Y")))
16591 day (string-to-number (match-string 1 ans))
16592 month (string-to-number (match-string 2 ans))
16593 ans (replace-match (format "%04d-%02d-%02d" year month day)
16594 t nil ans)))
16596 ;; Help matching american dates, like 5/30 or 5/30/7
16597 (when (string-match
16598 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16599 (setq year (if (match-end 4)
16600 (string-to-number (match-string 4 ans))
16601 (progn (setq kill-year t)
16602 (string-to-number (format-time-string "%Y"))))
16603 month (string-to-number (match-string 1 ans))
16604 day (string-to-number (match-string 2 ans)))
16605 (if (< year 100) (setq year (+ 2000 year)))
16606 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16607 t nil ans)))
16608 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16609 ;; If there is a time with am/pm, and *no* time without it, we convert
16610 ;; so that matching will be successful.
16611 (loop for i from 1 to 2 do ; twice, for end time as well
16612 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16613 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16614 (setq hour (string-to-number (match-string 1 ans))
16615 minute (if (match-end 3)
16616 (string-to-number (match-string 3 ans))
16618 pm (equal ?p
16619 (string-to-char (downcase (match-string 4 ans)))))
16620 (if (and (= hour 12) (not pm))
16621 (setq hour 0)
16622 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16623 (setq ans (replace-match (format "%02d:%02d" hour minute)
16624 t t ans))))
16626 ;; Check if a time range is given as a duration
16627 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16628 (setq hour (string-to-number (match-string 1 ans))
16629 h2 (+ hour (string-to-number (match-string 3 ans)))
16630 minute (string-to-number (match-string 2 ans))
16631 m2 (+ minute (if (match-end 5) (string-to-number
16632 (match-string 5 ans))0)))
16633 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16634 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16635 t t ans)))
16637 ;; Check if there is a time range
16638 (when (boundp 'org-end-time-was-given)
16639 (setq org-time-was-given nil)
16640 (when (and (string-match org-plain-time-of-day-regexp ans)
16641 (match-end 8))
16642 (setq org-end-time-was-given (match-string 8 ans))
16643 (setq ans (concat (substring ans 0 (match-beginning 7))
16644 (substring ans (match-end 7))))))
16646 (setq tl (parse-time-string ans)
16647 day (or (nth 3 tl) (nth 3 org-defdecode))
16648 month (or (nth 4 tl)
16649 (if (and org-read-date-prefer-future
16650 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16651 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16652 (nth 4 org-defdecode)))
16653 year (or (and (not kill-year) (nth 5 tl))
16654 (if (and org-read-date-prefer-future
16655 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16656 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16657 (nth 5 org-defdecode)))
16658 hour (or (nth 2 tl) (nth 2 org-defdecode))
16659 minute (or (nth 1 tl) (nth 1 org-defdecode))
16660 second (or (nth 0 tl) 0)
16661 wday (nth 6 tl))
16663 (when (and (eq org-read-date-prefer-future 'time)
16664 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16665 (equal day (nth 3 nowdecode))
16666 (equal month (nth 4 nowdecode))
16667 (equal year (nth 5 nowdecode))
16668 (nth 2 tl)
16669 (or (< (nth 2 tl) (nth 2 nowdecode))
16670 (and (= (nth 2 tl) (nth 2 nowdecode))
16671 (nth 1 tl)
16672 (< (nth 1 tl) (nth 1 nowdecode)))))
16673 (setq day (1+ day)
16674 futurep t))
16676 ;; Special date definitions below
16677 (cond
16678 (iso-week
16679 ;; There was an iso week
16680 (require 'cal-iso)
16681 (setq futurep nil)
16682 (setq year (or iso-year year)
16683 day (or iso-weekday wday 1)
16684 wday nil ; to make sure that the trigger below does not match
16685 iso-date (calendar-gregorian-from-absolute
16686 (calendar-absolute-from-iso
16687 (list iso-week day year))))
16688 ; FIXME: Should we also push ISO weeks into the future?
16689 ; (when (and org-read-date-prefer-future
16690 ; (not iso-year)
16691 ; (< (calendar-absolute-from-gregorian iso-date)
16692 ; (time-to-days (current-time))))
16693 ; (setq year (1+ year)
16694 ; iso-date (calendar-gregorian-from-absolute
16695 ; (calendar-absolute-from-iso
16696 ; (list iso-week day year)))))
16697 (setq month (car iso-date)
16698 year (nth 2 iso-date)
16699 day (nth 1 iso-date)))
16700 (deltan
16701 (setq futurep nil)
16702 (unless deltadef
16703 (let ((now (decode-time (current-time))))
16704 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16705 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16706 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16707 ((equal deltaw "m") (setq month (+ month deltan)))
16708 ((equal deltaw "y") (setq year (+ year deltan)))))
16709 ((and wday (not (nth 3 tl)))
16710 ;; Weekday was given, but no day, so pick that day in the week
16711 ;; on or after the derived date.
16712 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16713 (unless (equal wday wday1)
16714 (setq day (+ day (% (- wday wday1 -7) 7))))))
16715 (if (and (boundp 'org-time-was-given)
16716 (nth 2 tl))
16717 (setq org-time-was-given t))
16718 (if (< year 100) (setq year (+ 2000 year)))
16719 ;; Check of the date is representable
16720 (if org-read-date-force-compatible-dates
16721 (progn
16722 (if (< year 1970)
16723 (setq year 1970 org-read-date-analyze-forced-year t))
16724 (if (> year 2037)
16725 (setq year 2037 org-read-date-analyze-forced-year t)))
16726 (condition-case nil
16727 (ignore (encode-time second minute hour day month year))
16728 (error
16729 (setq year (nth 5 org-defdecode))
16730 (setq org-read-date-analyze-forced-year t))))
16731 (setq org-read-date-analyze-futurep futurep)
16732 (list second minute hour day month year)))
16734 (defvar parse-time-weekdays)
16735 (defun org-read-date-get-relative (s today default)
16736 "Check string S for special relative date string.
16737 TODAY and DEFAULT are internal times, for today and for a default.
16738 Return shift list (N what def-flag)
16739 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16740 N is the number of WHATs to shift.
16741 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16742 the DEFAULT date rather than TODAY."
16743 (require 'parse-time)
16744 (when (and
16745 (string-match
16746 (concat
16747 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16748 "\\([0-9]+\\)?"
16749 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16750 "\\([ \t]\\|$\\)") s)
16751 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16752 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16753 (string-to-char (substring (match-string 1 s) -1))
16754 ?+))
16755 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16756 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16757 (what (if (match-end 3) (match-string 3 s) "d"))
16758 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16759 (date (if rel default today))
16760 (wday (nth 6 (decode-time date)))
16761 delta)
16762 (if wday1
16763 (progn
16764 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16765 (if (= delta 0) (setq delta 7))
16766 (if (= dir ?-)
16767 (progn
16768 (setq delta (- delta 7))
16769 (if (= delta 0) (setq delta -7))))
16770 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16771 (list delta "d" rel))
16772 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16774 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16775 "Turn a user-specified date into the internal representation.
16776 The internal representation needed by the calendar is (month day year).
16777 This is a wrapper to handle the brain-dead convention in calendar that
16778 user function argument order change dependent on argument order."
16779 (if (boundp 'calendar-date-style)
16780 (cond
16781 ((eq calendar-date-style 'american)
16782 (list arg1 arg2 arg3))
16783 ((eq calendar-date-style 'european)
16784 (list arg2 arg1 arg3))
16785 ((eq calendar-date-style 'iso)
16786 (list arg2 arg3 arg1)))
16787 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16788 (if (org-bound-and-true-p european-calendar-style)
16789 (list arg2 arg1 arg3)
16790 (list arg1 arg2 arg3)))))
16792 (defun org-eval-in-calendar (form &optional keepdate)
16793 "Eval FORM in the calendar window and return to current window.
16794 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16795 otherwise stick to the current value of `org-ans2'."
16796 (let ((sf (selected-frame))
16797 (sw (selected-window)))
16798 (select-window (get-buffer-window "*Calendar*" t))
16799 (eval form)
16800 (when (and (not keepdate) (calendar-cursor-to-date))
16801 (let* ((date (calendar-cursor-to-date))
16802 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16803 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16804 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16805 (select-window sw)
16806 (org-select-frame-set-input-focus sf)))
16808 (defun org-calendar-select ()
16809 "Return to `org-read-date' with the date currently selected.
16810 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16811 (interactive)
16812 (when (calendar-cursor-to-date)
16813 (let* ((date (calendar-cursor-to-date))
16814 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16815 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16816 (if (active-minibuffer-window) (exit-minibuffer))))
16818 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16819 "Insert a date stamp for the date given by the internal TIME.
16820 WITH-HM means use the stamp format that includes the time of the day.
16821 INACTIVE means use square brackets instead of angular ones, so that the
16822 stamp will not contribute to the agenda.
16823 PRE and POST are optional strings to be inserted before and after the
16824 stamp.
16825 The command returns the inserted time stamp."
16826 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16827 stamp)
16828 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16829 (insert-before-markers (or pre ""))
16830 (when (listp extra)
16831 (setq extra (car extra))
16832 (if (and (stringp extra)
16833 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16834 (setq extra (format "-%02d:%02d"
16835 (string-to-number (match-string 1 extra))
16836 (string-to-number (match-string 2 extra))))
16837 (setq extra nil)))
16838 (when extra
16839 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16840 (insert-before-markers (setq stamp (format-time-string fmt time)))
16841 (insert-before-markers (or post ""))
16842 (setq org-last-inserted-timestamp stamp)))
16844 (defun org-toggle-time-stamp-overlays ()
16845 "Toggle the use of custom time stamp formats."
16846 (interactive)
16847 (setq org-display-custom-times (not org-display-custom-times))
16848 (unless org-display-custom-times
16849 (let ((p (point-min)) (bmp (buffer-modified-p)))
16850 (while (setq p (next-single-property-change p 'display))
16851 (if (and (get-text-property p 'display)
16852 (eq (get-text-property p 'face) 'org-date))
16853 (remove-text-properties
16854 p (setq p (next-single-property-change p 'display))
16855 '(display t))))
16856 (set-buffer-modified-p bmp)))
16857 (if (featurep 'xemacs)
16858 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16859 (org-restart-font-lock)
16860 (setq org-table-may-need-update t)
16861 (if org-display-custom-times
16862 (message "Time stamps are overlaid with custom format")
16863 (message "Time stamp overlays removed")))
16865 (defun org-display-custom-time (beg end)
16866 "Overlay modified time stamp format over timestamp between BEG and END."
16867 (let* ((ts (buffer-substring beg end))
16868 t1 w1 with-hm tf time str w2 (off 0))
16869 (save-match-data
16870 (setq t1 (org-parse-time-string ts t))
16871 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16872 (setq off (- (match-end 0) (match-beginning 0)))))
16873 (setq end (- end off))
16874 (setq w1 (- end beg)
16875 with-hm (and (nth 1 t1) (nth 2 t1))
16876 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16877 time (org-fix-decoded-time t1)
16878 str (org-add-props
16879 (format-time-string
16880 (substring tf 1 -1) (apply 'encode-time time))
16881 nil 'mouse-face 'highlight)
16882 w2 (length str))
16883 (if (not (= w2 w1))
16884 (add-text-properties (1+ beg) (+ 2 beg)
16885 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16886 (if (featurep 'xemacs)
16887 (progn
16888 (put-text-property beg end 'invisible t)
16889 (put-text-property beg end 'end-glyph (make-glyph str)))
16890 (put-text-property beg end 'display str))))
16892 (defun org-translate-time (string)
16893 "Translate all timestamps in STRING to custom format.
16894 But do this only if the variable `org-display-custom-times' is set."
16895 (when org-display-custom-times
16896 (save-match-data
16897 (let* ((start 0)
16898 (re org-ts-regexp-both)
16899 t1 with-hm inactive tf time str beg end)
16900 (while (setq start (string-match re string start))
16901 (setq beg (match-beginning 0)
16902 end (match-end 0)
16903 t1 (save-match-data
16904 (org-parse-time-string (substring string beg end) t))
16905 with-hm (and (nth 1 t1) (nth 2 t1))
16906 inactive (equal (substring string beg (1+ beg)) "[")
16907 tf (funcall (if with-hm 'cdr 'car)
16908 org-time-stamp-custom-formats)
16909 time (org-fix-decoded-time t1)
16910 str (format-time-string
16911 (concat
16912 (if inactive "[" "<") (substring tf 1 -1)
16913 (if inactive "]" ">"))
16914 (apply 'encode-time time))
16915 string (replace-match str t t string)
16916 start (+ start (length str)))))))
16917 string)
16919 (defun org-fix-decoded-time (time)
16920 "Set 0 instead of nil for the first 6 elements of time.
16921 Don't touch the rest."
16922 (let ((n 0))
16923 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16925 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16927 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16928 "Difference between TIMESTAMP-STRING and now in days.
16929 If SECONDS is non-nil, return the difference in seconds."
16930 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16931 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16932 (funcall fdiff (current-time)))))
16934 (defun org-deadline-close (timestamp-string &optional ndays)
16935 "Is the time in TIMESTAMP-STRING close to the current date?"
16936 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16937 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16938 (not (org-entry-is-done-p))))
16940 (defun org-get-wdays (ts &optional delay zero-delay)
16941 "Get the deadline lead time appropriate for timestring TS.
16942 When DELAY is non-nil, get the delay time for scheduled items
16943 instead of the deadline lead time. When ZERO-DELAY is non-nil
16944 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16945 don't try to find the delay cookie in the scheduled timestamp."
16946 (let ((tv (if delay org-scheduled-delay-days
16947 org-deadline-warning-days)))
16948 (cond
16949 ((or (and delay (< tv 0))
16950 (and delay zero-delay (<= tv 0))
16951 (and (not delay) (<= tv 0)))
16952 ;; Enforce this value no matter what
16953 (- tv))
16954 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16955 ;; lead time is specified.
16956 (floor (* (string-to-number (match-string 1 ts))
16957 (cdr (assoc (match-string 2 ts)
16958 '(("d" . 1) ("w" . 7)
16959 ("m" . 30.4) ("y" . 365.25)
16960 ("h" . 0.041667)))))))
16961 ;; go for the default.
16962 (t tv))))
16964 (defun org-calendar-select-mouse (ev)
16965 "Return to `org-read-date' with the date currently selected.
16966 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16967 (interactive "e")
16968 (mouse-set-point ev)
16969 (when (calendar-cursor-to-date)
16970 (let* ((date (calendar-cursor-to-date))
16971 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16972 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16973 (if (active-minibuffer-window) (exit-minibuffer))))
16975 (defun org-check-deadlines (ndays)
16976 "Check if there are any deadlines due or past due.
16977 A deadline is considered due if it happens within `org-deadline-warning-days'
16978 days from today's date. If the deadline appears in an entry marked DONE,
16979 it is not shown. The prefix arg NDAYS can be used to test that many
16980 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16981 (interactive "P")
16982 (let* ((org-warn-days
16983 (cond
16984 ((equal ndays '(4)) 100000)
16985 (ndays (prefix-numeric-value ndays))
16986 (t (abs org-deadline-warning-days))))
16987 (case-fold-search nil)
16988 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16989 (callback
16990 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16992 (message "%d deadlines past-due or due within %d days"
16993 (org-occur regexp nil callback)
16994 org-warn-days)))
16996 (defsubst org-re-timestamp (type)
16997 "Return a regexp for timestamp TYPE.
16998 Allowed values for TYPE are:
17000 all: all timestamps
17001 active: only active timestamps (<...>)
17002 inactive: only inactive timestamps ([...])
17003 scheduled: only scheduled timestamps
17004 deadline: only deadline timestamps
17005 closed: only closed time-stamps
17007 When TYPE is nil, fall back on returning a regexp that matches
17008 both scheduled and deadline timestamps."
17009 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17010 ((eq type 'active) org-ts-regexp)
17011 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17012 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17013 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17014 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17015 ((eq type 'scheduled-or-deadline)
17016 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17018 (defun org-check-before-date (date)
17019 "Check if there are deadlines or scheduled entries before DATE."
17020 (interactive (list (org-read-date)))
17021 (let ((case-fold-search nil)
17022 (regexp (org-re-timestamp org-ts-type))
17023 (callback
17024 (lambda () (time-less-p
17025 (org-time-string-to-time (match-string 1))
17026 (org-time-string-to-time date)))))
17027 (message "%d entries before %s"
17028 (org-occur regexp nil callback) date)))
17030 (defun org-check-after-date (date)
17031 "Check if there are deadlines or scheduled entries after DATE."
17032 (interactive (list (org-read-date)))
17033 (let ((case-fold-search nil)
17034 (regexp (org-re-timestamp org-ts-type))
17035 (callback
17036 (lambda () (not
17037 (time-less-p
17038 (org-time-string-to-time (match-string 1))
17039 (org-time-string-to-time date))))))
17040 (message "%d entries after %s"
17041 (org-occur regexp nil callback) date)))
17043 (defun org-check-dates-range (start-date end-date)
17044 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17045 (interactive (list (org-read-date nil nil nil "Range starts")
17046 (org-read-date nil nil nil "Range end")))
17047 (let ((case-fold-search nil)
17048 (regexp (org-re-timestamp org-ts-type))
17049 (callback
17050 (lambda ()
17051 (let ((match (match-string 1)))
17052 (and
17053 (not (time-less-p
17054 (org-time-string-to-time match)
17055 (org-time-string-to-time start-date)))
17056 (time-less-p
17057 (org-time-string-to-time match)
17058 (org-time-string-to-time end-date)))))))
17059 (message "%d entries between %s and %s"
17060 (org-occur regexp nil callback) start-date end-date)))
17062 (defun org-evaluate-time-range (&optional to-buffer)
17063 "Evaluate a time range by computing the difference between start and end.
17064 Normally the result is just printed in the echo area, but with prefix arg
17065 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17066 If the time range is actually in a table, the result is inserted into the
17067 next column.
17068 For time difference computation, a year is assumed to be exactly 365
17069 days in order to avoid rounding problems."
17070 (interactive "P")
17072 (org-clock-update-time-maybe)
17073 (save-excursion
17074 (unless (org-at-date-range-p t)
17075 (goto-char (point-at-bol))
17076 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17077 (if (not (org-at-date-range-p t))
17078 (user-error "Not at a time-stamp range, and none found in current line")))
17079 (let* ((ts1 (match-string 1))
17080 (ts2 (match-string 2))
17081 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17082 (match-end (match-end 0))
17083 (time1 (org-time-string-to-time ts1))
17084 (time2 (org-time-string-to-time ts2))
17085 (t1 (org-float-time time1))
17086 (t2 (org-float-time time2))
17087 (diff (abs (- t2 t1)))
17088 (negative (< (- t2 t1) 0))
17089 ;; (ys (floor (* 365 24 60 60)))
17090 (ds (* 24 60 60))
17091 (hs (* 60 60))
17092 (fy "%dy %dd %02d:%02d")
17093 (fy1 "%dy %dd")
17094 (fd "%dd %02d:%02d")
17095 (fd1 "%dd")
17096 (fh "%02d:%02d")
17097 y d h m align)
17098 (if havetime
17099 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17101 d (floor (/ diff ds)) diff (mod diff ds)
17102 h (floor (/ diff hs)) diff (mod diff hs)
17103 m (floor (/ diff 60)))
17104 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17106 d (floor (+ (/ diff ds) 0.5))
17107 h 0 m 0))
17108 (if (not to-buffer)
17109 (message "%s" (org-make-tdiff-string y d h m))
17110 (if (org-at-table-p)
17111 (progn
17112 (goto-char match-end)
17113 (setq align t)
17114 (and (looking-at " *|") (goto-char (match-end 0))))
17115 (goto-char match-end))
17116 (if (looking-at
17117 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17118 (replace-match ""))
17119 (if negative (insert " -"))
17120 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17121 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17122 (insert " " (format fh h m))))
17123 (if align (org-table-align))
17124 (message "Time difference inserted")))))
17126 (defun org-make-tdiff-string (y d h m)
17127 (let ((fmt "")
17128 (l nil))
17129 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17130 l (push y l)))
17131 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17132 l (push d l)))
17133 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17134 l (push h l)))
17135 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17136 l (push m l)))
17137 (apply 'format fmt (nreverse l))))
17139 (defun org-time-string-to-time (s &optional buffer pos)
17140 "Convert a timestamp string into internal time."
17141 (condition-case errdata
17142 (apply 'encode-time (org-parse-time-string s))
17143 (error (error "Bad timestamp `%s'%s\nError was: %s"
17144 s (if (not (and buffer pos))
17146 (format " at %d in buffer `%s'" pos buffer))
17147 (cdr errdata)))))
17149 (defun org-time-string-to-seconds (s)
17150 "Convert a timestamp string to a number of seconds."
17151 (org-float-time (org-time-string-to-time s)))
17153 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17154 "Convert a time stamp to an absolute day number.
17155 If there is a specifier for a cyclic time stamp, get the closest
17156 date to DAYNR.
17157 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17158 The variable `date' is bound by the calendar when this is called."
17159 (cond
17160 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17161 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17162 daynr
17163 (+ daynr 1000)))
17164 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17165 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17166 (time-to-days (current-time))) (match-string 0 s)
17167 prefer show-all))
17168 (t (time-to-days
17169 (condition-case errdata
17170 (apply 'encode-time (org-parse-time-string s))
17171 (error (error "Bad timestamp `%s'%s\nError was: %s"
17172 s (if (not (and buffer pos))
17174 (format " at %d in buffer `%s'" pos buffer))
17175 (cdr errdata))))))))
17177 (defun org-days-to-iso-week (days)
17178 "Return the iso week number."
17179 (require 'cal-iso)
17180 (car (calendar-iso-from-absolute days)))
17182 (defun org-small-year-to-year (year)
17183 "Convert 2-digit years into 4-digit years.
17184 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17185 The year 2000 cannot be abbreviated. Any year larger than 99
17186 is returned unchanged."
17187 (if (< year 38)
17188 (setq year (+ 2000 year))
17189 (if (< year 100)
17190 (setq year (+ 1900 year))))
17191 year)
17193 (defun org-time-from-absolute (d)
17194 "Return the time corresponding to date D.
17195 D may be an absolute day number, or a calendar-type list (month day year)."
17196 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17197 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17199 (defun org-calendar-holiday ()
17200 "List of holidays, for Diary display in Org-mode."
17201 (require 'holidays)
17202 (let ((hl (funcall
17203 (if (fboundp 'calendar-check-holidays)
17204 'calendar-check-holidays 'check-calendar-holidays) date)))
17205 (if hl (mapconcat 'identity hl "; "))))
17207 (defun org-diary-sexp-entry (sexp entry date)
17208 "Process a SEXP diary ENTRY for DATE."
17209 (require 'diary-lib)
17210 (let ((result (if calendar-debug-sexp
17211 (let ((stack-trace-on-error t))
17212 (eval (car (read-from-string sexp))))
17213 (condition-case nil
17214 (eval (car (read-from-string sexp)))
17215 (error
17216 (beep)
17217 (message "Bad sexp at line %d in %s: %s"
17218 (org-current-line)
17219 (buffer-file-name) sexp)
17220 (sleep-for 2))))))
17221 (cond ((stringp result) (split-string result "; "))
17222 ((and (consp result)
17223 (not (consp (cdr result)))
17224 (stringp (cdr result))) (cdr result))
17225 ((and (consp result)
17226 (stringp (car result))) result)
17227 (result entry))))
17229 (defun org-diary-to-ical-string (frombuf)
17230 "Get iCalendar entries from diary entries in buffer FROMBUF.
17231 This uses the icalendar.el library."
17232 (let* ((tmpdir (if (featurep 'xemacs)
17233 (temp-directory)
17234 temporary-file-directory))
17235 (tmpfile (make-temp-name
17236 (expand-file-name "orgics" tmpdir)))
17237 buf rtn b e)
17238 (with-current-buffer frombuf
17239 (icalendar-export-region (point-min) (point-max) tmpfile)
17240 (setq buf (find-buffer-visiting tmpfile))
17241 (set-buffer buf)
17242 (goto-char (point-min))
17243 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17244 (setq b (match-beginning 0)))
17245 (goto-char (point-max))
17246 (if (re-search-backward "^END:VEVENT" nil t)
17247 (setq e (match-end 0)))
17248 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17249 (kill-buffer buf)
17250 (delete-file tmpfile)
17251 rtn))
17253 (defun org-closest-date (start current change prefer show-all)
17254 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17255 When PREFER is `past', return a date that is either CURRENT or past.
17256 When PREFER is `future', return a date that is either CURRENT or future.
17257 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17258 ;; Make the proper lists from the dates
17259 (catch 'exit
17260 (let ((a1 '(("h" . hour)
17261 ("d" . day)
17262 ("w" . week)
17263 ("m" . month)
17264 ("y" . year)))
17265 (shour (nth 2 (org-parse-time-string start)))
17266 dn dw sday cday n1 n2 n0
17267 d m y y1 y2 date1 date2 nmonths nm ny m2)
17269 (setq start (org-date-to-gregorian start)
17270 current (org-date-to-gregorian
17271 (if show-all
17272 current
17273 (time-to-days (current-time))))
17274 sday (calendar-absolute-from-gregorian start)
17275 cday (calendar-absolute-from-gregorian current))
17277 (if (<= cday sday) (throw 'exit sday))
17279 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17280 (setq dn (string-to-number (match-string 1 change))
17281 dw (cdr (assoc (match-string 2 change) a1)))
17282 (user-error "Invalid change specifier: %s" change))
17283 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17284 (cond
17285 ((eq dw 'hour)
17286 (let ((missing-hours
17287 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17288 dn)))
17289 (setq n1 (if (zerop missing-hours) cday
17290 (- cday (1+ (floor (/ missing-hours 24)))))
17291 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17292 ((eq dw 'day)
17293 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17294 n2 (+ n1 dn)))
17295 ((eq dw 'year)
17296 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17297 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17298 (setq date1 (list m d y1)
17299 n1 (calendar-absolute-from-gregorian date1)
17300 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17301 n2 (calendar-absolute-from-gregorian date2)))
17302 ((eq dw 'month)
17303 ;; approx number of month between the two dates
17304 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17305 ;; How often does dn fit in there?
17306 (setq d (nth 1 start) m (car start) y (nth 2 start)
17307 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17308 m (+ m nm)
17309 ny (floor (/ m 12))
17310 y (+ y ny)
17311 m (- m (* ny 12)))
17312 (while (> m 12) (setq m (- m 12) y (1+ y)))
17313 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17314 (setq m2 (+ m dn) y2 y)
17315 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17316 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17317 (while (<= n2 cday)
17318 (setq n1 n2 m m2 y y2)
17319 (setq m2 (+ m dn) y2 y)
17320 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17321 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17322 ;; Make sure n1 is the earlier date
17323 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17324 (if show-all
17325 (cond
17326 ((eq prefer 'past) (if (= cday n2) n2 n1))
17327 ((eq prefer 'future) (if (= cday n1) n1 n2))
17328 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17329 (cond
17330 ((eq prefer 'past) (if (= cday n2) n2 n1))
17331 ((eq prefer 'future) (if (= cday n1) n1 n2))
17332 (t (if (= cday n1) n1 n2)))))))
17334 (defun org-date-to-gregorian (date)
17335 "Turn any specification of DATE into a Gregorian date for the calendar."
17336 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17337 ((and (listp date) (= (length date) 3)) date)
17338 ((stringp date)
17339 (setq date (org-parse-time-string date))
17340 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17341 ((listp date)
17342 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17344 (defun org-parse-time-string (s &optional nodefault)
17345 "Parse the standard Org-mode time string.
17346 This should be a lot faster than the normal `parse-time-string'.
17347 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17348 hour and minute fields will be nil if not given."
17349 (cond ((string-match org-ts-regexp0 s)
17350 (list 0
17351 (if (or (match-beginning 8) (not nodefault))
17352 (string-to-number (or (match-string 8 s) "0")))
17353 (if (or (match-beginning 7) (not nodefault))
17354 (string-to-number (or (match-string 7 s) "0")))
17355 (string-to-number (match-string 4 s))
17356 (string-to-number (match-string 3 s))
17357 (string-to-number (match-string 2 s))
17358 nil nil nil))
17359 ((string-match "^<[^>]+>$" s)
17360 (decode-time (seconds-to-time (org-matcher-time s))))
17361 (t (error "Not a standard Org-mode time string: %s" s))))
17363 (defun org-timestamp-up (&optional arg)
17364 "Increase the date item at the cursor by one.
17365 If the cursor is on the year, change the year. If it is on the month,
17366 the day or the time, change that.
17367 With prefix ARG, change by that many units."
17368 (interactive "p")
17369 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17371 (defun org-timestamp-down (&optional arg)
17372 "Decrease the date item at the cursor by one.
17373 If the cursor is on the year, change the year. If it is on the month,
17374 the day or the time, change that.
17375 With prefix ARG, change by that many units."
17376 (interactive "p")
17377 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17379 (defun org-timestamp-up-day (&optional arg)
17380 "Increase the date in the time stamp by one day.
17381 With prefix ARG, change that many days."
17382 (interactive "p")
17383 (if (and (not (org-at-timestamp-p t))
17384 (org-at-heading-p))
17385 (org-todo 'up)
17386 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17388 (defun org-timestamp-down-day (&optional arg)
17389 "Decrease the date in the time stamp by one day.
17390 With prefix ARG, change that many days."
17391 (interactive "p")
17392 (if (and (not (org-at-timestamp-p t))
17393 (org-at-heading-p))
17394 (org-todo 'down)
17395 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17397 (defun org-at-timestamp-p (&optional inactive-ok)
17398 "Determine if the cursor is in or at a timestamp."
17399 (interactive)
17400 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17401 (pos (point))
17402 (ans (or (looking-at tsr)
17403 (save-excursion
17404 (skip-chars-backward "^[<\n\r\t")
17405 (if (> (point) (point-min)) (backward-char 1))
17406 (and (looking-at tsr)
17407 (> (- (match-end 0) pos) -1))))))
17408 (and ans
17409 (boundp 'org-ts-what)
17410 (setq org-ts-what
17411 (cond
17412 ((= pos (match-beginning 0)) 'bracket)
17413 ;; Point is considered to be "on the bracket" whether
17414 ;; it's really on it or right after it.
17415 ((= pos (1- (match-end 0))) 'bracket)
17416 ((= pos (match-end 0)) 'after)
17417 ((org-pos-in-match-range pos 2) 'year)
17418 ((org-pos-in-match-range pos 3) 'month)
17419 ((org-pos-in-match-range pos 7) 'hour)
17420 ((org-pos-in-match-range pos 8) 'minute)
17421 ((or (org-pos-in-match-range pos 4)
17422 (org-pos-in-match-range pos 5)) 'day)
17423 ((and (> pos (or (match-end 8) (match-end 5)))
17424 (< pos (match-end 0)))
17425 (- pos (or (match-end 8) (match-end 5))))
17426 (t 'day))))
17427 ans))
17429 (defun org-toggle-timestamp-type ()
17430 "Toggle the type (<active> or [inactive]) of a time stamp."
17431 (interactive)
17432 (when (org-at-timestamp-p t)
17433 (let ((beg (match-beginning 0)) (end (match-end 0))
17434 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17435 (save-excursion
17436 (goto-char beg)
17437 (while (re-search-forward "[][<>]" end t)
17438 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17439 t t)))
17440 (message "Timestamp is now %sactive"
17441 (if (equal (char-after beg) ?<) "" "in")))))
17443 (defun org-at-clock-log-p nil
17444 "Is the cursor on the clock log line?"
17445 (save-excursion
17446 (move-beginning-of-line 1)
17447 (looking-at "^[ \t]*CLOCK:")))
17449 (defvar org-clock-history) ; defined in org-clock.el
17450 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17451 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17452 "Change the date in the time stamp at point.
17453 The date will be changed by N times WHAT. WHAT can be `day', `month',
17454 `year', `minute', `second'. If WHAT is not given, the cursor position
17455 in the timestamp determines what will be changed.
17456 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17457 (let ((origin (point)) origin-cat
17458 with-hm inactive
17459 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17460 org-ts-what
17461 extra rem
17462 ts time time0 fixnext clrgx)
17463 (if (not (org-at-timestamp-p t))
17464 (user-error "Not at a timestamp"))
17465 (if (and (not what) (eq org-ts-what 'bracket))
17466 (org-toggle-timestamp-type)
17467 ;; Point isn't on brackets. Remember the part of the time-stamp
17468 ;; the point was in. Indeed, size of time-stamps may change,
17469 ;; but point must be kept in the same category nonetheless.
17470 (setq origin-cat org-ts-what)
17471 (if (and (not what) (not (eq org-ts-what 'day))
17472 org-display-custom-times
17473 (get-text-property (point) 'display)
17474 (not (get-text-property (1- (point)) 'display)))
17475 (setq org-ts-what 'day))
17476 (setq org-ts-what (or what org-ts-what)
17477 inactive (= (char-after (match-beginning 0)) ?\[)
17478 ts (match-string 0))
17479 (replace-match "")
17480 (when (string-match
17481 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17483 (setq extra (match-string 1 ts))
17484 (if suppress-tmp-delay
17485 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17486 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17487 (setq with-hm t))
17488 (setq time0 (org-parse-time-string ts))
17489 (when (and updown
17490 (eq org-ts-what 'minute)
17491 (not current-prefix-arg))
17492 ;; This looks like s-up and s-down. Change by one rounding step.
17493 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17494 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17495 (setcar (cdr time0) (+ (nth 1 time0)
17496 (if (> n 0) (- rem) (- dm rem))))))
17497 (setq time
17498 (encode-time (or (car time0) 0)
17499 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17500 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17501 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17502 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17503 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17504 (nthcdr 6 time0)))
17505 (when (and (member org-ts-what '(hour minute))
17506 extra
17507 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17508 (setq extra (org-modify-ts-extra
17509 extra
17510 (if (eq org-ts-what 'hour) 2 5)
17511 n dm)))
17512 (when (integerp org-ts-what)
17513 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17514 (if (eq what 'calendar)
17515 (let ((cal-date (org-get-date-from-calendar)))
17516 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17517 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17518 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17519 (setcar time0 (or (car time0) 0))
17520 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17521 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17522 (setq time (apply 'encode-time time0))))
17523 ;; Insert the new time-stamp, and ensure point stays in the same
17524 ;; category as before (i.e. not after the last position in that
17525 ;; category).
17526 (let ((pos (point)))
17527 ;; Stay before inserted string. `save-excursion' is of no use.
17528 (setq org-last-changed-timestamp
17529 (org-insert-time-stamp time with-hm inactive nil nil extra))
17530 (goto-char pos))
17531 (save-match-data
17532 (looking-at org-ts-regexp3)
17533 (goto-char (cond
17534 ;; `day' category ends before `hour' if any, or at
17535 ;; the end of the day name.
17536 ((eq origin-cat 'day)
17537 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17538 ((eq origin-cat 'hour) (min (match-end 7) origin))
17539 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17540 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17541 ;; `year' and `month' have both fixed size: point
17542 ;; couldn't have moved into another part.
17543 (t origin))))
17544 ;; Update clock if on a CLOCK line.
17545 (org-clock-update-time-maybe)
17546 ;; Maybe adjust the closest clock in `org-clock-history'
17547 (when org-clock-adjust-closest
17548 (if (not (and (org-at-clock-log-p)
17549 (< 1 (length (delq nil (mapcar 'marker-position
17550 org-clock-history))))))
17551 (message "No clock to adjust")
17552 (cond ((save-excursion ; fix previous clock?
17553 (re-search-backward org-ts-regexp0 nil t)
17554 (org-looking-back (concat org-clock-string " \\[")))
17555 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17556 ((save-excursion ; fix next clock?
17557 (re-search-backward org-ts-regexp0 nil t)
17558 (looking-at (concat org-ts-regexp0 "\\] =>")))
17559 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17560 (save-window-excursion
17561 ;; Find closest clock to point, adjust the previous/next one in history
17562 (let* ((p (save-excursion (org-back-to-heading t)))
17563 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17564 (clfixnth
17565 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17566 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17567 (if (not clfixpos)
17568 (message "No clock to adjust")
17569 (save-excursion
17570 (org-goto-marker-or-bmk clfixpos)
17571 (org-show-subtree)
17572 (when (re-search-forward clrgx nil t)
17573 (goto-char (match-beginning 1))
17574 (let (org-clock-adjust-closest)
17575 (org-timestamp-change n org-ts-what updown))
17576 (message "Clock adjusted in %s for heading: %s"
17577 (file-name-nondirectory (buffer-file-name))
17578 (org-get-heading t t)))))))))
17579 ;; Try to recenter the calendar window, if any.
17580 (if (and org-calendar-follow-timestamp-change
17581 (get-buffer-window "*Calendar*" t)
17582 (memq org-ts-what '(day month year)))
17583 (org-recenter-calendar (time-to-days time))))))
17585 (defun org-modify-ts-extra (s pos n dm)
17586 "Change the different parts of the lead-time and repeat fields in timestamp."
17587 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17588 ng h m new rem)
17589 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17590 (cond
17591 ((or (org-pos-in-match-range pos 2)
17592 (org-pos-in-match-range pos 3))
17593 (setq m (string-to-number (match-string 3 s))
17594 h (string-to-number (match-string 2 s)))
17595 (if (org-pos-in-match-range pos 2)
17596 (setq h (+ h n))
17597 (setq n (* dm (org-no-warnings (signum n))))
17598 (when (not (= 0 (setq rem (% m dm))))
17599 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17600 (setq m (+ m n)))
17601 (if (< m 0) (setq m (+ m 60) h (1- h)))
17602 (if (> m 59) (setq m (- m 60) h (1+ h)))
17603 (setq h (min 24 (max 0 h)))
17604 (setq ng 1 new (format "-%02d:%02d" h m)))
17605 ((org-pos-in-match-range pos 6)
17606 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17607 ((org-pos-in-match-range pos 5)
17608 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17610 ((org-pos-in-match-range pos 9)
17611 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17612 ((org-pos-in-match-range pos 8)
17613 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17615 (when ng
17616 (setq s (concat
17617 (substring s 0 (match-beginning ng))
17619 (substring s (match-end ng))))))
17622 (defun org-recenter-calendar (date)
17623 "If the calendar is visible, recenter it to DATE."
17624 (let ((cwin (get-buffer-window "*Calendar*" t)))
17625 (when cwin
17626 (let ((calendar-move-hook nil))
17627 (with-selected-window cwin
17628 (calendar-goto-date (if (listp date) date
17629 (calendar-gregorian-from-absolute date))))))))
17631 (defun org-goto-calendar (&optional arg)
17632 "Go to the Emacs calendar at the current date.
17633 If there is a time stamp in the current line, go to that date.
17634 A prefix ARG can be used to force the current date."
17635 (interactive "P")
17636 (let ((tsr org-ts-regexp) diff
17637 (calendar-move-hook nil)
17638 (calendar-view-holidays-initially-flag nil)
17639 (calendar-view-diary-initially-flag nil))
17640 (if (or (org-at-timestamp-p)
17641 (save-excursion
17642 (beginning-of-line 1)
17643 (looking-at (concat ".*" tsr))))
17644 (let ((d1 (time-to-days (current-time)))
17645 (d2 (time-to-days
17646 (org-time-string-to-time (match-string 1)))))
17647 (setq diff (- d2 d1))))
17648 (calendar)
17649 (calendar-goto-today)
17650 (if (and diff (not arg)) (calendar-forward-day diff))))
17652 (defun org-get-date-from-calendar ()
17653 "Return a list (month day year) of date at point in calendar."
17654 (with-current-buffer "*Calendar*"
17655 (save-match-data
17656 (calendar-cursor-to-date))))
17658 (defun org-date-from-calendar ()
17659 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17660 If there is already a time stamp at the cursor position, update it."
17661 (interactive)
17662 (if (org-at-timestamp-p t)
17663 (org-timestamp-change 0 'calendar)
17664 (let ((cal-date (org-get-date-from-calendar)))
17665 (org-insert-time-stamp
17666 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17668 (defcustom org-effort-durations
17669 `(("h" . 60)
17670 ("d" . ,(* 60 8))
17671 ("w" . ,(* 60 8 5))
17672 ("m" . ,(* 60 8 5 4))
17673 ("y" . ,(* 60 8 5 40)))
17674 "Conversion factor to minutes for an effort modifier.
17676 Each entry has the form (MODIFIER . MINUTES).
17678 In an effort string, a number followed by MODIFIER is multiplied
17679 by the specified number of MINUTES to obtain an effort in
17680 minutes.
17682 For example, if the value of this variable is ((\"hours\" . 60)), then an
17683 effort string \"2hours\" is equivalent to 120 minutes."
17684 :group 'org-agenda
17685 :version "24.1"
17686 :type '(alist :key-type (string :tag "Modifier")
17687 :value-type (number :tag "Minutes")))
17689 (defun org-minutes-to-clocksum-string (m)
17690 "Format number of minutes as a clocksum string.
17691 The format is determined by `org-time-clocksum-format',
17692 `org-time-clocksum-use-fractional' and
17693 `org-time-clocksum-fractional-format' and
17694 `org-time-clocksum-use-effort-durations'."
17695 (let ((clocksum "")
17696 (m (round m)) ; Don't allow fractions of minutes
17697 h d w mo y fmt n)
17698 (setq h (if org-time-clocksum-use-effort-durations
17699 (cdr (assoc "h" org-effort-durations)) 60)
17700 d (if org-time-clocksum-use-effort-durations
17701 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17702 w (if org-time-clocksum-use-effort-durations
17703 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17704 mo (if org-time-clocksum-use-effort-durations
17705 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17706 y (if org-time-clocksum-use-effort-durations
17707 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17708 ;; fractional format
17709 (if org-time-clocksum-use-fractional
17710 (cond
17711 ;; single format string
17712 ((stringp org-time-clocksum-fractional-format)
17713 (format org-time-clocksum-fractional-format (/ m (float h))))
17714 ;; choice of fractional formats for different time units
17715 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17716 (> (/ (truncate m) (* y d h)) 0))
17717 (format fmt (/ m (* y d (float h)))))
17718 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17719 (> (/ (truncate m) (* mo d h)) 0))
17720 (format fmt (/ m (* mo d (float h)))))
17721 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17722 (> (/ (truncate m) (* w d h)) 0))
17723 (format fmt (/ m (* w d (float h)))))
17724 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17725 (> (/ (truncate m) (* d h)) 0))
17726 (format fmt (/ m (* d (float h)))))
17727 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17728 (> (/ (truncate m) h) 0))
17729 (format fmt (/ m (float h))))
17730 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17731 (format fmt m))
17732 ;; fall back to smallest time unit with a format
17733 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17734 (format fmt (/ m (float h))))
17735 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17736 (format fmt (/ m (* d (float h)))))
17737 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17738 (format fmt (/ m (* w d (float h)))))
17739 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17740 (format fmt (/ m (* mo d (float h)))))
17741 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17742 (format fmt (/ m (* y d (float h))))))
17743 ;; standard (non-fractional) format, with single format string
17744 (if (stringp org-time-clocksum-format)
17745 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17746 ;; separate formats components
17747 (and (setq fmt (plist-get org-time-clocksum-format :years))
17748 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17749 (plist-get org-time-clocksum-format :require-years))
17750 (setq clocksum (concat clocksum (format fmt n))
17751 m (- m (* n y d h))))
17752 (and (setq fmt (plist-get org-time-clocksum-format :months))
17753 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17754 (plist-get org-time-clocksum-format :require-months))
17755 (setq clocksum (concat clocksum (format fmt n))
17756 m (- m (* n mo d h))))
17757 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17758 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17759 (plist-get org-time-clocksum-format :require-weeks))
17760 (setq clocksum (concat clocksum (format fmt n))
17761 m (- m (* n w d h))))
17762 (and (setq fmt (plist-get org-time-clocksum-format :days))
17763 (or (> (setq n (/ (truncate m) (* d h))) 0)
17764 (plist-get org-time-clocksum-format :require-days))
17765 (setq clocksum (concat clocksum (format fmt n))
17766 m (- m (* n d h))))
17767 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17768 (or (> (setq n (/ (truncate m) h)) 0)
17769 (plist-get org-time-clocksum-format :require-hours))
17770 (setq clocksum (concat clocksum (format fmt n))
17771 m (- m (* n h))))
17772 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17773 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17774 (setq clocksum (concat clocksum (format fmt m))))
17775 ;; return formatted time duration
17776 clocksum))))
17778 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17779 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17780 "Org mode version 8.0")
17782 (defun org-hours-to-clocksum-string (n)
17783 (org-minutes-to-clocksum-string (* n 60)))
17785 (defun org-hh:mm-string-to-minutes (s)
17786 "Convert a string H:MM to a number of minutes.
17787 If the string is just a number, interpret it as minutes.
17788 In fact, the first hh:mm or number in the string will be taken,
17789 there can be extra stuff in the string.
17790 If no number is found, the return value is 0."
17791 (cond
17792 ((integerp s) s)
17793 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17794 (+ (* (string-to-number (match-string 1 s)) 60)
17795 (string-to-number (match-string 2 s))))
17796 ((string-match "\\([0-9]+\\)" s)
17797 (string-to-number (match-string 1 s)))
17798 (t 0)))
17800 (defcustom org-image-actual-width t
17801 "Should we use the actual width of images when inlining them?
17803 When set to `t', always use the image width.
17805 When set to a number, use imagemagick (when available) to set
17806 the image's width to this value.
17808 When set to a number in a list, try to get the width from any
17809 #+ATTR.* keyword if it matches a width specification like
17811 #+ATTR_HTML: :width 300px
17813 and fall back on that number if none is found.
17815 When set to nil, try to get the width from an #+ATTR.* keyword
17816 and fall back on the original width if none is found.
17818 This requires Emacs >= 24.1, build with imagemagick support."
17819 :group 'org-appearance
17820 :version "24.4"
17821 :package-version '(Org . "8.0")
17822 :type '(choice
17823 (const :tag "Use the image width" t)
17824 (integer :tag "Use a number of pixels")
17825 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17826 (const :tag "Use #+ATTR* or don't resize" nil)))
17828 (defcustom org-agenda-inhibit-startup nil
17829 "Inhibit startup when preparing agenda buffers.
17830 When this variable is `t' (the default), the initialization of
17831 the Org agenda buffers is inhibited: e.g. the visibility state
17832 is not set, the tables are not re-aligned, etc."
17833 :type 'boolean
17834 :version "24.3"
17835 :group 'org-agenda)
17837 (defcustom org-agenda-ignore-drawer-properties nil
17838 "Avoid updating text properties when building the agenda.
17839 Properties are used to prepare buffers for effort estimates, appointments,
17840 and subtree-local categories.
17841 If you don't use these in the agenda, you can add them to this list and
17842 agenda building will be a bit faster.
17843 The value is a list, with zero or more of the symbols `effort', `appt',
17844 or `category'."
17845 :type '(set :greedy t
17846 (const effort)
17847 (const appt)
17848 (const category))
17849 :version "24.3"
17850 :group 'org-agenda)
17852 (defun org-duration-string-to-minutes (s &optional output-to-string)
17853 "Convert a duration string S to minutes.
17855 A bare number is interpreted as minutes, modifiers can be set by
17856 customizing `org-effort-durations' (which see).
17858 Entries containing a colon are interpreted as H:MM by
17859 `org-hh:mm-string-to-minutes'."
17860 (let ((result 0)
17861 (re (concat "\\([0-9.]+\\) *\\("
17862 (regexp-opt (mapcar 'car org-effort-durations))
17863 "\\)")))
17864 (while (string-match re s)
17865 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17866 (string-to-number (match-string 1 s))))
17867 (setq s (replace-match "" nil t s)))
17868 (setq result (floor result))
17869 (incf result (org-hh:mm-string-to-minutes s))
17870 (if output-to-string (number-to-string result) result)))
17872 ;;;; Files
17874 (defun org-save-all-org-buffers ()
17875 "Save all Org-mode buffers without user confirmation."
17876 (interactive)
17877 (message "Saving all Org-mode buffers...")
17878 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17879 (when (featurep 'org-id) (org-id-locations-save))
17880 (message "Saving all Org-mode buffers... done"))
17882 (defun org-revert-all-org-buffers ()
17883 "Revert all Org-mode buffers.
17884 Prompt for confirmation when there are unsaved changes.
17885 Be sure you know what you are doing before letting this function
17886 overwrite your changes.
17888 This function is useful in a setup where one tracks org files
17889 with a version control system, to revert on one machine after pulling
17890 changes from another. I believe the procedure must be like this:
17892 1. M-x org-save-all-org-buffers
17893 2. Pull changes from the other machine, resolve conflicts
17894 3. M-x org-revert-all-org-buffers"
17895 (interactive)
17896 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17897 (user-error "Abort"))
17898 (save-excursion
17899 (save-window-excursion
17900 (mapc
17901 (lambda (b)
17902 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17903 (with-current-buffer b buffer-file-name))
17904 (org-pop-to-buffer-same-window b)
17905 (revert-buffer t 'no-confirm)))
17906 (buffer-list))
17907 (when (and (featurep 'org-id) org-id-track-globally)
17908 (org-id-locations-load)))))
17910 ;;;; Agenda files
17912 ;;;###autoload
17913 (defun org-switchb (&optional arg)
17914 "Switch between Org buffers.
17915 With one prefix argument, restrict available buffers to files.
17916 With two prefix arguments, restrict available buffers to agenda files.
17918 Defaults to `iswitchb' for buffer name completion.
17919 Set `org-completion-use-ido' to make it use ido instead."
17920 (interactive "P")
17921 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17922 ((equal arg '(16)) (org-buffer-list 'agenda))
17923 (t (org-buffer-list))))
17924 (org-completion-use-iswitchb org-completion-use-iswitchb)
17925 (org-completion-use-ido org-completion-use-ido))
17926 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17927 (setq org-completion-use-iswitchb t))
17928 (org-pop-to-buffer-same-window
17929 (org-icompleting-read "Org buffer: "
17930 (mapcar 'list (mapcar 'buffer-name blist))
17931 nil t))))
17933 ;;; Define some older names previously used for this functionality
17934 ;;;###autoload
17935 (defalias 'org-ido-switchb 'org-switchb)
17936 ;;;###autoload
17937 (defalias 'org-iswitchb 'org-switchb)
17939 (defun org-buffer-list (&optional predicate exclude-tmp)
17940 "Return a list of Org buffers.
17941 PREDICATE can be `export', `files' or `agenda'.
17943 export restrict the list to Export buffers.
17944 files restrict the list to buffers visiting Org files.
17945 agenda restrict the list to buffers visiting agenda files.
17947 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17948 (let* ((bfn nil)
17949 (agenda-files (and (eq predicate 'agenda)
17950 (mapcar 'file-truename (org-agenda-files t))))
17951 (filter
17952 (cond
17953 ((eq predicate 'files)
17954 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17955 ((eq predicate 'export)
17956 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17957 ((eq predicate 'agenda)
17958 (lambda (b)
17959 (with-current-buffer b
17960 (and (derived-mode-p 'org-mode)
17961 (setq bfn (buffer-file-name b))
17962 (member (file-truename bfn) agenda-files)))))
17963 (t (lambda (b) (with-current-buffer b
17964 (or (derived-mode-p 'org-mode)
17965 (string-match "\*Org .*Export"
17966 (buffer-name b)))))))))
17967 (delq nil
17968 (mapcar
17969 (lambda(b)
17970 (if (and (funcall filter b)
17971 (or (not exclude-tmp)
17972 (not (string-match "tmp" (buffer-name b)))))
17974 nil))
17975 (buffer-list)))))
17977 (defun org-agenda-files (&optional unrestricted archives)
17978 "Get the list of agenda files.
17979 Optional UNRESTRICTED means return the full list even if a restriction
17980 is currently in place.
17981 When ARCHIVES is t, include all archive files that are really being
17982 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17983 `org-agenda-archives-mode' is t."
17984 (let ((files
17985 (cond
17986 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17987 ((stringp org-agenda-files) (org-read-agenda-file-list))
17988 ((listp org-agenda-files) org-agenda-files)
17989 (t (error "Invalid value of `org-agenda-files'")))))
17990 (setq files (apply 'append
17991 (mapcar (lambda (f)
17992 (if (file-directory-p f)
17993 (directory-files
17994 f t org-agenda-file-regexp)
17995 (list f)))
17996 files)))
17997 (when org-agenda-skip-unavailable-files
17998 (setq files (delq nil
17999 (mapcar (function
18000 (lambda (file)
18001 (and (file-readable-p file) file)))
18002 files))))
18003 (when (or (eq archives t)
18004 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18005 (setq files (org-add-archive-files files)))
18006 files))
18008 (defun org-agenda-file-p (&optional file)
18009 "Return non-nil, if FILE is an agenda file.
18010 If FILE is omitted, use the file associated with the current
18011 buffer."
18012 (member (or file (buffer-file-name))
18013 (org-agenda-files t)))
18015 (defun org-edit-agenda-file-list ()
18016 "Edit the list of agenda files.
18017 Depending on setup, this either uses customize to edit the variable
18018 `org-agenda-files', or it visits the file that is holding the list. In the
18019 latter case, the buffer is set up in a way that saving it automatically kills
18020 the buffer and restores the previous window configuration."
18021 (interactive)
18022 (if (stringp org-agenda-files)
18023 (let ((cw (current-window-configuration)))
18024 (find-file org-agenda-files)
18025 (org-set-local 'org-window-configuration cw)
18026 (org-add-hook 'after-save-hook
18027 (lambda ()
18028 (set-window-configuration
18029 (prog1 org-window-configuration
18030 (kill-buffer (current-buffer))))
18031 (org-install-agenda-files-menu)
18032 (message "New agenda file list installed"))
18033 nil 'local)
18034 (message "%s" (substitute-command-keys
18035 "Edit list and finish with \\[save-buffer]")))
18036 (customize-variable 'org-agenda-files)))
18038 (defun org-store-new-agenda-file-list (list)
18039 "Set new value for the agenda file list and save it correctly."
18040 (if (stringp org-agenda-files)
18041 (let ((fe (org-read-agenda-file-list t)) b u)
18042 (while (setq b (find-buffer-visiting org-agenda-files))
18043 (kill-buffer b))
18044 (with-temp-file org-agenda-files
18045 (insert
18046 (mapconcat
18047 (lambda (f) ;; Keep un-expanded entries.
18048 (if (setq u (assoc f fe))
18049 (cdr u)
18051 list "\n")
18052 "\n")))
18053 (let ((org-mode-hook nil) (org-inhibit-startup t)
18054 (org-insert-mode-line-in-empty-file nil))
18055 (setq org-agenda-files list)
18056 (customize-save-variable 'org-agenda-files org-agenda-files))))
18058 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18059 "Read the list of agenda files from a file.
18060 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18061 filenames, used by `org-store-new-agenda-file-list' to write back
18062 un-expanded file names."
18063 (when (file-directory-p org-agenda-files)
18064 (error "`org-agenda-files' cannot be a single directory"))
18065 (when (stringp org-agenda-files)
18066 (with-temp-buffer
18067 (insert-file-contents org-agenda-files)
18068 (mapcar
18069 (lambda (f)
18070 (let ((e (expand-file-name (substitute-in-file-name f)
18071 org-directory)))
18072 (if pair-with-expansion
18073 (cons e f)
18074 e)))
18075 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18077 ;;;###autoload
18078 (defun org-cycle-agenda-files ()
18079 "Cycle through the files in `org-agenda-files'.
18080 If the current buffer visits an agenda file, find the next one in the list.
18081 If the current buffer does not, find the first agenda file."
18082 (interactive)
18083 (let* ((fs (org-agenda-files t))
18084 (files (append fs (list (car fs))))
18085 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18086 file)
18087 (unless files (user-error "No agenda files"))
18088 (catch 'exit
18089 (while (setq file (pop files))
18090 (if (equal (file-truename file) tcf)
18091 (when (car files)
18092 (find-file (car files))
18093 (throw 'exit t))))
18094 (find-file (car fs)))
18095 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18097 (defun org-agenda-file-to-front (&optional to-end)
18098 "Move/add the current file to the top of the agenda file list.
18099 If the file is not present in the list, it is added to the front. If it is
18100 present, it is moved there. With optional argument TO-END, add/move to the
18101 end of the list."
18102 (interactive "P")
18103 (let ((org-agenda-skip-unavailable-files nil)
18104 (file-alist (mapcar (lambda (x)
18105 (cons (file-truename x) x))
18106 (org-agenda-files t)))
18107 (ctf (file-truename
18108 (or buffer-file-name
18109 (user-error "Please save the current buffer to a file"))))
18110 x had)
18111 (setq x (assoc ctf file-alist) had x)
18113 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18114 (if to-end
18115 (setq file-alist (append (delq x file-alist) (list x)))
18116 (setq file-alist (cons x (delq x file-alist))))
18117 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18118 (org-install-agenda-files-menu)
18119 (message "File %s to %s of agenda file list"
18120 (if had "moved" "added") (if to-end "end" "front"))))
18122 (defun org-remove-file (&optional file)
18123 "Remove current file from the list of files in variable `org-agenda-files'.
18124 These are the files which are being checked for agenda entries.
18125 Optional argument FILE means use this file instead of the current."
18126 (interactive)
18127 (let* ((org-agenda-skip-unavailable-files nil)
18128 (file (or file buffer-file-name
18129 (user-error "Current buffer does not visit a file")))
18130 (true-file (file-truename file))
18131 (afile (abbreviate-file-name file))
18132 (files (delq nil (mapcar
18133 (lambda (x)
18134 (if (equal true-file
18135 (file-truename x))
18136 nil x))
18137 (org-agenda-files t)))))
18138 (if (not (= (length files) (length (org-agenda-files t))))
18139 (progn
18140 (org-store-new-agenda-file-list files)
18141 (org-install-agenda-files-menu)
18142 (message "Removed file: %s" afile))
18143 (message "File was not in list: %s (not removed)" afile))))
18145 (defun org-file-menu-entry (file)
18146 (vector file (list 'find-file file) t))
18148 (defun org-check-agenda-file (file)
18149 "Make sure FILE exists. If not, ask user what to do."
18150 (when (not (file-exists-p file))
18151 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18152 (abbreviate-file-name file))
18153 (let ((r (downcase (read-char-exclusive))))
18154 (cond
18155 ((equal r ?r)
18156 (org-remove-file file)
18157 (throw 'nextfile t))
18158 (t (user-error "Abort"))))))
18160 (defun org-get-agenda-file-buffer (file)
18161 "Get a buffer visiting FILE. If the buffer needs to be created, add
18162 it to the list of buffers which might be released later."
18163 (let ((buf (org-find-base-buffer-visiting file)))
18164 (if buf
18165 buf ; just return it
18166 ;; Make a new buffer and remember it
18167 (setq buf (find-file-noselect file))
18168 (if buf (push buf org-agenda-new-buffers))
18169 buf)))
18171 (defun org-release-buffers (blist)
18172 "Release all buffers in list, asking the user for confirmation when needed.
18173 When a buffer is unmodified, it is just killed. When modified, it is saved
18174 \(if the user agrees) and then killed."
18175 (let (buf file)
18176 (while (setq buf (pop blist))
18177 (setq file (buffer-file-name buf))
18178 (when (and (buffer-modified-p buf)
18179 file
18180 (y-or-n-p (format "Save file %s? " file)))
18181 (with-current-buffer buf (save-buffer)))
18182 (kill-buffer buf))))
18184 (defun org-agenda-prepare-buffers (files)
18185 "Create buffers for all agenda files, protect archived trees and comments."
18186 (interactive)
18187 (let ((pa '(:org-archived t))
18188 (pc '(:org-comment t))
18189 (pall '(:org-archived t :org-comment t))
18190 (inhibit-read-only t)
18191 (org-inhibit-startup org-agenda-inhibit-startup)
18192 (rea (concat ":" org-archive-tag ":"))
18193 file re pos)
18194 (setq org-tag-alist-for-agenda nil
18195 org-tag-groups-alist-for-agenda nil)
18196 (save-excursion
18197 (save-restriction
18198 (while (setq file (pop files))
18199 (catch 'nextfile
18200 (if (bufferp file)
18201 (set-buffer file)
18202 (org-check-agenda-file file)
18203 (set-buffer (org-get-agenda-file-buffer file)))
18204 (widen)
18205 (org-set-regexps-and-options-for-tags)
18206 (setq pos (point))
18207 (goto-char (point-min))
18208 (let ((case-fold-search t))
18209 (when (search-forward "#+setupfile" nil t)
18210 ;; Don't set all regexps and options systematically as
18211 ;; this is only run for setting agenda tags from setup
18212 ;; file
18213 (org-set-regexps-and-options)))
18214 (or (memq 'category org-agenda-ignore-drawer-properties)
18215 (org-refresh-category-properties))
18216 (or (memq 'effort org-agenda-ignore-drawer-properties)
18217 (org-refresh-properties org-effort-property 'org-effort))
18218 (or (memq 'appt org-agenda-ignore-drawer-properties)
18219 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18220 (setq org-todo-keywords-for-agenda
18221 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18222 (setq org-done-keywords-for-agenda
18223 (append org-done-keywords-for-agenda org-done-keywords))
18224 (setq org-todo-keyword-alist-for-agenda
18225 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18226 (setq org-tag-alist-for-agenda
18227 (org-uniquify
18228 (append org-tag-alist-for-agenda
18229 org-tag-alist
18230 org-tag-persistent-alist)))
18231 (if org-group-tags
18232 (setq org-tag-groups-alist-for-agenda
18233 (org-uniquify-alist
18234 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18235 (org-with-silent-modifications
18236 (save-excursion
18237 (remove-text-properties (point-min) (point-max) pall)
18238 (when org-agenda-skip-archived-trees
18239 (goto-char (point-min))
18240 (while (re-search-forward rea nil t)
18241 (if (org-at-heading-p t)
18242 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18243 (goto-char (point-min))
18244 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18245 (while (re-search-forward re nil t)
18246 (when (save-match-data (org-in-commented-heading-p t))
18247 (add-text-properties
18248 (match-beginning 0) (org-end-of-subtree t) pc)))))
18249 (goto-char pos)))))
18250 (setq org-todo-keywords-for-agenda
18251 (org-uniquify org-todo-keywords-for-agenda))
18252 (setq org-todo-keyword-alist-for-agenda
18253 (org-uniquify org-todo-keyword-alist-for-agenda))))
18256 ;;;; CDLaTeX minor mode
18258 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18259 "Keymap for the minor `org-cdlatex-mode'.")
18261 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18262 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18263 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18264 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18265 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18267 (defvar org-cdlatex-texmathp-advice-is-done nil
18268 "Flag remembering if we have applied the advice to texmathp already.")
18270 (define-minor-mode org-cdlatex-mode
18271 "Toggle the minor `org-cdlatex-mode'.
18272 This mode supports entering LaTeX environment and math in LaTeX fragments
18273 in Org-mode.
18274 \\{org-cdlatex-mode-map}"
18275 nil " OCDL" nil
18276 (when org-cdlatex-mode
18277 (require 'cdlatex)
18278 (run-hooks 'cdlatex-mode-hook)
18279 (cdlatex-compute-tables))
18280 (unless org-cdlatex-texmathp-advice-is-done
18281 (setq org-cdlatex-texmathp-advice-is-done t)
18282 (defadvice texmathp (around org-math-always-on activate)
18283 "Always return t in org-mode buffers.
18284 This is because we want to insert math symbols without dollars even outside
18285 the LaTeX math segments. If Orgmode thinks that point is actually inside
18286 an embedded LaTeX fragment, let texmathp do its job.
18287 \\[org-cdlatex-mode-map]"
18288 (interactive)
18289 (let (p)
18290 (cond
18291 ((not (derived-mode-p 'org-mode)) ad-do-it)
18292 ((eq this-command 'cdlatex-math-symbol)
18293 (setq ad-return-value t
18294 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18296 (let ((p (org-inside-LaTeX-fragment-p)))
18297 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18298 (setq ad-return-value t
18299 texmathp-why '("Org-mode embedded math" . 0))
18300 (if p ad-do-it)))))))))
18302 (defun turn-on-org-cdlatex ()
18303 "Unconditionally turn on `org-cdlatex-mode'."
18304 (org-cdlatex-mode 1))
18306 (defun org-try-cdlatex-tab ()
18307 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18308 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18309 - inside a LaTeX fragment, or
18310 - after the first word in a line, where an abbreviation expansion could
18311 insert a LaTeX environment."
18312 (when org-cdlatex-mode
18313 (cond
18314 ;; Before any word on the line: No expansion possible.
18315 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18316 ;; Just after first word on the line: Expand it. Make sure it
18317 ;; cannot happen on headlines, though.
18318 ((save-excursion
18319 (skip-chars-backward "a-zA-Z0-9*")
18320 (skip-chars-backward " \t")
18321 (and (bolp) (not (org-at-heading-p))))
18322 (cdlatex-tab) t)
18323 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18325 (defun org-cdlatex-underscore-caret (&optional arg)
18326 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18327 Revert to the normal definition outside of these fragments."
18328 (interactive "P")
18329 (if (org-inside-LaTeX-fragment-p)
18330 (call-interactively 'cdlatex-sub-superscript)
18331 (let (org-cdlatex-mode)
18332 (call-interactively (key-binding (vector last-input-event))))))
18334 (defun org-cdlatex-math-modify (&optional arg)
18335 "Execute `cdlatex-math-modify' in LaTeX fragments.
18336 Revert to the normal definition outside of these fragments."
18337 (interactive "P")
18338 (if (org-inside-LaTeX-fragment-p)
18339 (call-interactively 'cdlatex-math-modify)
18340 (let (org-cdlatex-mode)
18341 (call-interactively (key-binding (vector last-input-event))))))
18345 ;;;; LaTeX fragments
18347 (defun org-inside-LaTeX-fragment-p ()
18348 "Test if point is inside a LaTeX fragment.
18349 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18350 sequence appearing also before point.
18351 Even though the matchers for math are configurable, this function assumes
18352 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18353 delimiters are skipped when they have been removed by customization.
18354 The return value is nil, or a cons cell with the delimiter and the
18355 position of this delimiter.
18357 This function does a reasonably good job, but can locally be fooled by
18358 for example currency specifications. For example it will assume being in
18359 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18360 fragments that are properly closed, but during editing, we have to live
18361 with the uncertainty caused by missing closing delimiters. This function
18362 looks only before point, not after."
18363 (catch 'exit
18364 (let ((pos (point))
18365 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18366 (lim (progn
18367 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18368 (point)))
18369 dd-on str (start 0) m re)
18370 (goto-char pos)
18371 (when dodollar
18372 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18373 re (nth 1 (assoc "$" org-latex-regexps)))
18374 (while (string-match re str start)
18375 (cond
18376 ((= (match-end 0) (length str))
18377 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18378 ((= (match-end 0) (- (length str) 5))
18379 (throw 'exit nil))
18380 (t (setq start (match-end 0))))))
18381 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18382 (goto-char pos)
18383 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18384 (and (match-beginning 2) (throw 'exit nil))
18385 ;; count $$
18386 (while (re-search-backward "\\$\\$" lim t)
18387 (setq dd-on (not dd-on)))
18388 (goto-char pos)
18389 (if dd-on (cons "$$" m))))))
18391 (defun org-inside-latex-macro-p ()
18392 "Is point inside a LaTeX macro or its arguments?"
18393 (save-match-data
18394 (org-in-regexp
18395 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18397 (defvar org-latex-fragment-image-overlays nil
18398 "List of overlays carrying the images of latex fragments.")
18399 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18401 (defun org-remove-latex-fragment-image-overlays ()
18402 "Remove all overlays with LaTeX fragment images in current buffer."
18403 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18404 (setq org-latex-fragment-image-overlays nil))
18406 (defun org-preview-latex-fragment (&optional subtree)
18407 "Preview the LaTeX fragment at point, or all locally or globally.
18408 If the cursor is in a LaTeX fragment, create the image and overlay
18409 it over the source code. If there is no fragment at point, display
18410 all fragments in the current text, from one headline to the next. With
18411 prefix SUBTREE, display all fragments in the current subtree. With a
18412 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18413 the cursor is before the first headline,
18414 display all fragments in the buffer.
18415 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18416 (interactive "P")
18417 (unless buffer-file-name
18418 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18419 (when (display-graphic-p)
18420 (org-remove-latex-fragment-image-overlays)
18421 (save-excursion
18422 (save-restriction
18423 (let (beg end at msg)
18424 (cond
18425 ((or (equal subtree '(16))
18426 (not (save-excursion
18427 (re-search-backward org-outline-regexp-bol nil t))))
18428 (setq beg (point-min) end (point-max)
18429 msg "Creating images for buffer...%s"))
18430 ((equal subtree '(4))
18431 (org-back-to-heading)
18432 (setq beg (point) end (org-end-of-subtree t)
18433 msg "Creating images for subtree...%s"))
18435 (if (setq at (org-inside-LaTeX-fragment-p))
18436 (goto-char (max (point-min) (- (cdr at) 2)))
18437 (org-back-to-heading))
18438 (setq beg (point) end (progn (outline-next-heading) (point))
18439 msg (if at "Creating image...%s"
18440 "Creating images for entry...%s"))))
18441 (message msg "")
18442 (narrow-to-region beg end)
18443 (goto-char beg)
18444 (org-format-latex
18445 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18446 (file-name-nondirectory
18447 buffer-file-name)))
18448 default-directory 'overlays msg at 'forbuffer
18449 org-latex-create-formula-image-program)
18450 (message msg "done. Use `C-c C-c' to remove images."))))))
18452 (defun org-format-latex (prefix &optional dir overlays msg at
18453 forbuffer processing-type)
18454 "Replace LaTeX fragments with links to an image, and produce images.
18455 Some of the options can be changed using the variable
18456 `org-format-latex-options'."
18457 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18458 (let* ((prefixnodir (file-name-nondirectory prefix))
18459 (absprefix (expand-file-name prefix dir))
18460 (todir (file-name-directory absprefix))
18461 (opt org-format-latex-options)
18462 (optnew org-format-latex-options)
18463 (matchers (plist-get opt :matchers))
18464 (re-list org-latex-regexps)
18465 (cnt 0) txt hash link beg end re e checkdir
18466 string
18467 m n block-type block linkfile movefile ov)
18468 ;; Check the different regular expressions
18469 (while (setq e (pop re-list))
18470 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18471 block (if block-type "\n\n" ""))
18472 (when (member m matchers)
18473 (goto-char (point-min))
18474 (while (re-search-forward re nil t)
18475 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18476 (or (not overlays)
18477 (not (eq (get-char-property (match-beginning n)
18478 'org-overlay-type)
18479 'org-latex-overlay))))
18480 (cond
18481 ((eq processing-type 'verbatim))
18482 ((eq processing-type 'mathjax)
18483 ;; Prepare for MathJax processing.
18484 (setq string (match-string n))
18485 (when (member m '("$" "$1"))
18486 (save-excursion
18487 (delete-region (match-beginning n) (match-end n))
18488 (goto-char (match-beginning n))
18489 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18490 ((or (eq processing-type 'dvipng)
18491 (eq processing-type 'imagemagick))
18492 ;; Process to an image.
18493 (setq txt (match-string n)
18494 beg (match-beginning n) end (match-end n)
18495 cnt (1+ cnt))
18496 (let ((face (face-at-point))
18497 (fg (plist-get opt :foreground))
18498 (bg (plist-get opt :background))
18499 ;; Ensure full list is printed.
18500 print-length print-level)
18501 (when forbuffer
18502 ;; Get the colors from the face at point.
18503 (goto-char beg)
18504 (when (eq fg 'auto)
18505 (setq fg (face-attribute face :foreground nil 'default)))
18506 (when (eq bg 'auto)
18507 (setq bg (face-attribute face :background nil 'default)))
18508 (setq optnew (copy-sequence opt))
18509 (plist-put optnew :foreground fg)
18510 (plist-put optnew :background bg))
18511 (setq hash (sha1 (prin1-to-string
18512 (list org-format-latex-header
18513 org-latex-default-packages-alist
18514 org-latex-packages-alist
18515 org-format-latex-options
18516 forbuffer txt fg bg)))
18517 linkfile (format "%s_%s.png" prefix hash)
18518 movefile (format "%s_%s.png" absprefix hash)))
18519 (setq link (concat block "[[file:" linkfile "]]" block))
18520 (if msg (message msg cnt))
18521 (goto-char beg)
18522 (unless checkdir ; Ensure the directory exists.
18523 (setq checkdir t)
18524 (or (file-directory-p todir) (make-directory todir t)))
18525 (unless (file-exists-p movefile)
18526 (org-create-formula-image
18527 txt movefile optnew forbuffer processing-type))
18528 (if overlays
18529 (progn
18530 (mapc (lambda (o)
18531 (if (eq (overlay-get o 'org-overlay-type)
18532 'org-latex-overlay)
18533 (delete-overlay o)))
18534 (overlays-in beg end))
18535 (setq ov (make-overlay beg end))
18536 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18537 (if (featurep 'xemacs)
18538 (progn
18539 (overlay-put ov 'invisible t)
18540 (overlay-put
18541 ov 'end-glyph
18542 (make-glyph (vector 'png :file movefile))))
18543 (overlay-put
18544 ov 'display
18545 (list 'image :type 'png :file movefile :ascent 'center)))
18546 (push ov org-latex-fragment-image-overlays)
18547 (goto-char end))
18548 (delete-region beg end)
18549 (insert (org-add-props link
18550 (list 'org-latex-src
18551 (replace-regexp-in-string
18552 "\"" "" txt)
18553 'org-latex-src-embed-type
18554 (if block-type 'paragraph 'character))))))
18555 ((eq processing-type 'mathml)
18556 ;; Process to MathML
18557 (unless (save-match-data (org-format-latex-mathml-available-p))
18558 (user-error "LaTeX to MathML converter not configured"))
18559 (setq txt (match-string n)
18560 beg (match-beginning n) end (match-end n)
18561 cnt (1+ cnt))
18562 (if msg (message msg cnt))
18563 (goto-char beg)
18564 (delete-region beg end)
18565 (insert (org-format-latex-as-mathml
18566 txt block-type prefix dir)))
18568 (error "Unknown conversion type %s for LaTeX fragments"
18569 processing-type)))))))))
18571 (defun org-create-math-formula (latex-frag &optional mathml-file)
18572 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18573 Use `org-latex-to-mathml-convert-command'. If the conversion is
18574 sucessful, return the portion between \"<math...> </math>\"
18575 elements otherwise return nil. When MATHML-FILE is specified,
18576 write the results in to that file. When invoked as an
18577 interactive command, prompt for LATEX-FRAG, with initial value
18578 set to the current active region and echo the results for user
18579 inspection."
18580 (interactive (list (let ((frag (when (org-region-active-p)
18581 (buffer-substring-no-properties
18582 (region-beginning) (region-end)))))
18583 (read-string "LaTeX Fragment: " frag nil frag))))
18584 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18585 (let* ((tmp-in-file (file-relative-name
18586 (make-temp-name (expand-file-name "ltxmathml-in"))))
18587 (ignore (write-region latex-frag nil tmp-in-file))
18588 (tmp-out-file (file-relative-name
18589 (make-temp-name (expand-file-name "ltxmathml-out"))))
18590 (cmd (format-spec
18591 org-latex-to-mathml-convert-command
18592 `((?j . ,(shell-quote-argument
18593 (expand-file-name org-latex-to-mathml-jar-file)))
18594 (?I . ,(shell-quote-argument tmp-in-file))
18595 (?o . ,(shell-quote-argument tmp-out-file)))))
18596 mathml shell-command-output)
18597 (when (org-called-interactively-p 'any)
18598 (unless (org-format-latex-mathml-available-p)
18599 (user-error "LaTeX to MathML converter not configured")))
18600 (message "Running %s" cmd)
18601 (setq shell-command-output (shell-command-to-string cmd))
18602 (setq mathml
18603 (when (file-readable-p tmp-out-file)
18604 (with-current-buffer (find-file-noselect tmp-out-file t)
18605 (goto-char (point-min))
18606 (when (re-search-forward
18607 (concat
18608 (regexp-quote
18609 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18610 "\\(.\\|\n\\)*"
18611 (regexp-quote "</math>")) nil t)
18612 (prog1 (match-string 0) (kill-buffer))))))
18613 (cond
18614 (mathml
18615 (setq mathml
18616 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18617 (when mathml-file
18618 (write-region mathml nil mathml-file))
18619 (when (org-called-interactively-p 'any)
18620 (message mathml)))
18621 ((message "LaTeX to MathML conversion failed")
18622 (message shell-command-output)))
18623 (delete-file tmp-in-file)
18624 (when (file-exists-p tmp-out-file)
18625 (delete-file tmp-out-file))
18626 mathml))
18628 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18629 prefix &optional dir)
18630 "Use `org-create-math-formula' but check local cache first."
18631 (let* ((absprefix (expand-file-name prefix dir))
18632 (print-length nil) (print-level nil)
18633 (formula-id (concat
18634 "formula-"
18635 (sha1
18636 (prin1-to-string
18637 (list latex-frag
18638 org-latex-to-mathml-convert-command)))))
18639 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18640 (formula-cache-dir (file-name-directory formula-cache)))
18642 (unless (file-directory-p formula-cache-dir)
18643 (make-directory formula-cache-dir t))
18645 (unless (file-exists-p formula-cache)
18646 (org-create-math-formula latex-frag formula-cache))
18648 (if (file-exists-p formula-cache)
18649 ;; Successful conversion. Return the link to MathML file.
18650 (org-add-props
18651 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18652 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18653 'org-latex-src-embed-type (if latex-frag-type
18654 'paragraph 'character)))
18655 ;; Failed conversion. Return the LaTeX fragment verbatim
18656 latex-frag)))
18658 (defun org-create-formula-image (string tofile options buffer &optional type)
18659 "Create an image from LaTeX source using dvipng or convert.
18660 This function calls either `org-create-formula-image-with-dvipng'
18661 or `org-create-formula-image-with-imagemagick' depending on the
18662 value of `org-latex-create-formula-image-program' or on the value
18663 of the optional TYPE variable.
18665 Note: ultimately these two function should be combined as they
18666 share a good deal of logic."
18667 (org-check-external-command
18668 "latex" "needed to convert LaTeX fragments to images")
18669 (funcall
18670 (case (or type org-latex-create-formula-image-program)
18671 ('dvipng
18672 (org-check-external-command
18673 "dvipng" "needed to convert LaTeX fragments to images")
18674 #'org-create-formula-image-with-dvipng)
18675 ('imagemagick
18676 (org-check-external-command
18677 "convert" "you need to install imagemagick")
18678 #'org-create-formula-image-with-imagemagick)
18679 (t (error
18680 "Invalid value of `org-latex-create-formula-image-program'")))
18681 string tofile options buffer))
18683 (declare-function org-export-get-backend "ox" (name))
18684 (declare-function org-export--get-global-options "ox" (&optional backend))
18685 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18686 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18687 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18688 (defun org-create-formula--latex-header ()
18689 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18690 (let ((info (org-combine-plists (org-export--get-global-options
18691 (org-export-get-backend 'latex))
18692 (org-export--get-inbuffer-options
18693 (org-export-get-backend 'latex)))))
18694 (org-latex-guess-babel-language
18695 (org-latex-guess-inputenc
18696 (org-splice-latex-header
18697 org-format-latex-header
18698 org-latex-default-packages-alist
18699 org-latex-packages-alist t
18700 (plist-get info :latex-header)))
18701 info)))
18703 ;; This function borrows from Ganesh Swami's latex2png.el
18704 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18705 "This calls dvipng."
18706 (require 'ox-latex)
18707 (let* ((tmpdir (if (featurep 'xemacs)
18708 (temp-directory)
18709 temporary-file-directory))
18710 (texfilebase (make-temp-name
18711 (expand-file-name "orgtex" tmpdir)))
18712 (texfile (concat texfilebase ".tex"))
18713 (dvifile (concat texfilebase ".dvi"))
18714 (pngfile (concat texfilebase ".png"))
18715 (fnh (if (featurep 'xemacs)
18716 (font-height (face-font 'default))
18717 (face-attribute 'default :height nil)))
18718 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18719 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18720 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18721 "Black"))
18722 (bg (or (plist-get options (if buffer :background :html-background))
18723 "Transparent")))
18724 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18725 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18726 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18727 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18728 (let ((latex-header (org-create-formula--latex-header)))
18729 (with-temp-file texfile
18730 (insert latex-header)
18731 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18732 (let ((dir default-directory))
18733 (condition-case nil
18734 (progn
18735 (cd tmpdir)
18736 (call-process "latex" nil nil nil texfile))
18737 (error nil))
18738 (cd dir))
18739 (if (not (file-exists-p dvifile))
18740 (progn (message "Failed to create dvi file from %s" texfile) nil)
18741 (condition-case nil
18742 (if (featurep 'xemacs)
18743 (call-process "dvipng" nil nil nil
18744 "-fg" fg "-bg" bg
18745 "-T" "tight"
18746 "-o" pngfile
18747 dvifile)
18748 (call-process "dvipng" nil nil nil
18749 "-fg" fg "-bg" bg
18750 "-D" dpi
18751 ;;"-x" scale "-y" scale
18752 "-T" "tight"
18753 "-o" pngfile
18754 dvifile))
18755 (error nil))
18756 (if (not (file-exists-p pngfile))
18757 (if org-format-latex-signal-error
18758 (error "Failed to create png file from %s" texfile)
18759 (message "Failed to create png file from %s" texfile)
18760 nil)
18761 ;; Use the requested file name and clean up
18762 (copy-file pngfile tofile 'replace)
18763 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18764 (if (file-exists-p (concat texfilebase e))
18765 (delete-file (concat texfilebase e))))
18766 pngfile))))
18768 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18769 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18770 "This calls convert, which is included into imagemagick."
18771 (require 'ox-latex)
18772 (let* ((tmpdir (if (featurep 'xemacs)
18773 (temp-directory)
18774 temporary-file-directory))
18775 (texfilebase (make-temp-name
18776 (expand-file-name "orgtex" tmpdir)))
18777 (texfile (concat texfilebase ".tex"))
18778 (pdffile (concat texfilebase ".pdf"))
18779 (pngfile (concat texfilebase ".png"))
18780 (fnh (if (featurep 'xemacs)
18781 (font-height (face-font 'default))
18782 (face-attribute 'default :height nil)))
18783 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18784 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18785 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18786 "black"))
18787 (bg (or (plist-get options (if buffer :background :html-background))
18788 "white")))
18789 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18790 (setq fg (org-latex-color-format fg)))
18791 (if (eq bg 'default) (setq bg (org-latex-color :background))
18792 (setq bg (org-latex-color-format
18793 (if (string= bg "Transparent") "white" bg))))
18794 (let ((latex-header (org-create-formula--latex-header)))
18795 (with-temp-file texfile
18796 (insert latex-header)
18797 (insert "\n\\begin{document}\n"
18798 "\\definecolor{fg}{rgb}{" fg "}\n"
18799 "\\definecolor{bg}{rgb}{" bg "}\n"
18800 "\n\\pagecolor{bg}\n"
18801 "\n{\\color{fg}\n"
18802 string
18803 "\n}\n"
18804 "\n\\end{document}\n")))
18805 (org-latex-compile texfile t)
18806 (if (not (file-exists-p pdffile))
18807 (progn (message "Failed to create pdf file from %s" texfile) nil)
18808 (condition-case nil
18809 (if (featurep 'xemacs)
18810 (call-process "convert" nil nil nil
18811 "-density" "96"
18812 "-trim"
18813 "-antialias"
18814 pdffile
18815 "-quality" "100"
18816 ;; "-sharpen" "0x1.0"
18817 pngfile)
18818 (call-process "convert" nil nil nil
18819 "-density" dpi
18820 "-trim"
18821 "-antialias"
18822 pdffile
18823 "-quality" "100"
18824 ;; "-sharpen" "0x1.0"
18825 pngfile))
18826 (error nil))
18827 (if (not (file-exists-p pngfile))
18828 (if org-format-latex-signal-error
18829 (error "Failed to create png file from %s" texfile)
18830 (message "Failed to create png file from %s" texfile)
18831 nil)
18832 ;; Use the requested file name and clean up
18833 (copy-file pngfile tofile 'replace)
18834 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18835 (if (file-exists-p (concat texfilebase e))
18836 (delete-file (concat texfilebase e))))
18837 pngfile))))
18839 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18840 "Fill a LaTeX header template TPL.
18841 In the template, the following place holders will be recognized:
18843 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18844 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18845 [PACKAGES] \\usepackage statements for PKG
18846 [NO-PACKAGES] do not include PKG
18847 [EXTRA] the string EXTRA
18848 [NO-EXTRA] do not include EXTRA
18850 For backward compatibility, if both the positive and the negative place
18851 holder is missing, the positive one (without the \"NO-\") will be
18852 assumed to be present at the end of the template.
18853 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18854 EXTRA is a string.
18855 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18856 (let (rpl (end ""))
18857 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18858 (setq rpl (if (or (match-end 1) (not def-pkg))
18859 "" (org-latex-packages-to-string def-pkg snippets-p t))
18860 tpl (replace-match rpl t t tpl))
18861 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18863 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18864 (setq rpl (if (or (match-end 1) (not pkg))
18865 "" (org-latex-packages-to-string pkg snippets-p t))
18866 tpl (replace-match rpl t t tpl))
18867 (if pkg (setq end
18868 (concat end "\n"
18869 (org-latex-packages-to-string pkg snippets-p)))))
18871 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18872 (setq rpl (if (or (match-end 1) (not extra))
18873 "" (concat extra "\n"))
18874 tpl (replace-match rpl t t tpl))
18875 (if (and extra (string-match "\\S-" extra))
18876 (setq end (concat end "\n" extra))))
18878 (if (string-match "\\S-" end)
18879 (concat tpl "\n" end)
18880 tpl)))
18882 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18883 "Turn an alist of packages into a string with the \\usepackage macros."
18884 (setq pkg (mapconcat (lambda(p)
18885 (cond
18886 ((stringp p) p)
18887 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18888 (format "%% Package %s omitted" (cadr p)))
18889 ((equal "" (car p))
18890 (format "\\usepackage{%s}" (cadr p)))
18892 (format "\\usepackage[%s]{%s}"
18893 (car p) (cadr p)))))
18895 "\n"))
18896 (if newline (concat pkg "\n") pkg))
18898 (defun org-dvipng-color (attr)
18899 "Return a RGB color specification for dvipng."
18900 (apply 'format "rgb %s %s %s"
18901 (mapcar 'org-normalize-color
18902 (if (featurep 'xemacs)
18903 (color-rgb-components
18904 (face-property 'default
18905 (cond ((eq attr :foreground) 'foreground)
18906 ((eq attr :background) 'background))))
18907 (color-values (face-attribute 'default attr nil))))))
18909 (defun org-dvipng-color-format (color-name)
18910 "Convert COLOR-NAME to a RGB color value for dvipng."
18911 (apply 'format "rgb %s %s %s"
18912 (mapcar 'org-normalize-color
18913 (color-values color-name))))
18915 (defun org-latex-color (attr)
18916 "Return a RGB color for the LaTeX color package."
18917 (apply 'format "%s,%s,%s"
18918 (mapcar 'org-normalize-color
18919 (if (featurep 'xemacs)
18920 (color-rgb-components
18921 (face-property 'default
18922 (cond ((eq attr :foreground) 'foreground)
18923 ((eq attr :background) 'background))))
18924 (color-values (face-attribute 'default attr nil))))))
18926 (defun org-latex-color-format (color-name)
18927 "Convert COLOR-NAME to a RGB color value."
18928 (apply 'format "%s,%s,%s"
18929 (mapcar 'org-normalize-color
18930 (color-values color-name))))
18932 (defun org-normalize-color (value)
18933 "Return string to be used as color value for an RGB component."
18934 (format "%g" (/ value 65535.0)))
18938 ;; Image display
18940 (defvar org-inline-image-overlays nil)
18941 (make-variable-buffer-local 'org-inline-image-overlays)
18943 (defun org-toggle-inline-images (&optional include-linked)
18944 "Toggle the display of inline images.
18945 INCLUDE-LINKED is passed to `org-display-inline-images'."
18946 (interactive "P")
18947 (if org-inline-image-overlays
18948 (progn
18949 (org-remove-inline-images)
18950 (message "Inline image display turned off"))
18951 (org-display-inline-images include-linked)
18952 (if (and (org-called-interactively-p)
18953 org-inline-image-overlays)
18954 (message "%d images displayed inline"
18955 (length org-inline-image-overlays))
18956 (message "No images to display inline"))))
18958 (defun org-redisplay-inline-images ()
18959 "Refresh the display of inline images."
18960 (interactive)
18961 (if (not org-inline-image-overlays)
18962 (org-toggle-inline-images)
18963 (org-toggle-inline-images)
18964 (org-toggle-inline-images)))
18966 (defun org-display-inline-images (&optional include-linked refresh beg end)
18967 "Display inline images.
18969 An inline image is a link which follows either of these
18970 conventions:
18972 1. Its path is a file with an extension matching return value
18973 from `image-file-name-regexp' and it has no contents.
18975 2. Its description consists in a single link of the previous
18976 type.
18978 When optional argument INCLUDE-LINKED is non-nil, also links with
18979 a text description part will be inlined. This can be nice for
18980 a quick look at those images, but it does not reflect what
18981 exported files will look like.
18983 When optional argument REFRESH is non-nil, refresh existing
18984 images between BEG and END. This will create new image displays
18985 only if necessary. BEG and END default to the buffer
18986 boundaries."
18987 (interactive "P")
18988 (when (display-graphic-p)
18989 (unless refresh
18990 (org-remove-inline-images)
18991 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18992 (org-with-wide-buffer
18993 (goto-char (or beg (point-min)))
18994 (let ((case-fold-search t)
18995 (file-extension-re (org-image-file-name-regexp)))
18996 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
18997 (let ((link (save-match-data (org-element-context))))
18998 ;; Check if we're at an inline image.
18999 (when (and (equal (org-element-property :type link) "file")
19000 (or include-linked
19001 (not (org-element-property :contents-begin link)))
19002 (let ((parent (org-element-property :parent link)))
19003 (or (not (eq (org-element-type parent) 'link))
19004 (not (cdr (org-element-contents parent)))))
19005 (org-string-match-p file-extension-re
19006 (org-element-property :path link)))
19007 (let ((file (expand-file-name (org-element-property :path link))))
19008 (when (file-exists-p file)
19009 (let ((width
19010 ;; Apply `org-image-actual-width' specifications.
19011 (cond
19012 ((not (image-type-available-p 'imagemagick)) nil)
19013 ((eq org-image-actual-width t) nil)
19014 ((listp org-image-actual-width)
19016 ;; First try to find a width among
19017 ;; attributes associated to the paragraph
19018 ;; containing link.
19019 (let ((paragraph
19020 (let ((e link))
19021 (while (and (setq e (org-element-property
19022 :parent e))
19023 (not (eq (org-element-type e)
19024 'paragraph))))
19025 e)))
19026 (when paragraph
19027 (save-excursion
19028 (goto-char (org-element-property :begin paragraph))
19029 (when (save-match-data
19030 (re-search-forward
19031 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19032 (org-element-property
19033 :post-affiliated paragraph)
19035 (string-to-number (match-string 1))))))
19036 ;; Otherwise, fall-back to provided number.
19037 (car org-image-actual-width)))
19038 ((numberp org-image-actual-width)
19039 org-image-actual-width)))
19040 (old (get-char-property-and-overlay
19041 (org-element-property :begin link)
19042 'org-image-overlay)))
19043 (if (and (car-safe old) refresh)
19044 (image-refresh (overlay-get (cdr old) 'display))
19045 (let ((image (save-match-data
19046 (create-image file
19047 (and width 'imagemagick)
19049 :width width))))
19050 (when image
19051 (let* ((link
19052 ;; If inline image is the description
19053 ;; of another link, be sure to
19054 ;; consider the latter as the one to
19055 ;; apply the overlay on.
19056 (let ((parent
19057 (org-element-property :parent link)))
19058 (if (eq (org-element-type parent) 'link)
19059 parent
19060 link)))
19061 (ov (make-overlay
19062 (org-element-property :begin link)
19063 (progn
19064 (goto-char
19065 (org-element-property :end link))
19066 (skip-chars-backward " \t")
19067 (point)))))
19068 (overlay-put ov 'display image)
19069 (overlay-put ov 'face 'default)
19070 (overlay-put ov 'org-image-overlay t)
19071 (overlay-put
19072 ov 'modification-hooks
19073 (list 'org-display-inline-remove-overlay))
19074 (push ov org-inline-image-overlays)))))))))))))))
19076 (define-obsolete-function-alias
19077 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19079 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19080 "Remove inline-display overlay if a corresponding region is modified."
19081 (let ((inhibit-modification-hooks t))
19082 (when (and ov after)
19083 (delete ov org-inline-image-overlays)
19084 (delete-overlay ov))))
19086 (defun org-remove-inline-images ()
19087 "Remove inline display of images."
19088 (interactive)
19089 (mapc 'delete-overlay org-inline-image-overlays)
19090 (setq org-inline-image-overlays nil))
19092 ;;;; Key bindings
19094 ;; Outline functions from `outline-mode-prefix-map'
19095 ;; that can be remapped in Org:
19096 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19097 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19098 (define-key org-mode-map [remap outline-forward-same-level]
19099 'org-forward-heading-same-level)
19100 (define-key org-mode-map [remap outline-backward-same-level]
19101 'org-backward-heading-same-level)
19102 (define-key org-mode-map [remap show-branches]
19103 'org-kill-note-or-show-branches)
19104 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19105 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19106 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19108 ;; Outline functions from `outline-mode-prefix-map' that can not
19109 ;; be remapped in Org:
19111 ;; - the column "key binding" shows whether the Outline function is still
19112 ;; available in Org mode on the same key that it has been bound to in
19113 ;; Outline mode:
19114 ;; - "overridden": key used for a different functionality in Org mode
19115 ;; - else: key still bound to the same Outline function in Org mode
19117 ;; | Outline function | key binding | Org replacement |
19118 ;; |------------------------------------+-------------+-----------------------|
19119 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19120 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19121 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19122 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19123 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19124 ;; | `show-entry' | overridden | no replacement |
19125 ;; | `show-children' | `C-c C-i' | visibility cycling |
19126 ;; | `show-branches' | `C-c C-k' | still same function |
19127 ;; | `show-subtree' | overridden | visibility cycling |
19128 ;; | `show-all' | overridden | no replacement |
19129 ;; | `hide-subtree' | overridden | visibility cycling |
19130 ;; | `hide-body' | overridden | no replacement |
19131 ;; | `hide-entry' | overridden | visibility cycling |
19132 ;; | `hide-leaves' | overridden | no replacement |
19133 ;; | `hide-sublevels' | overridden | no replacement |
19134 ;; | `hide-other' | overridden | no replacement |
19136 ;; Make `C-c C-x' a prefix key
19137 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19139 ;; TAB key with modifiers
19140 (org-defkey org-mode-map "\C-i" 'org-cycle)
19141 (org-defkey org-mode-map [(tab)] 'org-cycle)
19142 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19143 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19144 ;; The following line is necessary under Suse GNU/Linux
19145 (unless (featurep 'xemacs)
19146 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19147 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19148 (define-key org-mode-map [backtab] 'org-shifttab)
19150 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19151 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19152 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19154 ;; Cursor keys with modifiers
19155 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19156 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19157 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19158 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19160 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19161 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19162 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19163 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19165 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19166 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19167 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19168 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19170 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19171 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19172 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19173 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19175 ;; Babel keys
19176 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19177 (mapc (lambda (pair)
19178 (define-key org-babel-map (car pair) (cdr pair)))
19179 org-babel-key-bindings)
19181 ;;; Extra keys for tty access.
19182 ;; We only set them when really needed because otherwise the
19183 ;; menus don't show the simple keys
19185 (when (or org-use-extra-keys
19186 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19187 (not window-system))
19188 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19189 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19190 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19191 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19192 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19193 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19194 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19195 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19196 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19197 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19198 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19199 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19200 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19201 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19202 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19203 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19204 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19205 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19206 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19207 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19208 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19209 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19210 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19211 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19212 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19213 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19214 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19215 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19217 ;; All the other keys
19219 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19220 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19221 (if (boundp 'narrow-map)
19222 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19223 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19224 (if (boundp 'narrow-map)
19225 (org-defkey narrow-map "b" 'org-narrow-to-block)
19226 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19227 (if (boundp 'narrow-map)
19228 (org-defkey narrow-map "e" 'org-narrow-to-element)
19229 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19230 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19231 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19232 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19233 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19234 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19235 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19236 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19237 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19238 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19239 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19240 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19241 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19242 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19243 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19244 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19245 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19246 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19247 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19248 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19249 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19250 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19251 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19252 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19253 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19254 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19255 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19256 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19257 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19258 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19259 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19260 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19261 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19262 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19263 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19264 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19265 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19266 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19267 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19268 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19269 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19270 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19271 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19272 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19273 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19274 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19275 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19276 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19277 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19278 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19279 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19280 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19281 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19282 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19283 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19284 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19285 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19286 (org-defkey org-mode-map "\C-c^" 'org-sort)
19287 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19288 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19289 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19290 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19291 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19292 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19293 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19294 (org-defkey org-mode-map "\C-m" 'org-return)
19295 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19296 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19297 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19298 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19299 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19300 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19301 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19302 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19303 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19304 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19305 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19306 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19307 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19308 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19309 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19310 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19311 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19312 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19313 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19314 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19315 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19316 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19317 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19319 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19320 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19321 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19323 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19324 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19325 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19326 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19327 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19328 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19329 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19330 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19331 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19332 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19333 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19334 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19335 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19336 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19337 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19338 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19339 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19340 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19341 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19342 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19343 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19344 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19345 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19347 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19348 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19349 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19350 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19351 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19353 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19355 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19357 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19358 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19360 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19363 (when (featurep 'xemacs)
19364 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19367 (defconst org-speed-commands-default
19369 ("Outline Navigation")
19370 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19371 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19372 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19373 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19374 ("F" . org-next-block)
19375 ("B" . org-previous-block)
19376 ("u" . (org-speed-move-safe 'outline-up-heading))
19377 ("j" . org-goto)
19378 ("g" . (org-refile t))
19379 ("Outline Visibility")
19380 ("c" . org-cycle)
19381 ("C" . org-shifttab)
19382 (" " . org-display-outline-path)
19383 ("s" . org-narrow-to-subtree)
19384 ("=" . org-columns)
19385 ("Outline Structure Editing")
19386 ("U" . org-shiftmetaup)
19387 ("D" . org-shiftmetadown)
19388 ("r" . org-metaright)
19389 ("l" . org-metaleft)
19390 ("R" . org-shiftmetaright)
19391 ("L" . org-shiftmetaleft)
19392 ("i" . (progn (forward-char 1) (call-interactively
19393 'org-insert-heading-respect-content)))
19394 ("^" . org-sort)
19395 ("w" . org-refile)
19396 ("a" . org-archive-subtree-default-with-confirmation)
19397 ("@" . org-mark-subtree)
19398 ("#" . org-toggle-comment)
19399 ("Clock Commands")
19400 ("I" . org-clock-in)
19401 ("O" . org-clock-out)
19402 ("Meta Data Editing")
19403 ("t" . org-todo)
19404 ("," . (org-priority))
19405 ("0" . (org-priority ?\ ))
19406 ("1" . (org-priority ?A))
19407 ("2" . (org-priority ?B))
19408 ("3" . (org-priority ?C))
19409 (":" . org-set-tags-command)
19410 ("e" . org-set-effort)
19411 ("E" . org-inc-effort)
19412 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19413 (org-entry-put (point) "APPT_WARNTIME" m)))
19414 ("Agenda Views etc")
19415 ("v" . org-agenda)
19416 ("/" . org-sparse-tree)
19417 ("Misc")
19418 ("o" . org-open-at-point)
19419 ("?" . org-speed-command-help)
19420 ("<" . (org-agenda-set-restriction-lock 'subtree))
19421 (">" . (org-agenda-remove-restriction-lock))
19423 "The default speed commands.")
19425 (defun org-print-speed-command (e)
19426 (if (> (length (car e)) 1)
19427 (progn
19428 (princ "\n")
19429 (princ (car e))
19430 (princ "\n")
19431 (princ (make-string (length (car e)) ?-))
19432 (princ "\n"))
19433 (princ (car e))
19434 (princ " ")
19435 (if (symbolp (cdr e))
19436 (princ (symbol-name (cdr e)))
19437 (prin1 (cdr e)))
19438 (princ "\n")))
19440 (defun org-speed-command-help ()
19441 "Show the available speed commands."
19442 (interactive)
19443 (if (not org-use-speed-commands)
19444 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19445 (with-output-to-temp-buffer "*Help*"
19446 (princ "User-defined Speed commands\n===========================\n")
19447 (mapc 'org-print-speed-command org-speed-commands-user)
19448 (princ "\n")
19449 (princ "Built-in Speed commands\n=======================\n")
19450 (mapc 'org-print-speed-command org-speed-commands-default))
19451 (with-current-buffer "*Help*"
19452 (setq truncate-lines t))))
19454 (defun org-speed-move-safe (cmd)
19455 "Execute CMD, but make sure that the cursor always ends up in a headline.
19456 If not, return to the original position and throw an error."
19457 (interactive)
19458 (let ((pos (point)))
19459 (call-interactively cmd)
19460 (unless (and (bolp) (org-at-heading-p))
19461 (goto-char pos)
19462 (error "Boundary reached while executing %s" cmd))))
19464 (defvar org-self-insert-command-undo-counter 0)
19466 (defvar org-table-auto-blank-field) ; defined in org-table.el
19467 (defvar org-speed-command nil)
19469 (define-obsolete-function-alias
19470 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19472 (defun org-speed-command-activate (keys)
19473 "Hook for activating single-letter speed commands.
19474 `org-speed-commands-default' specifies a minimal command set.
19475 Use `org-speed-commands-user' for further customization."
19476 (when (or (and (bolp) (looking-at org-outline-regexp))
19477 (and (functionp org-use-speed-commands)
19478 (funcall org-use-speed-commands)))
19479 (cdr (assoc keys (append org-speed-commands-user
19480 org-speed-commands-default)))))
19482 (define-obsolete-function-alias
19483 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19485 (defun org-babel-speed-command-activate (keys)
19486 "Hook for activating single-letter code block commands."
19487 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19488 (cdr (assoc keys org-babel-key-bindings))))
19490 (defcustom org-speed-command-hook
19491 '(org-speed-command-default-hook org-babel-speed-command-hook)
19492 "Hook for activating speed commands at strategic locations.
19493 Hook functions are called in sequence until a valid handler is
19494 found.
19496 Each hook takes a single argument, a user-pressed command key
19497 which is also a `self-insert-command' from the global map.
19499 Within the hook, examine the cursor position and the command key
19500 and return nil or a valid handler as appropriate. Handler could
19501 be one of an interactive command, a function, or a form.
19503 Set `org-use-speed-commands' to non-nil value to enable this
19504 hook. The default setting is `org-speed-command-activate'."
19505 :group 'org-structure
19506 :version "24.1"
19507 :type 'hook)
19509 (defun org-self-insert-command (N)
19510 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19511 If the cursor is in a table looking at whitespace, the whitespace is
19512 overwritten, and the table is not marked as requiring realignment."
19513 (interactive "p")
19514 (org-check-before-invisible-edit 'insert)
19515 (cond
19516 ((and org-use-speed-commands
19517 (setq org-speed-command
19518 (run-hook-with-args-until-success
19519 'org-speed-command-hook (this-command-keys))))
19520 (cond
19521 ((commandp org-speed-command)
19522 (setq this-command org-speed-command)
19523 (call-interactively org-speed-command))
19524 ((functionp org-speed-command)
19525 (funcall org-speed-command))
19526 ((and org-speed-command (listp org-speed-command))
19527 (eval org-speed-command))
19528 (t (let (org-use-speed-commands)
19529 (call-interactively 'org-self-insert-command)))))
19530 ((and
19531 (org-table-p)
19532 (progn
19533 ;; check if we blank the field, and if that triggers align
19534 (and (featurep 'org-table) org-table-auto-blank-field
19535 (member last-command
19536 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19537 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19538 ;; got extra space, this field does not determine column width
19539 (let (org-table-may-need-update) (org-table-blank-field))
19540 ;; no extra space, this field may determine column width
19541 (org-table-blank-field)))
19543 (eq N 1)
19544 (looking-at "[^|\n]* |"))
19545 (let (org-table-may-need-update)
19546 (goto-char (1- (match-end 0)))
19547 (backward-delete-char 1)
19548 (goto-char (match-beginning 0))
19549 (self-insert-command N)))
19551 (setq org-table-may-need-update t)
19552 (self-insert-command N)
19553 (org-fix-tags-on-the-fly)
19554 (if org-self-insert-cluster-for-undo
19555 (if (not (eq last-command 'org-self-insert-command))
19556 (setq org-self-insert-command-undo-counter 1)
19557 (if (>= org-self-insert-command-undo-counter 20)
19558 (setq org-self-insert-command-undo-counter 1)
19559 (and (> org-self-insert-command-undo-counter 0)
19560 buffer-undo-list (listp buffer-undo-list)
19561 (not (cadr buffer-undo-list)) ; remove nil entry
19562 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19563 (setq org-self-insert-command-undo-counter
19564 (1+ org-self-insert-command-undo-counter))))))))
19566 (defun org-check-before-invisible-edit (kind)
19567 "Check is editing if kind KIND would be dangerous with invisible text around.
19568 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19569 ;; First, try to get out of here as quickly as possible, to reduce overhead
19570 (if (and org-catch-invisible-edits
19571 (or (not (boundp 'visible-mode)) (not visible-mode))
19572 (or (get-char-property (point) 'invisible)
19573 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19574 ;; OK, we need to take a closer look
19575 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19576 (invisible-before-point (if (bobp) nil (get-char-property
19577 (1- (point)) 'invisible)))
19578 (border-and-ok-direction
19580 ;; Check if we are acting predictably before invisible text
19581 (and invisible-at-point (not invisible-before-point)
19582 (memq kind '(insert delete-backward)))
19583 ;; Check if we are acting predictably after invisible text
19584 ;; This works not well, and I have turned it off. It seems
19585 ;; better to always show and stop after invisible text.
19586 ;; (and (not invisible-at-point) invisible-before-point
19587 ;; (memq kind '(insert delete)))
19589 (when (or (memq invisible-at-point '(outline org-hide-block t))
19590 (memq invisible-before-point '(outline org-hide-block t)))
19591 (if (eq org-catch-invisible-edits 'error)
19592 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19593 (if (and org-custom-properties-overlays
19594 (y-or-n-p "Display invisible properties in this buffer? "))
19595 (org-toggle-custom-properties-visibility)
19596 ;; Make the area visible
19597 (save-excursion
19598 (if invisible-before-point
19599 (goto-char (previous-single-char-property-change
19600 (point) 'invisible)))
19601 (show-subtree))
19602 (cond
19603 ((eq org-catch-invisible-edits 'show)
19604 ;; That's it, we do the edit after showing
19605 (message
19606 "Unfolding invisible region around point before editing")
19607 (sit-for 1))
19608 ((and (eq org-catch-invisible-edits 'smart)
19609 border-and-ok-direction)
19610 (message "Unfolding invisible region around point before editing"))
19612 ;; Don't do the edit, make the user repeat it in full visibility
19613 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19615 (defun org-fix-tags-on-the-fly ()
19616 (when (and (equal (char-after (point-at-bol)) ?*)
19617 (org-at-heading-p))
19618 (org-align-tags-here org-tags-column)))
19620 (defun org-delete-backward-char (N)
19621 "Like `delete-backward-char', insert whitespace at field end in tables.
19622 When deleting backwards, in tables this function will insert whitespace in
19623 front of the next \"|\" separator, to keep the table aligned. The table will
19624 still be marked for re-alignment if the field did fill the entire column,
19625 because, in this case the deletion might narrow the column."
19626 (interactive "p")
19627 (save-match-data
19628 (org-check-before-invisible-edit 'delete-backward)
19629 (if (and (org-table-p)
19630 (eq N 1)
19631 (string-match "|" (buffer-substring (point-at-bol) (point)))
19632 (looking-at ".*?|"))
19633 (let ((pos (point))
19634 (noalign (looking-at "[^|\n\r]* |"))
19635 (c org-table-may-need-update))
19636 (backward-delete-char N)
19637 (if (not overwrite-mode)
19638 (progn
19639 (skip-chars-forward "^|")
19640 (insert " ")
19641 (goto-char (1- pos))))
19642 ;; noalign: if there were two spaces at the end, this field
19643 ;; does not determine the width of the column.
19644 (if noalign (setq org-table-may-need-update c)))
19645 (backward-delete-char N)
19646 (org-fix-tags-on-the-fly))))
19648 (defun org-delete-char (N)
19649 "Like `delete-char', but insert whitespace at field end in tables.
19650 When deleting characters, in tables this function will insert whitespace in
19651 front of the next \"|\" separator, to keep the table aligned. The table will
19652 still be marked for re-alignment if the field did fill the entire column,
19653 because, in this case the deletion might narrow the column."
19654 (interactive "p")
19655 (save-match-data
19656 (org-check-before-invisible-edit 'delete)
19657 (if (and (org-table-p)
19658 (not (bolp))
19659 (not (= (char-after) ?|))
19660 (eq N 1))
19661 (if (looking-at ".*?|")
19662 (let ((pos (point))
19663 (noalign (looking-at "[^|\n\r]* |"))
19664 (c org-table-may-need-update))
19665 (replace-match
19666 (concat (substring (match-string 0) 1 -1) " |") nil t)
19667 (goto-char pos)
19668 ;; noalign: if there were two spaces at the end, this field
19669 ;; does not determine the width of the column.
19670 (if noalign (setq org-table-may-need-update c)))
19671 (delete-char N))
19672 (delete-char N)
19673 (org-fix-tags-on-the-fly))))
19675 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19676 (put 'org-self-insert-command 'delete-selection
19677 (lambda ()
19678 (not (run-hook-with-args-until-success
19679 'self-insert-uses-region-functions))))
19680 (put 'orgtbl-self-insert-command 'delete-selection
19681 (lambda ()
19682 (not (run-hook-with-args-until-success
19683 'self-insert-uses-region-functions))))
19684 (put 'org-delete-char 'delete-selection 'supersede)
19685 (put 'org-delete-backward-char 'delete-selection 'supersede)
19686 (put 'org-yank 'delete-selection 'yank)
19688 ;; Make `flyspell-mode' delay after some commands
19689 (put 'org-self-insert-command 'flyspell-delayed t)
19690 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19691 (put 'org-delete-char 'flyspell-delayed t)
19692 (put 'org-delete-backward-char 'flyspell-delayed t)
19694 ;; Make pabbrev-mode expand after org-mode commands
19695 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19696 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19698 (defun org-remap (map &rest commands)
19699 "In MAP, remap the functions given in COMMANDS.
19700 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19701 (let (new old)
19702 (while commands
19703 (setq old (pop commands) new (pop commands))
19704 (if (fboundp 'command-remapping)
19705 (org-defkey map (vector 'remap old) new)
19706 (substitute-key-definition old new map global-map)))))
19708 (defun org-transpose-words ()
19709 "Transpose words for Org.
19710 This uses the `org-mode-transpose-word-syntax-table' syntax
19711 table, which interprets characters in `org-emphasis-alist' as
19712 word constituents."
19713 (interactive)
19714 (with-syntax-table org-mode-transpose-word-syntax-table
19715 (call-interactively 'transpose-words)))
19716 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19718 (when (eq org-enable-table-editor 'optimized)
19719 ;; If the user wants maximum table support, we need to hijack
19720 ;; some standard editing functions
19721 (org-remap org-mode-map
19722 'self-insert-command 'org-self-insert-command
19723 'delete-char 'org-delete-char
19724 'delete-backward-char 'org-delete-backward-char)
19725 (org-defkey org-mode-map "|" 'org-force-self-insert))
19727 (defvar org-ctrl-c-ctrl-c-hook nil
19728 "Hook for functions attaching themselves to `C-c C-c'.
19730 This can be used to add additional functionality to the C-c C-c
19731 key which executes context-dependent commands. This hook is run
19732 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19733 run after the last test.
19735 Each function will be called with no arguments. The function
19736 must check if the context is appropriate for it to act. If yes,
19737 it should do its thing and then return a non-nil value. If the
19738 context is wrong, just do nothing and return nil.")
19740 (defvar org-ctrl-c-ctrl-c-final-hook nil
19741 "Hook for functions attaching themselves to `C-c C-c'.
19743 This can be used to add additional functionality to the C-c C-c
19744 key which executes context-dependent commands. This hook is run
19745 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19746 before the first test.
19748 Each function will be called with no arguments. The function
19749 must check if the context is appropriate for it to act. If yes,
19750 it should do its thing and then return a non-nil value. If the
19751 context is wrong, just do nothing and return nil.")
19753 (defvar org-tab-first-hook nil
19754 "Hook for functions to attach themselves to TAB.
19755 See `org-ctrl-c-ctrl-c-hook' for more information.
19756 This hook runs as the first action when TAB is pressed, even before
19757 `org-cycle' messes around with the `outline-regexp' to cater for
19758 inline tasks and plain list item folding.
19759 If any function in this hook returns t, any other actions that
19760 would have been caused by TAB (such as table field motion or visibility
19761 cycling) will not occur.")
19763 (defvar org-tab-after-check-for-table-hook nil
19764 "Hook for functions to attach themselves to TAB.
19765 See `org-ctrl-c-ctrl-c-hook' for more information.
19766 This hook runs after it has been established that the cursor is not in a
19767 table, but before checking if the cursor is in a headline or if global cycling
19768 should be done.
19769 If any function in this hook returns t, not other actions like visibility
19770 cycling will be done.")
19772 (defvar org-tab-after-check-for-cycling-hook nil
19773 "Hook for functions to attach themselves to TAB.
19774 See `org-ctrl-c-ctrl-c-hook' for more information.
19775 This hook runs after it has been established that not table field motion and
19776 not visibility should be done because of current context. This is probably
19777 the place where a package like yasnippets can hook in.")
19779 (defvar org-tab-before-tab-emulation-hook nil
19780 "Hook for functions to attach themselves to TAB.
19781 See `org-ctrl-c-ctrl-c-hook' for more information.
19782 This hook runs after every other options for TAB have been exhausted, but
19783 before indentation and \t insertion takes place.")
19785 (defvar org-metaleft-hook nil
19786 "Hook for functions attaching themselves to `M-left'.
19787 See `org-ctrl-c-ctrl-c-hook' for more information.")
19788 (defvar org-metaright-hook nil
19789 "Hook for functions attaching themselves to `M-right'.
19790 See `org-ctrl-c-ctrl-c-hook' for more information.")
19791 (defvar org-metaup-hook nil
19792 "Hook for functions attaching themselves to `M-up'.
19793 See `org-ctrl-c-ctrl-c-hook' for more information.")
19794 (defvar org-metadown-hook nil
19795 "Hook for functions attaching themselves to `M-down'.
19796 See `org-ctrl-c-ctrl-c-hook' for more information.")
19797 (defvar org-shiftmetaleft-hook nil
19798 "Hook for functions attaching themselves to `M-S-left'.
19799 See `org-ctrl-c-ctrl-c-hook' for more information.")
19800 (defvar org-shiftmetaright-hook nil
19801 "Hook for functions attaching themselves to `M-S-right'.
19802 See `org-ctrl-c-ctrl-c-hook' for more information.")
19803 (defvar org-shiftmetaup-hook nil
19804 "Hook for functions attaching themselves to `M-S-up'.
19805 See `org-ctrl-c-ctrl-c-hook' for more information.")
19806 (defvar org-shiftmetadown-hook nil
19807 "Hook for functions attaching themselves to `M-S-down'.
19808 See `org-ctrl-c-ctrl-c-hook' for more information.")
19809 (defvar org-metareturn-hook nil
19810 "Hook for functions attaching themselves to `M-RET'.
19811 See `org-ctrl-c-ctrl-c-hook' for more information.")
19812 (defvar org-shiftup-hook nil
19813 "Hook for functions attaching themselves to `S-up'.
19814 See `org-ctrl-c-ctrl-c-hook' for more information.")
19815 (defvar org-shiftup-final-hook nil
19816 "Hook for functions attaching themselves to `S-up'.
19817 This one runs after all other options except shift-select have been excluded.
19818 See `org-ctrl-c-ctrl-c-hook' for more information.")
19819 (defvar org-shiftdown-hook nil
19820 "Hook for functions attaching themselves to `S-down'.
19821 See `org-ctrl-c-ctrl-c-hook' for more information.")
19822 (defvar org-shiftdown-final-hook nil
19823 "Hook for functions attaching themselves to `S-down'.
19824 This one runs after all other options except shift-select have been excluded.
19825 See `org-ctrl-c-ctrl-c-hook' for more information.")
19826 (defvar org-shiftleft-hook nil
19827 "Hook for functions attaching themselves to `S-left'.
19828 See `org-ctrl-c-ctrl-c-hook' for more information.")
19829 (defvar org-shiftleft-final-hook nil
19830 "Hook for functions attaching themselves to `S-left'.
19831 This one runs after all other options except shift-select have been excluded.
19832 See `org-ctrl-c-ctrl-c-hook' for more information.")
19833 (defvar org-shiftright-hook nil
19834 "Hook for functions attaching themselves to `S-right'.
19835 See `org-ctrl-c-ctrl-c-hook' for more information.")
19836 (defvar org-shiftright-final-hook nil
19837 "Hook for functions attaching themselves to `S-right'.
19838 This one runs after all other options except shift-select have been excluded.
19839 See `org-ctrl-c-ctrl-c-hook' for more information.")
19841 (defun org-modifier-cursor-error ()
19842 "Throw an error, a modified cursor command was applied in wrong context."
19843 (user-error "This command is active in special context like tables, headlines or items"))
19845 (defun org-shiftselect-error ()
19846 "Throw an error because Shift-Cursor command was applied in wrong context."
19847 (if (and (boundp 'shift-select-mode) shift-select-mode)
19848 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19849 (user-error "This command works only in special context like headlines or timestamps")))
19851 (defun org-call-for-shift-select (cmd)
19852 (let ((this-command-keys-shift-translated t))
19853 (call-interactively cmd)))
19855 (defun org-shifttab (&optional arg)
19856 "Global visibility cycling or move to previous table field.
19857 Call `org-table-previous-field' within a table.
19858 When ARG is nil, cycle globally through visibility states.
19859 When ARG is a numeric prefix, show contents of this level."
19860 (interactive "P")
19861 (cond
19862 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19863 ((integerp arg)
19864 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19865 (message "Content view to level: %d" arg)
19866 (org-content (prefix-numeric-value arg2))
19867 (org-cycle-show-empty-lines t)
19868 (setq org-cycle-global-status 'overview)))
19869 (t (call-interactively 'org-global-cycle))))
19871 (defun org-shiftmetaleft ()
19872 "Promote subtree or delete table column.
19873 Calls `org-promote-subtree', `org-outdent-item-tree', or
19874 `org-table-delete-column', depending on context. See the
19875 individual commands for more information."
19876 (interactive)
19877 (cond
19878 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19879 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19880 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19881 ((if (not (org-region-active-p)) (org-at-item-p)
19882 (save-excursion (goto-char (region-beginning))
19883 (org-at-item-p)))
19884 (call-interactively 'org-outdent-item-tree))
19885 (t (org-modifier-cursor-error))))
19887 (defun org-shiftmetaright ()
19888 "Demote subtree or insert table column.
19889 Calls `org-demote-subtree', `org-indent-item-tree', or
19890 `org-table-insert-column', depending on context. See the
19891 individual commands for more information."
19892 (interactive)
19893 (cond
19894 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19895 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19896 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19897 ((if (not (org-region-active-p)) (org-at-item-p)
19898 (save-excursion (goto-char (region-beginning))
19899 (org-at-item-p)))
19900 (call-interactively 'org-indent-item-tree))
19901 (t (org-modifier-cursor-error))))
19903 (defun org-shiftmetaup (&optional arg)
19904 "Move subtree up or kill table row.
19905 Calls `org-move-subtree-up' or `org-table-kill-row' or
19906 `org-move-item-up' or `org-timestamp-up', depending on context.
19907 See the individual commands for more information."
19908 (interactive "P")
19909 (cond
19910 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19911 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19912 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19913 ((org-at-item-p) (call-interactively 'org-move-item-up))
19914 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19915 (call-interactively 'org-timestamp-up)))
19916 (t (call-interactively 'org-drag-line-backward))))
19918 (defun org-shiftmetadown (&optional arg)
19919 "Move subtree down or insert table row.
19920 Calls `org-move-subtree-down' or `org-table-insert-row' or
19921 `org-move-item-down' 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-shiftmetadown-hook))
19926 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19927 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19928 ((org-at-item-p) (call-interactively 'org-move-item-down))
19929 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19930 (call-interactively 'org-timestamp-down)))
19931 (t (call-interactively 'org-drag-line-forward))))
19933 (defsubst org-hidden-tree-error ()
19934 (user-error
19935 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19937 (defun org-metaleft (&optional arg)
19938 "Promote heading or move table column to left.
19939 Calls `org-do-promote' or `org-table-move-column', depending on context.
19940 With no specific context, calls the Emacs default `backward-word'.
19941 See the individual commands for more information."
19942 (interactive "P")
19943 (cond
19944 ((run-hook-with-args-until-success 'org-metaleft-hook))
19945 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19946 ((org-with-limited-levels
19947 (or (org-at-heading-p)
19948 (and (org-region-active-p)
19949 (save-excursion
19950 (goto-char (region-beginning))
19951 (org-at-heading-p)))))
19952 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19953 (call-interactively 'org-do-promote))
19954 ;; At an inline task.
19955 ((org-at-heading-p)
19956 (call-interactively 'org-inlinetask-promote))
19957 ((or (org-at-item-p)
19958 (and (org-region-active-p)
19959 (save-excursion
19960 (goto-char (region-beginning))
19961 (org-at-item-p))))
19962 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19963 (call-interactively 'org-outdent-item))
19964 (t (call-interactively 'backward-word))))
19966 (defun org-metaright (&optional arg)
19967 "Demote a subtree, a list item or move table column to right.
19968 In front of a drawer or a block keyword, indent it correctly.
19969 With no specific context, calls the Emacs default `forward-word'.
19970 See the individual commands for more information."
19971 (interactive "P")
19972 (cond
19973 ((run-hook-with-args-until-success 'org-metaright-hook))
19974 ((org-at-table-p) (call-interactively 'org-table-move-column))
19975 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19976 ((org-at-block-p) (call-interactively 'org-indent-block))
19977 ((org-with-limited-levels
19978 (or (org-at-heading-p)
19979 (and (org-region-active-p)
19980 (save-excursion
19981 (goto-char (region-beginning))
19982 (org-at-heading-p)))))
19983 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19984 (call-interactively 'org-do-demote))
19985 ;; At an inline task.
19986 ((org-at-heading-p)
19987 (call-interactively 'org-inlinetask-demote))
19988 ((or (org-at-item-p)
19989 (and (org-region-active-p)
19990 (save-excursion
19991 (goto-char (region-beginning))
19992 (org-at-item-p))))
19993 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19994 (call-interactively 'org-indent-item))
19995 (t (call-interactively 'forward-word))))
19997 (defun org-check-for-hidden (what)
19998 "Check if there are hidden headlines/items in the current visual line.
19999 WHAT can be either `headlines' or `items'. If the current line is
20000 an outline or item heading and it has a folded subtree below it,
20001 this function returns t, nil otherwise."
20002 (let ((re (cond
20003 ((eq what 'headlines) org-outline-regexp-bol)
20004 ((eq what 'items) (org-item-beginning-re))
20005 (t (error "This should not happen"))))
20006 beg end)
20007 (save-excursion
20008 (catch 'exit
20009 (unless (org-region-active-p)
20010 (setq beg (point-at-bol))
20011 (beginning-of-line 2)
20012 (while (and (not (eobp)) ;; this is like `next-line'
20013 (get-char-property (1- (point)) 'invisible))
20014 (beginning-of-line 2))
20015 (setq end (point))
20016 (goto-char beg)
20017 (goto-char (point-at-eol))
20018 (setq end (max end (point)))
20019 (while (re-search-forward re end t)
20020 (if (get-char-property (match-beginning 0) 'invisible)
20021 (throw 'exit t))))
20022 nil))))
20024 (defun org-metaup (&optional arg)
20025 "Move subtree up or move table row up.
20026 Calls `org-move-subtree-up' or `org-table-move-row' or
20027 `org-move-item-up', depending on context. See the individual commands
20028 for more information."
20029 (interactive "P")
20030 (cond
20031 ((run-hook-with-args-until-success 'org-metaup-hook))
20032 ((org-region-active-p)
20033 (let* ((a (min (region-beginning) (region-end)))
20034 (b (1- (max (region-beginning) (region-end))))
20035 (c (save-excursion (goto-char a)
20036 (move-beginning-of-line 0)))
20037 (d (save-excursion (goto-char a)
20038 (move-end-of-line 0) (point))))
20039 (transpose-regions a b c d)
20040 (goto-char c)))
20041 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20042 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20043 ((org-at-item-p) (call-interactively 'org-move-item-up))
20044 (t (org-drag-element-backward))))
20046 (defun org-metadown (&optional arg)
20047 "Move subtree down or move table row down.
20048 Calls `org-move-subtree-down' or `org-table-move-row' or
20049 `org-move-item-down', depending on context. See the individual
20050 commands for more information."
20051 (interactive "P")
20052 (cond
20053 ((run-hook-with-args-until-success 'org-metadown-hook))
20054 ((org-region-active-p)
20055 (let* ((a (min (region-beginning) (region-end)))
20056 (b (max (region-beginning) (region-end)))
20057 (c (save-excursion (goto-char b)
20058 (move-beginning-of-line 1)))
20059 (d (save-excursion (goto-char b)
20060 (move-end-of-line 1) (1+ (point)))))
20061 (transpose-regions a b c d)
20062 (goto-char d)))
20063 ((org-at-table-p) (call-interactively 'org-table-move-row))
20064 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20065 ((org-at-item-p) (call-interactively 'org-move-item-down))
20066 (t (org-drag-element-forward))))
20068 (defun org-shiftup (&optional arg)
20069 "Increase item in timestamp or increase priority of current headline.
20070 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20071 depending on context. See the individual commands for more information."
20072 (interactive "P")
20073 (cond
20074 ((run-hook-with-args-until-success 'org-shiftup-hook))
20075 ((and org-support-shift-select (org-region-active-p))
20076 (org-call-for-shift-select 'previous-line))
20077 ((org-at-timestamp-p t)
20078 (call-interactively (if org-edit-timestamp-down-means-later
20079 'org-timestamp-down 'org-timestamp-up)))
20080 ((and (not (eq org-support-shift-select 'always))
20081 org-enable-priority-commands
20082 (org-at-heading-p))
20083 (call-interactively 'org-priority-up))
20084 ((and (not org-support-shift-select) (org-at-item-p))
20085 (call-interactively 'org-previous-item))
20086 ((org-clocktable-try-shift 'up arg))
20087 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20088 (org-support-shift-select
20089 (org-call-for-shift-select 'previous-line))
20090 (t (org-shiftselect-error))))
20092 (defun org-shiftdown (&optional arg)
20093 "Decrease item in timestamp or decrease priority of current headline.
20094 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20095 depending on context. See the individual commands for more information."
20096 (interactive "P")
20097 (cond
20098 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20099 ((and org-support-shift-select (org-region-active-p))
20100 (org-call-for-shift-select 'next-line))
20101 ((org-at-timestamp-p t)
20102 (call-interactively (if org-edit-timestamp-down-means-later
20103 'org-timestamp-up 'org-timestamp-down)))
20104 ((and (not (eq org-support-shift-select 'always))
20105 org-enable-priority-commands
20106 (org-at-heading-p))
20107 (call-interactively 'org-priority-down))
20108 ((and (not org-support-shift-select) (org-at-item-p))
20109 (call-interactively 'org-next-item))
20110 ((org-clocktable-try-shift 'down arg))
20111 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20112 (org-support-shift-select
20113 (org-call-for-shift-select 'next-line))
20114 (t (org-shiftselect-error))))
20116 (defun org-shiftright (&optional arg)
20117 "Cycle the thing at point or in the current line, depending on context.
20118 Depending on context, this does one of the following:
20120 - switch a timestamp at point one day into the future
20121 - on a headline, switch to the next TODO keyword.
20122 - on an item, switch entire list to the next bullet type
20123 - on a property line, switch to the next allowed value
20124 - on a clocktable definition line, move time block into the future"
20125 (interactive "P")
20126 (cond
20127 ((run-hook-with-args-until-success 'org-shiftright-hook))
20128 ((and org-support-shift-select (org-region-active-p))
20129 (org-call-for-shift-select 'forward-char))
20130 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20131 ((and (not (eq org-support-shift-select 'always))
20132 (org-at-heading-p))
20133 (let ((org-inhibit-logging
20134 (not org-treat-S-cursor-todo-selection-as-state-change))
20135 (org-inhibit-blocking
20136 (not org-treat-S-cursor-todo-selection-as-state-change)))
20137 (org-call-with-arg 'org-todo 'right)))
20138 ((or (and org-support-shift-select
20139 (not (eq org-support-shift-select 'always))
20140 (org-at-item-bullet-p))
20141 (and (not org-support-shift-select) (org-at-item-p)))
20142 (org-call-with-arg 'org-cycle-list-bullet nil))
20143 ((and (not (eq org-support-shift-select 'always))
20144 (org-at-property-p))
20145 (call-interactively 'org-property-next-allowed-value))
20146 ((org-clocktable-try-shift 'right arg))
20147 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20148 (org-support-shift-select
20149 (org-call-for-shift-select 'forward-char))
20150 (t (org-shiftselect-error))))
20152 (defun org-shiftleft (&optional arg)
20153 "Cycle the thing at point or in the current line, depending on context.
20154 Depending on context, this does one of the following:
20156 - switch a timestamp at point one day into the past
20157 - on a headline, switch to the previous TODO keyword.
20158 - on an item, switch entire list to the previous bullet type
20159 - on a property line, switch to the previous allowed value
20160 - on a clocktable definition line, move time block into the past"
20161 (interactive "P")
20162 (cond
20163 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20164 ((and org-support-shift-select (org-region-active-p))
20165 (org-call-for-shift-select 'backward-char))
20166 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20167 ((and (not (eq org-support-shift-select 'always))
20168 (org-at-heading-p))
20169 (let ((org-inhibit-logging
20170 (not org-treat-S-cursor-todo-selection-as-state-change))
20171 (org-inhibit-blocking
20172 (not org-treat-S-cursor-todo-selection-as-state-change)))
20173 (org-call-with-arg 'org-todo 'left)))
20174 ((or (and org-support-shift-select
20175 (not (eq org-support-shift-select 'always))
20176 (org-at-item-bullet-p))
20177 (and (not org-support-shift-select) (org-at-item-p)))
20178 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20179 ((and (not (eq org-support-shift-select 'always))
20180 (org-at-property-p))
20181 (call-interactively 'org-property-previous-allowed-value))
20182 ((org-clocktable-try-shift 'left arg))
20183 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20184 (org-support-shift-select
20185 (org-call-for-shift-select 'backward-char))
20186 (t (org-shiftselect-error))))
20188 (defun org-shiftcontrolright ()
20189 "Switch to next TODO set."
20190 (interactive)
20191 (cond
20192 ((and org-support-shift-select (org-region-active-p))
20193 (org-call-for-shift-select 'forward-word))
20194 ((and (not (eq org-support-shift-select 'always))
20195 (org-at-heading-p))
20196 (org-call-with-arg 'org-todo 'nextset))
20197 (org-support-shift-select
20198 (org-call-for-shift-select 'forward-word))
20199 (t (org-shiftselect-error))))
20201 (defun org-shiftcontrolleft ()
20202 "Switch to previous TODO set."
20203 (interactive)
20204 (cond
20205 ((and org-support-shift-select (org-region-active-p))
20206 (org-call-for-shift-select 'backward-word))
20207 ((and (not (eq org-support-shift-select 'always))
20208 (org-at-heading-p))
20209 (org-call-with-arg 'org-todo 'previousset))
20210 (org-support-shift-select
20211 (org-call-for-shift-select 'backward-word))
20212 (t (org-shiftselect-error))))
20214 (defun org-shiftcontrolup (&optional n)
20215 "Change timestamps synchronously up in CLOCK log lines.
20216 Optional argument N tells to change by that many units."
20217 (interactive "P")
20218 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20219 (let (org-support-shift-select)
20220 (org-clock-timestamps-up n))
20221 (user-error "Not at a clock log")))
20223 (defun org-shiftcontroldown (&optional n)
20224 "Change timestamps synchronously down in CLOCK log lines.
20225 Optional argument N tells to change by that many units."
20226 (interactive "P")
20227 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20228 (let (org-support-shift-select)
20229 (org-clock-timestamps-down n))
20230 (user-error "Not at a clock log")))
20232 (defun org-ctrl-c-ret ()
20233 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20234 (interactive)
20235 (cond
20236 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20237 (t (call-interactively 'org-insert-heading))))
20239 (defun org-find-visible ()
20240 (let ((s (point)))
20241 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20242 (get-char-property s 'invisible)))
20244 (defun org-find-invisible ()
20245 (let ((s (point)))
20246 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20247 (not (get-char-property s 'invisible))))
20250 (defun org-copy-visible (beg end)
20251 "Copy the visible parts of the region."
20252 (interactive "r")
20253 (let (snippets s)
20254 (save-excursion
20255 (save-restriction
20256 (narrow-to-region beg end)
20257 (setq s (goto-char (point-min)))
20258 (while (not (= (point) (point-max)))
20259 (goto-char (org-find-invisible))
20260 (push (buffer-substring s (point)) snippets)
20261 (setq s (goto-char (org-find-visible))))))
20262 (kill-new (apply 'concat (nreverse snippets)))))
20264 (defun org-copy-special ()
20265 "Copy region in table or copy current subtree.
20266 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20267 See the individual commands for more information."
20268 (interactive)
20269 (call-interactively
20270 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20272 (defun org-cut-special ()
20273 "Cut region in table or cut current subtree.
20274 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20275 See the individual commands for more information."
20276 (interactive)
20277 (call-interactively
20278 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20280 (defun org-paste-special (arg)
20281 "Paste rectangular region into table, or past subtree relative to level.
20282 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20283 See the individual commands for more information."
20284 (interactive "P")
20285 (if (org-at-table-p)
20286 (org-table-paste-rectangle)
20287 (org-paste-subtree arg)))
20289 (defsubst org-in-fixed-width-region-p ()
20290 "Is point in a fixed-width region?"
20291 (save-match-data
20292 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20294 (defun org-edit-special (&optional arg)
20295 "Call a special editor for the element at point.
20296 When at a table, call the formula editor with `org-table-edit-formulas'.
20297 When in a source code block, call `org-edit-src-code'.
20298 When in a fixed-width region, call `org-edit-fixed-width-region'.
20299 When at an #+INCLUDE keyword, visit the included file.
20300 On a link, call `ffap' to visit the link at point.
20301 Otherwise, return a user error."
20302 (interactive "P")
20303 (let ((element (org-element-at-point)))
20304 (assert (not buffer-read-only) nil
20305 "Buffer is read-only: %s" (buffer-name))
20306 (case (org-element-type element)
20307 (src-block
20308 (if (not arg) (org-edit-src-code)
20309 (let* ((info (org-babel-get-src-block-info))
20310 (lang (nth 0 info))
20311 (params (nth 2 info))
20312 (session (cdr (assq :session params))))
20313 (if (not session) (org-edit-src-code)
20314 ;; At a src-block with a session and function called with
20315 ;; an ARG: switch to the buffer related to the inferior
20316 ;; process.
20317 (switch-to-buffer
20318 (funcall (intern (concat "org-babel-prep-session:" lang))
20319 session params))))))
20320 (keyword
20321 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20322 (find-file-other-window
20323 (org-remove-double-quotes
20324 (car (org-split-string (org-element-property :value element)))))
20325 (user-error "No special environment to edit here")))
20326 (table
20327 (if (eq (org-element-property :type element) 'table.el)
20328 (org-edit-src-code)
20329 (call-interactively 'org-table-edit-formulas)))
20330 ;; Only Org tables contain `table-row' type elements.
20331 (table-row (call-interactively 'org-table-edit-formulas))
20332 ((example-block export-block) (org-edit-src-code))
20333 (fixed-width (org-edit-fixed-width-region))
20334 (otherwise
20335 ;; No notable element at point. Though, we may be at a link,
20336 ;; which is an object. Thus, scan deeper.
20337 (if (eq (org-element-type (org-element-context element)) 'link)
20338 (call-interactively 'ffap)
20339 (user-error "No special environment to edit here"))))))
20341 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20342 (defun org-ctrl-c-ctrl-c (&optional arg)
20343 "Set tags in headline, or update according to changed information at point.
20345 This command does many different things, depending on context:
20347 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20348 this is what we do.
20350 - If the cursor is on a statistics cookie, update it.
20352 - If the cursor is in a headline, prompt for tags and insert them
20353 into the current line, aligned to `org-tags-column'. When called
20354 with prefix arg, realign all tags in the current buffer.
20356 - If the cursor is in one of the special #+KEYWORD lines, this
20357 triggers scanning the buffer for these lines and updating the
20358 information.
20360 - If the cursor is inside a table, realign the table. This command
20361 works even if the automatic table editor has been turned off.
20363 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20364 the entire table.
20366 - If the cursor is at a footnote reference or definition, jump to
20367 the corresponding definition or references, respectively.
20369 - If the cursor is a the beginning of a dynamic block, update it.
20371 - If the current buffer is a capture buffer, close note and file it.
20373 - If the cursor is on a <<<target>>>, update radio targets and
20374 corresponding links in this buffer.
20376 - If the cursor is on a numbered item in a plain list, renumber the
20377 ordered list.
20379 - If the cursor is on a checkbox, toggle it.
20381 - If the cursor is on a code block, evaluate it. The variable
20382 `org-confirm-babel-evaluate' can be used to control prompting
20383 before code block evaluation, by default every code block
20384 evaluation requires confirmation. Code block evaluation can be
20385 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20386 (interactive "P")
20387 (cond
20388 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20389 org-occur-highlights
20390 org-latex-fragment-image-overlays)
20391 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20392 (org-remove-occur-highlights)
20393 (org-remove-latex-fragment-image-overlays)
20394 (message "Temporary highlights/overlays removed from current buffer"))
20395 ((and (local-variable-p 'org-finish-function (current-buffer))
20396 (fboundp org-finish-function))
20397 (funcall org-finish-function))
20398 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20400 (let* ((context (org-element-context)) (type (org-element-type context)))
20401 ;; Test if point is within a blank line.
20402 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20403 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20404 (user-error "C-c C-c can do nothing useful at this location"))
20405 (case type
20406 ;; When at a link, act according to the parent instead.
20407 (link (setq context (org-element-property :parent context))
20408 (setq type (org-element-type context)))
20409 ;; Unsupported object types: refer to the first supported
20410 ;; element or object containing it.
20411 ((bold code entity export-snippet inline-babel-call inline-src-block
20412 italic latex-fragment line-break macro strike-through subscript
20413 superscript underline verbatim)
20414 (while (and (setq context (org-element-property :parent context))
20415 (not (memq (setq type (org-element-type context))
20416 '(radio-target paragraph verse-block
20417 table-cell)))))))
20418 ;; For convenience: at the first line of a paragraph on the
20419 ;; same line as an item, apply function on that item instead.
20420 (when (eq type 'paragraph)
20421 (let ((parent (org-element-property :parent context)))
20422 (when (and (eq (org-element-type parent) 'item)
20423 (= (point-at-bol) (org-element-property :begin parent)))
20424 (setq context parent type 'item))))
20425 ;; Act according to type of element or object at point.
20426 (case type
20427 (clock (org-clock-update-time-maybe))
20428 (dynamic-block
20429 (save-excursion
20430 (goto-char (org-element-property :post-affiliated context))
20431 (org-update-dblock)))
20432 (footnote-definition
20433 (goto-char (org-element-property :post-affiliated context))
20434 (call-interactively 'org-footnote-action))
20435 (footnote-reference (call-interactively 'org-footnote-action))
20436 ((headline inlinetask)
20437 (save-excursion (goto-char (org-element-property :begin context))
20438 (call-interactively 'org-set-tags)))
20439 (item
20440 ;; At an item: a double C-u set checkbox to "[-]"
20441 ;; unconditionally, whereas a single one will toggle its
20442 ;; presence. Without an universal argument, if the item
20443 ;; has a checkbox, toggle it. Otherwise repair the list.
20444 (let* ((box (org-element-property :checkbox context))
20445 (struct (org-element-property :structure context))
20446 (old-struct (copy-tree struct))
20447 (parents (org-list-parents-alist struct))
20448 (prevs (org-list-prevs-alist struct))
20449 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20450 (org-list-set-checkbox
20451 (org-element-property :begin context) struct
20452 (cond ((equal arg '(16)) "[-]")
20453 ((and (not box) (equal arg '(4))) "[ ]")
20454 ((or (not box) (equal arg '(4))) nil)
20455 ((eq box 'on) "[ ]")
20456 (t "[X]")))
20457 ;; Mimic `org-list-write-struct' but with grabbing
20458 ;; a return value from `org-list-struct-fix-box'.
20459 (org-list-struct-fix-ind struct parents 2)
20460 (org-list-struct-fix-item-end struct)
20461 (org-list-struct-fix-bul struct prevs)
20462 (org-list-struct-fix-ind struct parents)
20463 (let ((block-item
20464 (org-list-struct-fix-box struct parents prevs orderedp)))
20465 (if (and box (equal struct old-struct))
20466 (if (equal arg '(16))
20467 (message "Checkboxes already reset")
20468 (user-error "Cannot toggle this checkbox: %s"
20469 (if (eq box 'on)
20470 "all subitems checked"
20471 "unchecked subitems")))
20472 (org-list-struct-apply-struct struct old-struct)
20473 (org-update-checkbox-count-maybe))
20474 (when block-item
20475 (message "Checkboxes were removed due to empty box at line %d"
20476 (org-current-line block-item))))))
20477 (keyword
20478 (let ((org-inhibit-startup-visibility-stuff t)
20479 (org-startup-align-all-tables nil))
20480 (when (boundp 'org-table-coordinate-overlays)
20481 (mapc 'delete-overlay org-table-coordinate-overlays)
20482 (setq org-table-coordinate-overlays nil))
20483 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20484 (message "Local setup has been refreshed"))
20485 (plain-list
20486 ;; At a plain list, with a double C-u argument, set
20487 ;; checkboxes of each item to "[-]", whereas a single one
20488 ;; will toggle their presence according to the state of the
20489 ;; first item in the list. Without an argument, repair the
20490 ;; list.
20491 (let* ((begin (org-element-property :contents-begin context))
20492 (beginm (move-marker (make-marker) begin))
20493 (struct (org-element-property :structure context))
20494 (old-struct (copy-tree struct))
20495 (first-box (save-excursion
20496 (goto-char begin)
20497 (looking-at org-list-full-item-re)
20498 (match-string-no-properties 3)))
20499 (new-box (cond ((equal arg '(16)) "[-]")
20500 ((equal arg '(4)) (unless first-box "[ ]"))
20501 ((equal first-box "[X]") "[ ]")
20502 (t "[X]"))))
20503 (cond
20504 (arg
20505 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20506 (org-list-get-all-items
20507 begin struct (org-list-prevs-alist struct))))
20508 ((and first-box (eq (point) begin))
20509 ;; For convenience, when point is at bol on the first
20510 ;; item of the list and no argument is provided, simply
20511 ;; toggle checkbox of that item, if any.
20512 (org-list-set-checkbox begin struct new-box)))
20513 (org-list-write-struct
20514 struct (org-list-parents-alist struct) old-struct)
20515 (org-update-checkbox-count-maybe)
20516 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20517 ((property-drawer node-property)
20518 (call-interactively 'org-property-action))
20519 ((radio-target target)
20520 (call-interactively 'org-update-radio-target-regexp))
20521 (statistics-cookie
20522 (call-interactively 'org-update-statistics-cookies))
20523 ((table table-cell table-row)
20524 ;; At a table, recalculate every field and align it. Also
20525 ;; send the table if necessary. If the table has
20526 ;; a `table.el' type, just give up. At a table row or
20527 ;; cell, maybe recalculate line but always align table.
20528 (if (eq (org-element-property :type context) 'table.el)
20529 (message "Use C-c ' to edit table.el tables")
20530 (let ((org-enable-table-editor t))
20531 (if (or (eq type 'table)
20532 ;; Check if point is at a TBLFM line.
20533 (and (eq type 'table-row)
20534 (= (point) (org-element-property :end context))))
20535 (save-excursion
20536 (if (org-at-TBLFM-p)
20537 (progn (require 'org-table)
20538 (org-table-calc-current-TBLFM))
20539 (goto-char (org-element-property :contents-begin context))
20540 (org-call-with-arg 'org-table-recalculate (or arg t))
20541 (orgtbl-send-table 'maybe)))
20542 (org-table-maybe-eval-formula)
20543 (cond (arg (call-interactively 'org-table-recalculate))
20544 ((org-table-maybe-recalculate-line))
20545 (t (org-table-align)))))))
20546 (timestamp (org-timestamp-change 0 'day))
20547 (otherwise
20548 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20549 (user-error
20550 "C-c C-c can do nothing useful at this location")))))))))
20552 (defun org-mode-restart ()
20553 (interactive)
20554 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20555 (funcall major-mode)
20556 (hack-local-variables)
20557 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20558 (org-indent-mode -1)))
20559 (message "%s restarted" major-mode))
20561 (defun org-kill-note-or-show-branches ()
20562 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20563 (interactive)
20564 (if (not org-finish-function)
20565 (progn
20566 (hide-subtree)
20567 (call-interactively 'show-branches))
20568 (let ((org-note-abort t))
20569 (funcall org-finish-function))))
20571 (defun org-open-line (n)
20572 "Insert a new row in tables, call `open-line' elsewhere.
20573 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20574 (interactive "*p")
20575 (cond
20576 ((not org-special-ctrl-o)
20577 (open-line n))
20578 ((org-at-table-p)
20579 (org-table-insert-row))
20581 (open-line n))))
20583 (defun org-return (&optional indent)
20584 "Goto next table row or insert a newline.
20585 Calls `org-table-next-row' or `newline', depending on context.
20586 See the individual commands for more information."
20587 (interactive)
20588 (let (org-ts-what)
20589 (cond
20590 ((or (bobp) (org-in-src-block-p))
20591 (if indent (newline-and-indent) (newline)))
20592 ((org-at-table-p)
20593 (org-table-justify-field-maybe)
20594 (call-interactively 'org-table-next-row))
20595 ;; when `newline-and-indent' is called within a list, make sure
20596 ;; text moved stays inside the item.
20597 ((and (org-in-item-p) indent)
20598 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20599 (progn
20600 (save-match-data (newline))
20601 (org-indent-line-to (length (match-string 0))))
20602 (let ((ind (org-get-indentation)))
20603 (newline)
20604 (if (org-looking-back org-list-end-re)
20605 (org-indent-line)
20606 (org-indent-line-to ind)))))
20607 ((and org-return-follows-link
20608 (org-at-timestamp-p t)
20609 (not (eq org-ts-what 'after)))
20610 (org-follow-timestamp-link))
20611 ((and org-return-follows-link
20612 (let ((tprop (get-text-property (point) 'face)))
20613 (or (eq tprop 'org-link)
20614 (and (listp tprop) (memq 'org-link tprop)))))
20615 (call-interactively 'org-open-at-point))
20616 ((and (org-at-heading-p)
20617 (looking-at
20618 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20619 (org-show-entry)
20620 (end-of-line 1)
20621 (newline))
20622 (t (if indent (newline-and-indent) (newline))))))
20624 (defun org-return-indent ()
20625 "Goto next table row or insert a newline and indent.
20626 Calls `org-table-next-row' or `newline-and-indent', depending on
20627 context. See the individual commands for more information."
20628 (interactive)
20629 (org-return t))
20631 (defun org-ctrl-c-star ()
20632 "Compute table, or change heading status of lines.
20633 Calls `org-table-recalculate' or `org-toggle-heading',
20634 depending on context."
20635 (interactive)
20636 (cond
20637 ((org-at-table-p)
20638 (call-interactively 'org-table-recalculate))
20640 ;; Convert all lines in region to list items
20641 (call-interactively 'org-toggle-heading))))
20643 (defun org-ctrl-c-minus ()
20644 "Insert separator line in table or modify bullet status of line.
20645 Also turns a plain line or a region of lines into list items.
20646 Calls `org-table-insert-hline', `org-toggle-item', or
20647 `org-cycle-list-bullet', depending on context."
20648 (interactive)
20649 (cond
20650 ((org-at-table-p)
20651 (call-interactively 'org-table-insert-hline))
20652 ((org-region-active-p)
20653 (call-interactively 'org-toggle-item))
20654 ((org-in-item-p)
20655 (call-interactively 'org-cycle-list-bullet))
20657 (call-interactively 'org-toggle-item))))
20659 (defun org-toggle-item (arg)
20660 "Convert headings or normal lines to items, items to normal lines.
20661 If there is no active region, only the current line is considered.
20663 If the first non blank line in the region is a headline, convert
20664 all headlines to items, shifting text accordingly.
20666 If it is an item, convert all items to normal lines.
20668 If it is normal text, change region into a list of items.
20669 With a prefix argument ARG, change the region in a single item."
20670 (interactive "P")
20671 (let ((shift-text
20672 (function
20673 ;; Shift text in current section to IND, from point to END.
20674 ;; The function leaves point to END line.
20675 (lambda (ind end)
20676 (let ((min-i 1000) (end (copy-marker end)))
20677 ;; First determine the minimum indentation (MIN-I) of
20678 ;; the text.
20679 (save-excursion
20680 (catch 'exit
20681 (while (< (point) end)
20682 (let ((i (org-get-indentation)))
20683 (cond
20684 ;; Skip blank lines and inline tasks.
20685 ((looking-at "^[ \t]*$"))
20686 ((looking-at org-outline-regexp-bol))
20687 ;; We can't find less than 0 indentation.
20688 ((zerop i) (throw 'exit (setq min-i 0)))
20689 ((< i min-i) (setq min-i i))))
20690 (forward-line))))
20691 ;; Then indent each line so that a line indented to
20692 ;; MIN-I becomes indented to IND. Ignore blank lines
20693 ;; and inline tasks in the process.
20694 (let ((delta (- ind min-i)))
20695 (while (< (point) end)
20696 (unless (or (looking-at "^[ \t]*$")
20697 (looking-at org-outline-regexp-bol))
20698 (org-indent-line-to (+ (org-get-indentation) delta)))
20699 (forward-line)))))))
20700 (skip-blanks
20701 (function
20702 ;; Return beginning of first non-blank line, starting from
20703 ;; line at POS.
20704 (lambda (pos)
20705 (save-excursion
20706 (goto-char pos)
20707 (skip-chars-forward " \r\t\n")
20708 (point-at-bol)))))
20709 beg end)
20710 ;; Determine boundaries of changes.
20711 (if (org-region-active-p)
20712 (setq beg (funcall skip-blanks (region-beginning))
20713 end (copy-marker (region-end)))
20714 (setq beg (funcall skip-blanks (point-at-bol))
20715 end (copy-marker (point-at-eol))))
20716 ;; Depending on the starting line, choose an action on the text
20717 ;; between BEG and END.
20718 (org-with-limited-levels
20719 (save-excursion
20720 (goto-char beg)
20721 (cond
20722 ;; Case 1. Start at an item: de-itemize. Note that it only
20723 ;; happens when a region is active: `org-ctrl-c-minus'
20724 ;; would call `org-cycle-list-bullet' otherwise.
20725 ((org-at-item-p)
20726 (while (< (point) end)
20727 (when (org-at-item-p)
20728 (skip-chars-forward " \t")
20729 (delete-region (point) (match-end 0)))
20730 (forward-line)))
20731 ;; Case 2. Start at an heading: convert to items.
20732 ((org-at-heading-p)
20733 (let* ((bul (org-list-bullet-string "-"))
20734 (bul-len (length bul))
20735 (done (org-entry-is-done-p))
20736 (todo (org-entry-is-todo-p))
20737 ;; Indentation of the first heading. It should be
20738 ;; relative to the indentation of its parent, if any.
20739 (start-ind (save-excursion
20740 (cond
20741 ((not org-adapt-indentation) 0)
20742 ((not (outline-previous-heading)) 0)
20743 (t (length (match-string 0))))))
20744 ;; Level of first heading. Further headings will be
20745 ;; compared to it to determine hierarchy in the list.
20746 (ref-level (org-reduced-level (org-outline-level))))
20747 (when (or done todo) (org-todo ""))
20748 (while (< (point) end)
20749 (let* ((level (org-reduced-level (org-outline-level)))
20750 (delta (max 0 (- level ref-level))))
20751 ;; If current headline is less indented than the first
20752 ;; one, set it as reference, in order to preserve
20753 ;; subtrees.
20754 (when (< level ref-level) (setq ref-level level))
20755 (replace-match bul t t)
20756 (org-indent-line-to (+ start-ind (* delta bul-len)))
20757 (when (or done todo)
20758 (let* ((struct (org-list-struct))
20759 (old (copy-tree struct)))
20760 (org-list-set-checkbox (line-beginning-position)
20761 struct
20762 (if done "[X]" "[ ]"))
20763 (org-list-write-struct struct
20764 (org-list-parents-alist struct)
20765 old)))
20766 ;; Ensure all text down to END (or SECTION-END) belongs
20767 ;; to the newly created item.
20768 (let ((section-end (save-excursion
20769 (or (outline-next-heading) (point)))))
20770 (forward-line)
20771 (funcall shift-text
20772 (+ start-ind (* (1+ delta) bul-len))
20773 (min end section-end)))))))
20774 ;; Case 3. Normal line with ARG: make the first line of region
20775 ;; an item, and shift indentation of others lines to
20776 ;; set them as item's body.
20777 (arg (let* ((bul (org-list-bullet-string "-"))
20778 (bul-len (length bul))
20779 (ref-ind (org-get-indentation)))
20780 (skip-chars-forward " \t")
20781 (insert bul)
20782 (forward-line)
20783 (while (< (point) end)
20784 ;; Ensure that lines less indented than first one
20785 ;; still get included in item body.
20786 (funcall shift-text
20787 (+ ref-ind bul-len)
20788 (min end (save-excursion (or (outline-next-heading)
20789 (point)))))
20790 (forward-line))))
20791 ;; Case 4. Normal line without ARG: turn each non-item line
20792 ;; into an item.
20794 (while (< (point) end)
20795 (unless (or (org-at-heading-p) (org-at-item-p))
20796 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20797 (replace-match
20798 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20799 (forward-line))))))))
20801 (defun org-toggle-heading (&optional nstars)
20802 "Convert headings to normal text, or items or text to headings.
20803 If there is no active region, only convert the current line.
20805 With a \\[universal-argument] prefix, convert the whole list at
20806 point into heading.
20808 In a region:
20810 - If the first non blank line is a headline, remove the stars
20811 from all headlines in the region.
20813 - If it is a normal line, turn each and every normal line (i.e.,
20814 not an heading or an item) in the region into headings. If you
20815 want to convert only the first line of this region, use one
20816 universal prefix argument.
20818 - If it is a plain list item, turn all plain list items into headings.
20820 When converting a line into a heading, the number of stars is chosen
20821 such that the lines become children of the current entry. However,
20822 when a numeric prefix argument is given, its value determines the
20823 number of stars to add."
20824 (interactive "P")
20825 (let ((skip-blanks
20826 (function
20827 ;; Return beginning of first non-blank line, starting from
20828 ;; line at POS.
20829 (lambda (pos)
20830 (save-excursion
20831 (goto-char pos)
20832 (while (org-at-comment-p) (forward-line))
20833 (skip-chars-forward " \r\t\n")
20834 (point-at-bol)))))
20835 beg end toggled)
20836 ;; Determine boundaries of changes. If a universal prefix has
20837 ;; been given, put the list in a region. If region ends at a bol,
20838 ;; do not consider the last line to be in the region.
20840 (when (and current-prefix-arg (org-at-item-p))
20841 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20842 (org-mark-element))
20844 (if (org-region-active-p)
20845 (setq beg (funcall skip-blanks (region-beginning))
20846 end (copy-marker (save-excursion
20847 (goto-char (region-end))
20848 (if (bolp) (point) (point-at-eol)))))
20849 (setq beg (funcall skip-blanks (point-at-bol))
20850 end (copy-marker (point-at-eol))))
20851 ;; Ensure inline tasks don't count as headings.
20852 (org-with-limited-levels
20853 (save-excursion
20854 (goto-char beg)
20855 (cond
20856 ;; Case 1. Started at an heading: de-star headings.
20857 ((org-at-heading-p)
20858 (while (< (point) end)
20859 (when (org-at-heading-p t)
20860 (looking-at org-outline-regexp) (replace-match "")
20861 (setq toggled t))
20862 (forward-line)))
20863 ;; Case 2. Started at an item: change items into headlines.
20864 ;; One star will be added by `org-list-to-subtree'.
20865 ((org-at-item-p)
20866 (let* ((stars (make-string
20867 ;; subtract the star that will be added again by
20868 ;; `org-list-to-subtree'
20869 (if (numberp nstars) (1- nstars)
20870 (or (org-current-level) 0))
20871 ?*))
20872 (add-stars
20873 (cond (nstars "") ; stars from prefix only
20874 ((equal stars "") "") ; before first heading
20875 (org-odd-levels-only "*") ; inside heading, odd
20876 (t "")))) ; inside heading, oddeven
20877 (while (< (point) end)
20878 (when (org-at-item-p)
20879 ;; Pay attention to cases when region ends before list.
20880 (let* ((struct (org-list-struct))
20881 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20882 (save-restriction
20883 (narrow-to-region (point) list-end)
20884 (insert
20885 (org-list-to-subtree
20886 (org-list-parse-list t)
20887 '(:istart (concat stars add-stars (funcall get-stars depth))
20888 :icount (concat stars add-stars (funcall get-stars depth)))))))
20889 (setq toggled t))
20890 (forward-line))))
20891 ;; Case 3. Started at normal text: make every line an heading,
20892 ;; skipping headlines and items.
20893 (t (let* ((stars
20894 (make-string
20895 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20896 (add-stars
20897 (cond (nstars "") ; stars from prefix only
20898 ((equal stars "") "*") ; before first heading
20899 (org-odd-levels-only "**") ; inside heading, odd
20900 (t "*"))) ; inside heading, oddeven
20901 (rpl (concat stars add-stars " "))
20902 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20903 (while (< (point) (if (equal nstars '(4)) lend end))
20904 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20905 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20906 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20907 (forward-line)))))))
20908 (unless toggled (message "Cannot toggle heading from here"))))
20910 (defun org-meta-return (&optional arg)
20911 "Insert a new heading or wrap a region in a table.
20912 Calls `org-insert-heading' or `org-table-wrap-region', depending
20913 on context. See the individual commands for more information."
20914 (interactive "P")
20915 (org-check-before-invisible-edit 'insert)
20916 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20917 (let* ((element (org-element-at-point))
20918 (type (org-element-type element)))
20919 (when (eq type 'table-row)
20920 (setq element (org-element-property :parent element))
20921 (setq type 'table))
20922 (if (and (eq type 'table)
20923 (eq (org-element-property :type element) 'org)
20924 (>= (point) (org-element-property :contents-begin element))
20925 (< (point) (org-element-property :contents-end element)))
20926 (call-interactively 'org-table-wrap-region)
20927 (call-interactively 'org-insert-heading)))))
20929 ;;; Menu entries
20931 (defsubst org-in-subtree-not-table-p ()
20932 "Are we in a subtree and not in a table?"
20933 (and (not (org-before-first-heading-p))
20934 (not (org-at-table-p))))
20936 ;; Define the Org-mode menus
20937 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20938 '("Tbl"
20939 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20940 ["Next Field" org-cycle (org-at-table-p)]
20941 ["Previous Field" org-shifttab (org-at-table-p)]
20942 ["Next Row" org-return (org-at-table-p)]
20943 "--"
20944 ["Blank Field" org-table-blank-field (org-at-table-p)]
20945 ["Edit Field" org-table-edit-field (org-at-table-p)]
20946 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20947 "--"
20948 ("Column"
20949 ["Move Column Left" org-metaleft (org-at-table-p)]
20950 ["Move Column Right" org-metaright (org-at-table-p)]
20951 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20952 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20953 ("Row"
20954 ["Move Row Up" org-metaup (org-at-table-p)]
20955 ["Move Row Down" org-metadown (org-at-table-p)]
20956 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20957 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20958 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20959 "--"
20960 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20961 ("Rectangle"
20962 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20963 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20964 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20965 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20966 "--"
20967 ("Calculate"
20968 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20969 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20970 ["Edit Formulas" org-edit-special (org-at-table-p)]
20971 "--"
20972 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20973 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20974 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20975 "--"
20976 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20977 "--"
20978 ["Sum Column/Rectangle" org-table-sum
20979 (or (org-at-table-p) (org-region-active-p))]
20980 ["Which Column?" org-table-current-column (org-at-table-p)])
20981 ["Debug Formulas"
20982 org-table-toggle-formula-debugger
20983 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20984 ["Show Col/Row Numbers"
20985 org-table-toggle-coordinate-overlays
20986 :style toggle
20987 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20988 "--"
20989 ["Create" org-table-create (and (not (org-at-table-p))
20990 org-enable-table-editor)]
20991 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20992 ["Import from File" org-table-import (not (org-at-table-p))]
20993 ["Export to File" org-table-export (org-at-table-p)]
20994 "--"
20995 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20997 (easy-menu-define org-org-menu org-mode-map "Org menu"
20998 '("Org"
20999 ("Show/Hide"
21000 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21001 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21002 ["Sparse Tree..." org-sparse-tree t]
21003 ["Reveal Context" org-reveal t]
21004 ["Show All" show-all t]
21005 "--"
21006 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21007 "--"
21008 ["New Heading" org-insert-heading t]
21009 ("Navigate Headings"
21010 ["Up" outline-up-heading t]
21011 ["Next" outline-next-visible-heading t]
21012 ["Previous" outline-previous-visible-heading t]
21013 ["Next Same Level" outline-forward-same-level t]
21014 ["Previous Same Level" outline-backward-same-level t]
21015 "--"
21016 ["Jump" org-goto t])
21017 ("Edit Structure"
21018 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21019 "--"
21020 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21021 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21022 "--"
21023 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21024 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21025 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21026 "--"
21027 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21028 "--"
21029 ["Copy visible text" org-copy-visible t]
21030 "--"
21031 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21032 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21033 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21034 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21035 "--"
21036 ["Sort Region/Children" org-sort t]
21037 "--"
21038 ["Convert to odd levels" org-convert-to-odd-levels t]
21039 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21040 ("Editing"
21041 ["Emphasis..." org-emphasize t]
21042 ["Edit Source Example" org-edit-special t]
21043 "--"
21044 ["Footnote new/jump" org-footnote-action t]
21045 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21046 ("Archive"
21047 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21048 "--"
21049 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21050 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21051 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21053 "--"
21054 ("Hyperlinks"
21055 ["Store Link (Global)" org-store-link t]
21056 ["Find existing link to here" org-occur-link-in-agenda-files t]
21057 ["Insert Link" org-insert-link t]
21058 ["Follow Link" org-open-at-point t]
21059 "--"
21060 ["Next link" org-next-link t]
21061 ["Previous link" org-previous-link t]
21062 "--"
21063 ["Descriptive Links"
21064 org-toggle-link-display
21065 :style radio
21066 :selected org-descriptive-links
21068 ["Literal Links"
21069 org-toggle-link-display
21070 :style radio
21071 :selected (not org-descriptive-links)])
21072 "--"
21073 ("TODO Lists"
21074 ["TODO/DONE/-" org-todo t]
21075 ("Select keyword"
21076 ["Next keyword" org-shiftright (org-at-heading-p)]
21077 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21078 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21079 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21080 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21081 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21082 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21083 "--"
21084 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21085 :selected org-enforce-todo-dependencies :style toggle :active t]
21086 "Settings for tree at point"
21087 ["Do Children sequentially" org-toggle-ordered-property :style radio
21088 :selected (org-entry-get nil "ORDERED")
21089 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21090 ["Do Children parallel" org-toggle-ordered-property :style radio
21091 :selected (not (org-entry-get nil "ORDERED"))
21092 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21093 "--"
21094 ["Set Priority" org-priority t]
21095 ["Priority Up" org-shiftup t]
21096 ["Priority Down" org-shiftdown t]
21097 "--"
21098 ["Get news from all feeds" org-feed-update-all t]
21099 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21100 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21101 ("TAGS and Properties"
21102 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21103 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21104 "--"
21105 ["Set property" org-set-property (not (org-before-first-heading-p))]
21106 ["Column view of properties" org-columns t]
21107 ["Insert Column View DBlock" org-insert-columns-dblock t])
21108 ("Dates and Scheduling"
21109 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21110 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21111 ("Change Date"
21112 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21113 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21114 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21115 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21116 ["Compute Time Range" org-evaluate-time-range t]
21117 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21118 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21119 "--"
21120 ["Custom time format" org-toggle-time-stamp-overlays
21121 :style radio :selected org-display-custom-times]
21122 "--"
21123 ["Goto Calendar" org-goto-calendar t]
21124 ["Date from Calendar" org-date-from-calendar t]
21125 "--"
21126 ["Start/Restart Timer" org-timer-start t]
21127 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21128 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21129 ["Insert Timer String" org-timer t]
21130 ["Insert Timer Item" org-timer-item t])
21131 ("Logging work"
21132 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21133 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21134 ["Clock out" org-clock-out t]
21135 ["Clock cancel" org-clock-cancel t]
21136 "--"
21137 ["Mark as default task" org-clock-mark-default-task t]
21138 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21139 ["Goto running clock" org-clock-goto t]
21140 "--"
21141 ["Display times" org-clock-display t]
21142 ["Create clock table" org-clock-report t]
21143 "--"
21144 ["Record DONE time"
21145 (progn (setq org-log-done (not org-log-done))
21146 (message "Switching to %s will %s record a timestamp"
21147 (car org-done-keywords)
21148 (if org-log-done "automatically" "not")))
21149 :style toggle :selected org-log-done])
21150 "--"
21151 ["Agenda Command..." org-agenda t]
21152 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21153 ("File List for Agenda")
21154 ("Special views current file"
21155 ["TODO Tree" org-show-todo-tree t]
21156 ["Check Deadlines" org-check-deadlines t]
21157 ["Timeline" org-timeline t]
21158 ["Tags/Property tree" org-match-sparse-tree t])
21159 "--"
21160 ["Export/Publish..." org-export-dispatch t]
21161 ("LaTeX"
21162 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21163 :selected org-cdlatex-mode]
21164 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21165 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21166 ["Modify math symbol" org-cdlatex-math-modify
21167 (org-inside-LaTeX-fragment-p)]
21168 ["Insert citation" org-reftex-citation t]
21169 "--"
21170 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21171 "--"
21172 ("MobileOrg"
21173 ["Push Files and Views" org-mobile-push t]
21174 ["Get Captured and Flagged" org-mobile-pull t]
21175 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21176 "--"
21177 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21178 "--"
21179 ("Documentation"
21180 ["Show Version" org-version t]
21181 ["Info Documentation" org-info t])
21182 ("Customize"
21183 ["Browse Org Group" org-customize t]
21184 "--"
21185 ["Expand This Menu" org-create-customize-menu
21186 (fboundp 'customize-menu-create)])
21187 ["Send bug report" org-submit-bug-report t]
21188 "--"
21189 ("Refresh/Reload"
21190 ["Refresh setup current buffer" org-mode-restart t]
21191 ["Reload Org (after update)" org-reload t]
21192 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21195 (defun org-info (&optional node)
21196 "Read documentation for Org-mode in the info system.
21197 With optional NODE, go directly to that node."
21198 (interactive)
21199 (info (format "(org)%s" (or node ""))))
21201 ;;;###autoload
21202 (defun org-submit-bug-report ()
21203 "Submit a bug report on Org-mode via mail.
21205 Don't hesitate to report any problems or inaccurate documentation.
21207 If you don't have setup sending mail from (X)Emacs, please copy the
21208 output buffer into your mail program, as it gives us important
21209 information about your Org-mode version and configuration."
21210 (interactive)
21211 (require 'reporter)
21212 (org-load-modules-maybe)
21213 (org-require-autoloaded-modules)
21214 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21215 (reporter-submit-bug-report
21216 "emacs-orgmode@gnu.org"
21217 (org-version nil 'full)
21218 (let (list)
21219 (save-window-excursion
21220 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21221 (delete-other-windows)
21222 (erase-buffer)
21223 (insert "You are about to submit a bug report to the Org-mode mailing list.
21225 We would like to add your full Org-mode and Outline configuration to the
21226 bug report. This greatly simplifies the work of the maintainer and
21227 other experts on the mailing list.
21229 HOWEVER, some variables you have customized may contain private
21230 information. The names of customers, colleagues, or friends, might
21231 appear in the form of file names, tags, todo states, or search strings.
21232 If you answer yes to the prompt, you might want to check and remove
21233 such private information before sending the email.")
21234 (add-text-properties (point-min) (point-max) '(face org-warning))
21235 (when (yes-or-no-p "Include your Org-mode configuration ")
21236 (mapatoms
21237 (lambda (v)
21238 (and (boundp v)
21239 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21240 (or (and (symbol-value v)
21241 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21242 (and
21243 (get v 'custom-type) (get v 'standard-value)
21244 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21245 (push v list)))))
21246 (kill-buffer (get-buffer "*Warn about privacy*"))
21247 list))
21248 nil nil
21249 "Remember to cover the basics, that is, what you expected to happen and
21250 what in fact did happen. You don't know how to make a good report? See
21252 http://orgmode.org/manual/Feedback.html#Feedback
21254 Your bug report will be posted to the Org-mode mailing list.
21255 ------------------------------------------------------------------------")
21256 (save-excursion
21257 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21258 (replace-match "\\1Bug: \\3 [\\2]")))))
21261 (defun org-install-agenda-files-menu ()
21262 (let ((bl (buffer-list)))
21263 (save-excursion
21264 (while bl
21265 (set-buffer (pop bl))
21266 (if (derived-mode-p 'org-mode) (setq bl nil)))
21267 (when (derived-mode-p 'org-mode)
21268 (easy-menu-change
21269 '("Org") "File List for Agenda"
21270 (append
21271 (list
21272 ["Edit File List" (org-edit-agenda-file-list) t]
21273 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21274 ["Remove Current File from List" org-remove-file t]
21275 ["Cycle through agenda files" org-cycle-agenda-files t]
21276 ["Occur in all agenda files" org-occur-in-agenda-files t]
21277 "--")
21278 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21280 ;;;; Documentation
21282 (defun org-require-autoloaded-modules ()
21283 (interactive)
21284 (mapc 'require
21285 '(org-agenda org-archive org-attach org-clock org-colview org-id
21286 org-table org-timer)))
21288 ;;;###autoload
21289 (defun org-reload (&optional uncompiled)
21290 "Reload all org lisp files.
21291 With prefix arg UNCOMPILED, load the uncompiled versions."
21292 (interactive "P")
21293 (require 'loadhist)
21294 (let* ((org-dir (org-find-library-dir "org"))
21295 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21296 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21297 (remove-re (mapconcat 'identity
21298 (mapcar (lambda (f) (concat "^" f "$"))
21299 (list (if (featurep 'xemacs)
21300 "org-colview"
21301 "org-colview-xemacs")
21302 "org" "org-loaddefs" "org-version"))
21303 "\\|"))
21304 (feats (delete-dups
21305 (mapcar 'file-name-sans-extension
21306 (mapcar 'file-name-nondirectory
21307 (delq nil
21308 (mapcar 'feature-file
21309 features))))))
21310 (lfeat (append
21311 (sort
21312 (setq feats
21313 (delq nil (mapcar
21314 (lambda (f)
21315 (if (and (string-match feature-re f)
21316 (not (string-match remove-re f)))
21317 f nil))
21318 feats)))
21319 'string-lessp)
21320 (list "org-version" "org")))
21321 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21322 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21323 load-uncore load-misses)
21324 (setq load-misses
21325 (delq 't
21326 (mapcar (lambda (f)
21327 (or (org-load-noerror-mustsuffix (concat org-dir f))
21328 (and (string= org-dir contrib-dir)
21329 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21330 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21331 (add-to-list 'load-uncore f 'append)
21334 lfeat)))
21335 (if load-uncore
21336 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21337 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21338 (if load-misses
21339 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21340 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21341 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21343 ;;;###autoload
21344 (defun org-customize ()
21345 "Call the customize function with org as argument."
21346 (interactive)
21347 (org-load-modules-maybe)
21348 (org-require-autoloaded-modules)
21349 (customize-browse 'org))
21351 (defun org-create-customize-menu ()
21352 "Create a full customization menu for Org-mode, insert it into the menu."
21353 (interactive)
21354 (org-load-modules-maybe)
21355 (org-require-autoloaded-modules)
21356 (if (fboundp 'customize-menu-create)
21357 (progn
21358 (easy-menu-change
21359 '("Org") "Customize"
21360 `(["Browse Org group" org-customize t]
21361 "--"
21362 ,(customize-menu-create 'org)
21363 ["Set" Custom-set t]
21364 ["Save" Custom-save t]
21365 ["Reset to Current" Custom-reset-current t]
21366 ["Reset to Saved" Custom-reset-saved t]
21367 ["Reset to Standard Settings" Custom-reset-standard t]))
21368 (message "\"Org\"-menu now contains full customization menu"))
21369 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21371 ;;;; Miscellaneous stuff
21373 ;;; Generally useful functions
21375 (defun org-get-at-bol (property)
21376 "Get text property PROPERTY at beginning of line."
21377 (get-text-property (point-at-bol) property))
21379 (defun org-find-text-property-in-string (prop s)
21380 "Return the first non-nil value of property PROP in string S."
21381 (or (get-text-property 0 prop s)
21382 (get-text-property (or (next-single-property-change 0 prop s) 0)
21383 prop s)))
21385 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21386 "Display the given MESSAGE as a warning."
21387 (if (fboundp 'display-warning)
21388 (display-warning 'org message
21389 (if (featurep 'xemacs) 'warning :warning))
21390 (let ((buf (get-buffer-create "*Org warnings*")))
21391 (with-current-buffer buf
21392 (goto-char (point-max))
21393 (insert "Warning (Org): " message)
21394 (unless (bolp)
21395 (newline)))
21396 (display-buffer buf)
21397 (sit-for 0))))
21399 (defun org-eval (form)
21400 "Eval FORM and return result."
21401 (condition-case error
21402 (eval form)
21403 (error (format "%%![Error: %s]" error))))
21405 (defun org-in-clocktable-p ()
21406 "Check if the cursor is in a clocktable."
21407 (let ((pos (point)) start)
21408 (save-excursion
21409 (end-of-line 1)
21410 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21411 (setq start (match-beginning 0))
21412 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21413 (>= (match-end 0) pos)
21414 start))))
21416 (defun org-in-commented-line ()
21417 "Is point in a line starting with `#'?"
21418 (equal (char-after (point-at-bol)) ?#))
21420 (defun org-in-indented-comment-line ()
21421 "Is point in a line starting with `#' after some white space?"
21422 (save-excursion
21423 (save-match-data
21424 (goto-char (point-at-bol))
21425 (looking-at "[ \t]*#"))))
21427 (defun org-in-verbatim-emphasis ()
21428 (save-match-data
21429 (and (org-in-regexp org-emph-re 2)
21430 (>= (point) (match-beginning 3))
21431 (<= (point) (match-end 4))
21432 (member (match-string 3) '("=" "~")))))
21434 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21435 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21436 (if (and marker (marker-buffer marker)
21437 (buffer-live-p (marker-buffer marker)))
21438 (progn
21439 (org-pop-to-buffer-same-window (marker-buffer marker))
21440 (if (or (> marker (point-max)) (< marker (point-min)))
21441 (widen))
21442 (goto-char marker)
21443 (org-show-context 'org-goto))
21444 (if bookmark
21445 (bookmark-jump bookmark)
21446 (error "Cannot find location"))))
21448 (defun org-quote-csv-field (s)
21449 "Quote field for inclusion in CSV material."
21450 (if (string-match "[\",]" s)
21451 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21454 (defun org-force-self-insert (N)
21455 "Needed to enforce self-insert under remapping."
21456 (interactive "p")
21457 (self-insert-command N))
21459 (defun org-string-width (s)
21460 "Compute width of string, ignoring invisible characters.
21461 This ignores character with invisibility property `org-link', and also
21462 characters with property `org-cwidth', because these will become invisible
21463 upon the next fontification round."
21464 (let (b l)
21465 (when (or (eq t buffer-invisibility-spec)
21466 (assq 'org-link buffer-invisibility-spec))
21467 (while (setq b (text-property-any 0 (length s)
21468 'invisible 'org-link s))
21469 (setq s (concat (substring s 0 b)
21470 (substring s (or (next-single-property-change
21471 b 'invisible s) (length s)))))))
21472 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21473 (setq s (concat (substring s 0 b)
21474 (substring s (or (next-single-property-change
21475 b 'org-cwidth s) (length s))))))
21476 (setq l (string-width s) b -1)
21477 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21478 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21481 (defun org-shorten-string (s maxlength)
21482 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21483 If the string is shorter or has length MAXLENGTH, just return the
21484 original string. If it is longer, the functions finds a space in the
21485 string, breaks this string off at that locations and adds three dots
21486 as ellipsis. Including the ellipsis, the string will not be longer
21487 than MAXLENGTH. If finding a good breaking point in the string does
21488 not work, the string is just chopped off in the middle of a word
21489 if necessary."
21490 (if (<= (length s) maxlength)
21492 (let* ((n (max (- maxlength 4) 1))
21493 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21494 (if (string-match re s)
21495 (concat (match-string 1 s) "...")
21496 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21498 (defun org-get-indentation (&optional line)
21499 "Get the indentation of the current line, interpreting tabs.
21500 When LINE is given, assume it represents a line and compute its indentation."
21501 (if line
21502 (if (string-match "^ *" (org-remove-tabs line))
21503 (match-end 0))
21504 (save-excursion
21505 (beginning-of-line 1)
21506 (skip-chars-forward " \t")
21507 (current-column))))
21509 (defun org-get-string-indentation (s)
21510 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21511 (let ((n -1) (i 0) (w tab-width) c)
21512 (catch 'exit
21513 (while (< (setq n (1+ n)) (length s))
21514 (setq c (aref s n))
21515 (cond ((= c ?\ ) (setq i (1+ i)))
21516 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21517 (t (throw 'exit t)))))
21520 (defun org-remove-tabs (s &optional width)
21521 "Replace tabulators in S with spaces.
21522 Assumes that s is a single line, starting in column 0."
21523 (setq width (or width tab-width))
21524 (while (string-match "\t" s)
21525 (setq s (replace-match
21526 (make-string
21527 (- (* width (/ (+ (match-beginning 0) width) width))
21528 (match-beginning 0)) ?\ )
21529 t t s)))
21532 (defun org-fix-indentation (line ind)
21533 "Fix indentation in LINE.
21534 IND is a cons cell with target and minimum indentation.
21535 If the current indentation in LINE is smaller than the minimum,
21536 leave it alone. If it is larger than ind, set it to the target."
21537 (let* ((l (org-remove-tabs line))
21538 (i (org-get-indentation l))
21539 (i1 (car ind)) (i2 (cdr ind)))
21540 (if (>= i i2) (setq l (substring line i2)))
21541 (if (> i1 0)
21542 (concat (make-string i1 ?\ ) l)
21543 l)))
21545 (defun org-remove-indentation (code &optional n)
21546 "Remove the maximum common indentation from the lines in CODE.
21547 N may optionally be the number of spaces to remove."
21548 (with-temp-buffer
21549 (insert code)
21550 (org-do-remove-indentation n)
21551 (buffer-string)))
21553 (defun org-do-remove-indentation (&optional n)
21554 "Remove the maximum common indentation from the buffer."
21555 (untabify (point-min) (point-max))
21556 (let ((min 10000) re)
21557 (if n
21558 (setq min n)
21559 (goto-char (point-min))
21560 (while (re-search-forward "^ *[^ \n]" nil t)
21561 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21562 (unless (or (= min 0) (= min 10000))
21563 (setq re (format "^ \\{%d\\}" min))
21564 (goto-char (point-min))
21565 (while (re-search-forward re nil t)
21566 (replace-match "")
21567 (end-of-line 1))
21568 min)))
21570 (defun org-fill-template (template alist)
21571 "Find each %key of ALIST in TEMPLATE and replace it."
21572 (let ((case-fold-search nil)
21573 entry key value)
21574 (setq alist (sort (copy-sequence alist)
21575 (lambda (a b) (< (length (car a)) (length (car b))))))
21576 (while (setq entry (pop alist))
21577 (setq template
21578 (replace-regexp-in-string
21579 (concat "%" (regexp-quote (car entry)))
21580 (or (cdr entry) "") template t t)))
21581 template))
21583 (defun org-base-buffer (buffer)
21584 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21585 (if (not buffer)
21586 buffer
21587 (or (buffer-base-buffer buffer)
21588 buffer)))
21590 (defsubst org-trim (s)
21591 "Remove whitespace at the beginning and the end of string S."
21592 (replace-regexp-in-string
21593 "\\`[ \t\n\r]+" ""
21594 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
21596 (defun org-wrap (string &optional width lines)
21597 "Wrap string to either a number of lines, or a width in characters.
21598 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21599 that costs. If there is a word longer than WIDTH, the text is actually
21600 wrapped to the length of that word.
21601 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21602 many lines, whatever width that takes.
21603 The return value is a list of lines, without newlines at the end."
21604 (let* ((words (org-split-string string "[ \t\n]+"))
21605 (maxword (apply 'max (mapcar 'org-string-width words)))
21606 w ll)
21607 (cond (width
21608 (org-do-wrap words (max maxword width)))
21609 (lines
21610 (setq w maxword)
21611 (setq ll (org-do-wrap words maxword))
21612 (if (<= (length ll) lines)
21614 (setq ll words)
21615 (while (> (length ll) lines)
21616 (setq w (1+ w))
21617 (setq ll (org-do-wrap words w)))
21618 ll))
21619 (t (error "Cannot wrap this")))))
21621 (defun org-do-wrap (words width)
21622 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21623 (let (lines line)
21624 (while words
21625 (setq line (pop words))
21626 (while (and words (< (+ (length line) (length (car words))) width))
21627 (setq line (concat line " " (pop words))))
21628 (setq lines (push line lines)))
21629 (nreverse lines)))
21631 (defun org-split-string (string &optional separators)
21632 "Splits STRING into substrings at SEPARATORS.
21633 No empty strings are returned if there are matches at the beginning
21634 and end of string."
21635 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21636 (start 0)
21637 notfirst
21638 (list nil))
21639 (while (and (string-match rexp string
21640 (if (and notfirst
21641 (= start (match-beginning 0))
21642 (< start (length string)))
21643 (1+ start) start))
21644 (< (match-beginning 0) (length string)))
21645 (setq notfirst t)
21646 (or (eq (match-beginning 0) 0)
21647 (and (eq (match-beginning 0) (match-end 0))
21648 (eq (match-beginning 0) start))
21649 (setq list
21650 (cons (substring string start (match-beginning 0))
21651 list)))
21652 (setq start (match-end 0)))
21653 (or (eq start (length string))
21654 (setq list
21655 (cons (substring string start)
21656 list)))
21657 (nreverse list)))
21659 (defun org-quote-vert (s)
21660 "Replace \"|\" with \"\\vert\"."
21661 (while (string-match "|" s)
21662 (setq s (replace-match "\\vert" t t s)))
21665 (defun org-uuidgen-p (s)
21666 "Is S an ID created by UUIDGEN?"
21667 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21669 (defun org-in-src-block-p (&optional inside)
21670 "Whether point is in a code source block.
21671 When INSIDE is non-nil, don't consider we are within a src block
21672 when point is at #+BEGIN_SRC or #+END_SRC."
21673 (let ((case-fold-search t) ov)
21674 (or (and (setq ov (overlays-at (point)))
21675 (memq 'org-block-background
21676 (overlay-properties (car ov))))
21677 (and (not inside)
21678 (save-match-data
21679 (save-excursion
21680 (beginning-of-line)
21681 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21683 (defun org-context ()
21684 "Return a list of contexts of the current cursor position.
21685 If several contexts apply, all are returned.
21686 Each context entry is a list with a symbol naming the context, and
21687 two positions indicating start and end of the context. Possible
21688 contexts are:
21690 :headline anywhere in a headline
21691 :headline-stars on the leading stars in a headline
21692 :todo-keyword on a TODO keyword (including DONE) in a headline
21693 :tags on the TAGS in a headline
21694 :priority on the priority cookie in a headline
21695 :item on the first line of a plain list item
21696 :item-bullet on the bullet/number of a plain list item
21697 :checkbox on the checkbox in a plain list item
21698 :table in an org-mode table
21699 :table-special on a special filed in a table
21700 :table-table in a table.el table
21701 :clocktable in a clocktable
21702 :src-block in a source block
21703 :link on a hyperlink
21704 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21705 :target on a <<target>>
21706 :radio-target on a <<<radio-target>>>
21707 :latex-fragment on a LaTeX fragment
21708 :latex-preview on a LaTeX fragment with overlaid preview image
21710 This function expects the position to be visible because it uses font-lock
21711 faces as a help to recognize the following contexts: :table-special, :link,
21712 and :keyword."
21713 (let* ((f (get-text-property (point) 'face))
21714 (faces (if (listp f) f (list f)))
21715 (case-fold-search t)
21716 (p (point)) clist o)
21717 ;; First the large context
21718 (cond
21719 ((org-at-heading-p t)
21720 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21721 (when (progn
21722 (beginning-of-line 1)
21723 (looking-at org-todo-line-tags-regexp))
21724 (push (org-point-in-group p 1 :headline-stars) clist)
21725 (push (org-point-in-group p 2 :todo-keyword) clist)
21726 (push (org-point-in-group p 4 :tags) clist))
21727 (goto-char p)
21728 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21729 (if (looking-at "\\[#[A-Z0-9]\\]")
21730 (push (org-point-in-group p 0 :priority) clist)))
21732 ((org-at-item-p)
21733 (push (org-point-in-group p 2 :item-bullet) clist)
21734 (push (list :item (point-at-bol)
21735 (save-excursion (org-end-of-item) (point)))
21736 clist)
21737 (and (org-at-item-checkbox-p)
21738 (push (org-point-in-group p 0 :checkbox) clist)))
21740 ((org-at-table-p)
21741 (push (list :table (org-table-begin) (org-table-end)) clist)
21742 (if (memq 'org-formula faces)
21743 (push (list :table-special
21744 (previous-single-property-change p 'face)
21745 (next-single-property-change p 'face)) clist)))
21746 ((org-at-table-p 'any)
21747 (push (list :table-table) clist)))
21748 (goto-char p)
21750 (let ((case-fold-search t))
21751 ;; New the "medium" contexts: clocktables, source blocks
21752 (cond ((org-in-clocktable-p)
21753 (push (list :clocktable
21754 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21755 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21756 (match-beginning 1))
21757 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21758 (match-end 0))) clist))
21759 ((org-in-src-block-p)
21760 (push (list :src-block
21761 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21762 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21763 (match-beginning 1))
21764 (and (search-forward "#+END_SRC" nil t)
21765 (match-beginning 0))) clist))))
21766 (goto-char p)
21768 ;; Now the small context
21769 (cond
21770 ((org-at-timestamp-p)
21771 (push (org-point-in-group p 0 :timestamp) clist))
21772 ((memq 'org-link faces)
21773 (push (list :link
21774 (previous-single-property-change p 'face)
21775 (next-single-property-change p 'face)) clist))
21776 ((memq 'org-special-keyword faces)
21777 (push (list :keyword
21778 (previous-single-property-change p 'face)
21779 (next-single-property-change p 'face)) clist))
21780 ((org-at-target-p)
21781 (push (org-point-in-group p 0 :target) clist)
21782 (goto-char (1- (match-beginning 0)))
21783 (if (looking-at org-radio-target-regexp)
21784 (push (org-point-in-group p 0 :radio-target) clist))
21785 (goto-char p))
21786 ((setq o (car (delq nil
21787 (mapcar
21788 (lambda (x)
21789 (if (memq x org-latex-fragment-image-overlays) x))
21790 (overlays-at (point))))))
21791 (push (list :latex-fragment
21792 (overlay-start o) (overlay-end o)) clist)
21793 (push (list :latex-preview
21794 (overlay-start o) (overlay-end o)) clist))
21795 ((org-inside-LaTeX-fragment-p)
21796 ;; FIXME: positions wrong.
21797 (push (list :latex-fragment (point) (point)) clist)))
21799 (setq clist (nreverse (delq nil clist)))
21800 clist))
21802 ;; FIXME: Compare with at-regexp-p Do we need both?
21803 (defun org-in-regexp (re &optional nlines visually)
21804 "Check if point is inside a match of regexp.
21805 Normally only the current line is checked, but you can include NLINES extra
21806 lines both before and after point into the search.
21807 If VISUALLY is set, require that the cursor is not after the match but
21808 really on, so that the block visually is on the match."
21809 (catch 'exit
21810 (let ((pos (point))
21811 (eol (point-at-eol (+ 1 (or nlines 0))))
21812 (inc (if visually 1 0)))
21813 (save-excursion
21814 (beginning-of-line (- 1 (or nlines 0)))
21815 (while (re-search-forward re eol t)
21816 (if (and (<= (match-beginning 0) pos)
21817 (>= (+ inc (match-end 0)) pos))
21818 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21820 (defun org-at-regexp-p (regexp)
21821 "Is point inside a match of REGEXP in the current line?"
21822 (catch 'exit
21823 (save-excursion
21824 (let ((pos (point)) (end (point-at-eol)))
21825 (beginning-of-line 1)
21826 (while (re-search-forward regexp end t)
21827 (if (and (<= (match-beginning 0) pos)
21828 (>= (match-end 0) pos))
21829 (throw 'exit t)))
21830 nil))))
21832 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21833 "Non-nil when point is between matches of START-RE and END-RE.
21835 Also return a non-nil value when point is on one of the matches.
21837 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21838 buffer positions. Default values are the positions of headlines
21839 surrounding the point.
21841 The functions returns a cons cell whose car (resp. cdr) is the
21842 position before START-RE (resp. after END-RE)."
21843 (save-match-data
21844 (let ((pos (point))
21845 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21846 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21847 beg end)
21848 (save-excursion
21849 ;; Point is on a block when on START-RE or if START-RE can be
21850 ;; found before it...
21851 (and (or (org-at-regexp-p start-re)
21852 (re-search-backward start-re limit-up t))
21853 (setq beg (match-beginning 0))
21854 ;; ... and END-RE after it...
21855 (goto-char (match-end 0))
21856 (re-search-forward end-re limit-down t)
21857 (> (setq end (match-end 0)) pos)
21858 ;; ... without another START-RE in-between.
21859 (goto-char (match-beginning 0))
21860 (not (re-search-backward start-re (1+ beg) t))
21861 ;; Return value.
21862 (cons beg end))))))
21864 (defun org-in-block-p (names)
21865 "Non-nil when point belongs to a block whose name belongs to NAMES.
21867 NAMES is a list of strings containing names of blocks.
21869 Return first block name matched, or nil. Beware that in case of
21870 nested blocks, the returned name may not belong to the closest
21871 block from point."
21872 (save-match-data
21873 (catch 'exit
21874 (let ((case-fold-search t)
21875 (lim-up (save-excursion (outline-previous-heading)))
21876 (lim-down (save-excursion (outline-next-heading))))
21877 (mapc (lambda (name)
21878 (let ((n (regexp-quote name)))
21879 (when (org-between-regexps-p
21880 (concat "^[ \t]*#\\+begin_" n)
21881 (concat "^[ \t]*#\\+end_" n)
21882 lim-up lim-down)
21883 (throw 'exit n))))
21884 names))
21885 nil)))
21887 (defun org-in-drawer-p ()
21888 "Non-nil if point is within a drawer.
21889 If point is within a drawer, return it, as parsed data."
21890 (let ((element (save-match-data (org-element-at-point))))
21891 (while (and element (not (memq (org-element-type element)
21892 '(drawer property-drawer))))
21893 (setq element (org-element-property :parent element)))
21894 element))
21896 (defun org-occur-in-agenda-files (regexp &optional nlines)
21897 "Call `multi-occur' with buffers for all agenda files."
21898 (interactive "sOrg-files matching: \np")
21899 (let* ((files (org-agenda-files))
21900 (tnames (mapcar 'file-truename files))
21901 (extra org-agenda-text-search-extra-files)
21903 (when (eq (car extra) 'agenda-archives)
21904 (setq extra (cdr extra))
21905 (setq files (org-add-archive-files files)))
21906 (while (setq f (pop extra))
21907 (unless (member (file-truename f) tnames)
21908 (add-to-list 'files f 'append)
21909 (add-to-list 'tnames (file-truename f) 'append)))
21910 (multi-occur
21911 (mapcar (lambda (x)
21912 (with-current-buffer
21913 (or (get-file-buffer x) (find-file-noselect x))
21914 (widen)
21915 (current-buffer)))
21916 files)
21917 regexp)))
21919 (if (boundp 'occur-mode-find-occurrence-hook)
21920 ;; Emacs 23
21921 (add-hook 'occur-mode-find-occurrence-hook
21922 (lambda ()
21923 (when (derived-mode-p 'org-mode)
21924 (org-reveal))))
21925 ;; Emacs 22
21926 (defadvice occur-mode-goto-occurrence
21927 (after org-occur-reveal activate)
21928 (and (derived-mode-p 'org-mode) (org-reveal)))
21929 (defadvice occur-mode-goto-occurrence-other-window
21930 (after org-occur-reveal activate)
21931 (and (derived-mode-p 'org-mode) (org-reveal)))
21932 (defadvice occur-mode-display-occurrence
21933 (after org-occur-reveal activate)
21934 (when (derived-mode-p 'org-mode)
21935 (let ((pos (occur-mode-find-occurrence)))
21936 (with-current-buffer (marker-buffer pos)
21937 (save-excursion
21938 (goto-char pos)
21939 (org-reveal)))))))
21941 (defun org-occur-link-in-agenda-files ()
21942 "Create a link and search for it in the agendas.
21943 The link is not stored in `org-stored-links', it is just created
21944 for the search purpose."
21945 (interactive)
21946 (let ((link (condition-case nil
21947 (org-store-link nil)
21948 (error "Unable to create a link to here"))))
21949 (org-occur-in-agenda-files (regexp-quote link))))
21951 (defun org-reverse-string (string)
21952 "Return the reverse of STRING."
21953 (apply 'string (reverse (string-to-list string))))
21955 (defun org-uniquify-alist (alist)
21956 "Merge elements of ALIST with the same key.
21958 For example, in this alist:
21960 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21961 => '((a 1 3) (b 2))
21963 merge (a 1) and (a 3) into (a 1 3).
21965 The function returns the new ALIST."
21966 (let (rtn)
21967 (mapc
21968 (lambda (e)
21969 (let (n)
21970 (if (not (assoc (car e) rtn))
21971 (push e rtn)
21972 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21973 (setq rtn (assq-delete-all (car e) rtn))
21974 (push n rtn))))
21975 alist)
21976 rtn))
21978 (defun org-delete-all (elts list)
21979 "Remove all elements in ELTS from LIST."
21980 (while elts
21981 (setq list (delete (pop elts) list)))
21982 list)
21984 (defun org-count (cl-item cl-seq)
21985 "Count the number of occurrences of ITEM in SEQ.
21986 Taken from `count' in cl-seq.el with all keyword arguments removed."
21987 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21988 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21989 (while (< cl-start cl-end)
21990 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21991 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21992 (setq cl-start (1+ cl-start)))
21993 cl-count))
21995 (defun org-remove-if (predicate seq)
21996 "Remove everything from SEQ that fulfills PREDICATE."
21997 (let (res e)
21998 (while seq
21999 (setq e (pop seq))
22000 (if (not (funcall predicate e)) (push e res)))
22001 (nreverse res)))
22003 (defun org-remove-if-not (predicate seq)
22004 "Remove everything from SEQ that does not fulfill PREDICATE."
22005 (let (res e)
22006 (while seq
22007 (setq e (pop seq))
22008 (if (funcall predicate e) (push e res)))
22009 (nreverse res)))
22011 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22012 "Reduce two-argument FUNCTION across SEQ.
22013 Taken from `reduce' in cl-seq.el with all keyword arguments but
22014 \":initial-value\" removed."
22015 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22016 (cadr (memq :initial-value cl-keys)))
22017 (cl-seq (pop cl-seq))
22018 (t (funcall cl-func)))))
22019 (while cl-seq
22020 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22021 cl-accum))
22023 (defun org-every (pred seq)
22024 "Return true if PREDICATE is true of every element of SEQ.
22025 Adapted from `every' in cl.el."
22026 (catch 'org-every
22027 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22030 (defun org-some (pred seq)
22031 "Return true if PREDICATE is true of any element of SEQ.
22032 Adapted from `some' in cl.el."
22033 (catch 'org-some
22034 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22035 nil))
22037 (defun org-back-over-empty-lines ()
22038 "Move backwards over whitespace, to the beginning of the first empty line.
22039 Returns the number of empty lines passed."
22040 (let ((pos (point)))
22041 (if (cdr (assoc 'heading org-blank-before-new-entry))
22042 (skip-chars-backward " \t\n\r")
22043 (unless (eobp)
22044 (forward-line -1)))
22045 (beginning-of-line 2)
22046 (goto-char (min (point) pos))
22047 (count-lines (point) pos)))
22049 (defun org-skip-whitespace ()
22050 (skip-chars-forward " \t\n\r"))
22052 (defun org-point-in-group (point group &optional context)
22053 "Check if POINT is in match-group GROUP.
22054 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22055 match. If the match group does not exist or point is not inside it,
22056 return nil."
22057 (and (match-beginning group)
22058 (>= point (match-beginning group))
22059 (<= point (match-end group))
22060 (if context
22061 (list context (match-beginning group) (match-end group))
22062 t)))
22064 (defun org-switch-to-buffer-other-window (&rest args)
22065 "Switch to buffer in a second window on the current frame.
22066 In particular, do not allow pop-up frames.
22067 Returns the newly created buffer."
22068 (org-no-popups
22069 (apply 'switch-to-buffer-other-window args)))
22071 (defun org-combine-plists (&rest plists)
22072 "Create a single property list from all plists in PLISTS.
22073 The process starts by copying the first list, and then setting properties
22074 from the other lists. Settings in the last list are the most significant
22075 ones and overrule settings in the other lists."
22076 (let ((rtn (copy-sequence (pop plists)))
22077 p v ls)
22078 (while plists
22079 (setq ls (pop plists))
22080 (while ls
22081 (setq p (pop ls) v (pop ls))
22082 (setq rtn (plist-put rtn p v))))
22083 rtn))
22085 (defun org-replace-escapes (string table)
22086 "Replace %-escapes in STRING with values in TABLE.
22087 TABLE is an association list with keys like \"%a\" and string values.
22088 The sequences in STRING may contain normal field width and padding information,
22089 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22090 so values can contain further %-escapes if they are define later in TABLE."
22091 (let ((tbl (copy-alist table))
22092 (case-fold-search nil)
22093 (pchg 0)
22094 e re rpl)
22095 (while (setq e (pop tbl))
22096 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22097 (when (and (cdr e) (string-match re (cdr e)))
22098 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22099 (safe "SREF"))
22100 (add-text-properties 0 3 (list 'sref sref) safe)
22101 (setcdr e (replace-match safe t t (cdr e)))))
22102 (while (string-match re string)
22103 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22104 (cdr e)))
22105 (setq string (replace-match rpl t t string))))
22106 (while (setq pchg (next-property-change pchg string))
22107 (let ((sref (get-text-property pchg 'sref string)))
22108 (when (and sref (string-match "SREF" string pchg))
22109 (setq string (replace-match sref t t string)))))
22110 string))
22112 (defun org-sublist (list start end)
22113 "Return a section of LIST, from START to END.
22114 Counting starts at 1."
22115 (let (rtn (c start))
22116 (setq list (nthcdr (1- start) list))
22117 (while (and list (<= c end))
22118 (push (pop list) rtn)
22119 (setq c (1+ c)))
22120 (nreverse rtn)))
22122 (defun org-find-base-buffer-visiting (file)
22123 "Like `find-buffer-visiting' but always return the base buffer and
22124 not an indirect buffer."
22125 (let ((buf (or (get-file-buffer file)
22126 (find-buffer-visiting file))))
22127 (if buf
22128 (or (buffer-base-buffer buf) buf)
22129 nil)))
22131 (defun org-image-file-name-regexp (&optional extensions)
22132 "Return regexp matching the file names of images.
22133 If EXTENSIONS is given, only match these."
22134 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22135 (image-file-name-regexp)
22136 (let ((image-file-name-extensions
22137 (or extensions
22138 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22139 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22140 (concat "\\."
22141 (regexp-opt (nconc (mapcar 'upcase
22142 image-file-name-extensions)
22143 image-file-name-extensions)
22145 "\\'"))))
22147 (defun org-file-image-p (file &optional extensions)
22148 "Return non-nil if FILE is an image."
22149 (save-match-data
22150 (string-match (org-image-file-name-regexp extensions) file)))
22152 (defun org-get-cursor-date (&optional with-time)
22153 "Return the date at cursor in as a time.
22154 This works in the calendar and in the agenda, anywhere else it just
22155 returns the current time.
22156 If WITH-TIME is non-nil, returns the time of the event at point (in
22157 the agenda) or the current time of the day."
22158 (let (date day defd tp tm hod mod)
22159 (when with-time
22160 (setq tp (get-text-property (point) 'time))
22161 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22162 (setq hod (string-to-number (match-string 1 tp))
22163 mod (string-to-number (match-string 2 tp))))
22164 (or tp (setq hod (nth 2 (decode-time (current-time)))
22165 mod (nth 1 (decode-time (current-time))))))
22166 (cond
22167 ((eq major-mode 'calendar-mode)
22168 (setq date (calendar-cursor-to-date)
22169 defd (encode-time 0 (or mod 0) (or hod 0)
22170 (nth 1 date) (nth 0 date) (nth 2 date))))
22171 ((eq major-mode 'org-agenda-mode)
22172 (setq day (get-text-property (point) 'day))
22173 (if day
22174 (setq date (calendar-gregorian-from-absolute day)
22175 defd (encode-time 0 (or mod 0) (or hod 0)
22176 (nth 1 date) (nth 0 date) (nth 2 date))))))
22177 (or defd (current-time))))
22179 (defun org-mark-subtree (&optional up)
22180 "Mark the current subtree.
22181 This puts point at the start of the current subtree, and mark at
22182 the end. If a numeric prefix UP is given, move up into the
22183 hierarchy of headlines by UP levels before marking the subtree."
22184 (interactive "P")
22185 (org-with-limited-levels
22186 (cond ((org-at-heading-p) (beginning-of-line))
22187 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22188 (t (outline-previous-visible-heading 1))))
22189 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22190 (if (org-called-interactively-p 'any)
22191 (call-interactively 'org-mark-element)
22192 (org-mark-element)))
22195 ;;; Indentation
22197 (defun org-indent-line ()
22198 "Indent line depending on context."
22199 (interactive)
22200 (let* ((pos (point))
22201 (itemp (org-at-item-p))
22202 (case-fold-search t)
22203 (org-drawer-regexp (or org-drawer-regexp "\000"))
22204 (inline-task-p (and (featurep 'org-inlinetask)
22205 (org-inlinetask-in-task-p)))
22206 (inline-re (and inline-task-p
22207 (org-inlinetask-outline-regexp)))
22208 column)
22209 (if (and orgstruct-is-++ (eq pos (point)))
22210 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22211 (indent-according-to-mode))
22212 (beginning-of-line 1)
22213 (cond
22214 ;; Headings
22215 ((looking-at org-outline-regexp) (setq column 0))
22216 ;; Footnote definition
22217 ((looking-at org-footnote-definition-re) (setq column 0))
22218 ;; Literal examples
22219 ((looking-at "[ \t]*:\\( \\|$\\)")
22220 (setq column (org-get-indentation))) ; do nothing
22221 ;; Lists
22222 ((ignore-errors (goto-char (org-in-item-p)))
22223 (setq column (if itemp
22224 (org-get-indentation)
22225 (org-list-item-body-column (point))))
22226 (goto-char pos))
22227 ;; Drawers
22228 ((and (looking-at "[ \t]*:END:")
22229 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22230 (save-excursion
22231 (goto-char (1- (match-beginning 1)))
22232 (setq column (current-column))))
22233 ;; Special blocks
22234 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22235 (save-excursion
22236 (re-search-backward
22237 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22238 (setq column (org-get-indentation (match-string 0))))
22239 ((and (not (looking-at "[ \t]*#\\+begin_"))
22240 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22241 (save-excursion
22242 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22243 (setq column
22244 (cond ((equal (downcase (match-string 1)) "src")
22245 ;; src blocks: let `org-edit-src-exit' handle them
22246 (org-get-indentation))
22247 ((equal (downcase (match-string 1)) "example")
22248 (max (org-get-indentation)
22249 (org-get-indentation (match-string 0))))
22251 (org-get-indentation (match-string 0))))))
22252 ;; This line has nothing special, look at the previous relevant
22253 ;; line to compute indentation
22255 (beginning-of-line 0)
22256 (while (and (not (bobp))
22257 (not (looking-at org-table-line-regexp))
22258 (not (looking-at org-drawer-regexp))
22259 ;; When point started in an inline task, do not move
22260 ;; above task starting line.
22261 (not (and inline-task-p (looking-at inline-re)))
22262 ;; Skip drawers, blocks, empty lines, verbatim,
22263 ;; comments, tables, footnotes definitions, lists,
22264 ;; inline tasks.
22265 (or (and (looking-at "[ \t]*:END:")
22266 (re-search-backward org-drawer-regexp nil t))
22267 (and (looking-at "[ \t]*#\\+end_")
22268 (re-search-backward "[ \t]*#\\+begin_"nil t))
22269 (looking-at "[ \t]*[\n:#|]")
22270 (looking-at org-footnote-definition-re)
22271 (and (not inline-task-p)
22272 (featurep 'org-inlinetask)
22273 (org-inlinetask-in-task-p)
22274 (or (org-inlinetask-goto-beginning) t))))
22275 (beginning-of-line 0))
22276 (cond
22277 ;; There was a list item above.
22278 ((ignore-errors (goto-char (org-in-item-p)))
22279 (goto-char (org-list-get-top-point (org-list-struct)))
22280 (setq column (org-get-indentation)))
22281 ;; There was an heading above.
22282 ((looking-at "\\*+[ \t]+")
22283 (if (not org-adapt-indentation)
22284 (setq column 0)
22285 (goto-char (match-end 0))
22286 (setq column (current-column))))
22287 ;; A drawer had started and is unfinished
22288 ((looking-at org-drawer-regexp)
22289 (goto-char (1- (match-beginning 1)))
22290 (setq column (current-column)))
22291 ;; Else, nothing noticeable found: get indentation and go on.
22292 (t (setq column (org-get-indentation))))))
22293 ;; Now apply indentation and move cursor accordingly
22294 (goto-char pos)
22295 (if (<= (current-column) (current-indentation))
22296 (org-indent-line-to column)
22297 (save-excursion (org-indent-line-to column)))
22298 ;; Special polishing for properties, see `org-property-format'
22299 (setq column (current-column))
22300 (beginning-of-line 1)
22301 (if (looking-at org-property-re)
22302 (replace-match (concat (match-string 4)
22303 (format org-property-format
22304 (match-string 1) (match-string 3)))
22305 t t))
22306 (org-move-to-column column))))
22308 (defun org-indent-drawer ()
22309 "Indent the drawer at point."
22310 (interactive)
22311 (let ((p (point))
22312 (e (and (save-excursion (re-search-forward ":END:" nil t))
22313 (match-end 0)))
22314 (folded
22315 (save-excursion
22316 (end-of-line)
22317 (when (overlays-at (point))
22318 (member 'invisible (overlay-properties
22319 (car (overlays-at (point)))))))))
22320 (when folded (org-cycle))
22321 (indent-for-tab-command)
22322 (while (and (move-beginning-of-line 2) (< (point) e))
22323 (indent-for-tab-command))
22324 (goto-char p)
22325 (when folded (org-cycle)))
22326 (message "Drawer at point indented"))
22328 (defun org-indent-block ()
22329 "Indent the block at point."
22330 (interactive)
22331 (let ((p (point))
22332 (case-fold-search t)
22333 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22334 (match-end 0)))
22335 (folded
22336 (save-excursion
22337 (end-of-line)
22338 (when (overlays-at (point))
22339 (member 'invisible (overlay-properties
22340 (car (overlays-at (point)))))))))
22341 (when folded (org-cycle))
22342 (indent-for-tab-command)
22343 (while (and (move-beginning-of-line 2) (< (point) e))
22344 (indent-for-tab-command))
22345 (goto-char p)
22346 (when folded (org-cycle)))
22347 (message "Block at point indented"))
22349 (defun org-indent-region (start end)
22350 "Indent region."
22351 (interactive "r")
22352 (save-excursion
22353 (let ((line-end (org-current-line end)))
22354 (goto-char start)
22355 (while (< (org-current-line) line-end)
22356 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22357 (t (call-interactively 'org-indent-line)))
22358 (move-beginning-of-line 2)))))
22361 ;;; Filling
22363 ;; We use our own fill-paragraph and auto-fill functions.
22365 ;; `org-fill-paragraph' relies on adaptive filling and context
22366 ;; checking. Appropriate `fill-prefix' is computed with
22367 ;; `org-adaptive-fill-function'.
22369 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22370 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22371 ;; `org-adaptive-fill-function' value. Internally,
22372 ;; `org-comment-line-break-function' breaks the line.
22374 ;; `org-setup-filling' installs filling and auto-filling related
22375 ;; variables during `org-mode' initialization.
22377 (defvar org-element-paragraph-separate) ; org-element.el
22378 (defun org-setup-filling ()
22379 (require 'org-element)
22380 ;; Prevent auto-fill from inserting unwanted new items.
22381 (when (boundp 'fill-nobreak-predicate)
22382 (org-set-local
22383 'fill-nobreak-predicate
22384 (org-uniquify
22385 (append fill-nobreak-predicate
22386 '(org-fill-line-break-nobreak-p
22387 org-fill-paragraph-with-timestamp-nobreak-p)))))
22388 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22389 (org-set-local 'paragraph-start paragraph-ending)
22390 (org-set-local 'paragraph-separate paragraph-ending))
22391 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22392 (org-set-local 'auto-fill-inhibit-regexp nil)
22393 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22394 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22395 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22397 (defun org-fill-line-break-nobreak-p ()
22398 "Non-nil when a new line at point would create an Org line break."
22399 (save-excursion
22400 (skip-chars-backward "[ \t]")
22401 (skip-chars-backward "\\\\")
22402 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22404 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22405 "Non-nil when a new line at point would split a timestamp."
22406 (and (org-at-timestamp-p t)
22407 (not (looking-at org-ts-regexp-both))))
22409 (declare-function message-in-body-p "message" ())
22410 (defvar orgtbl-line-start-regexp) ; From org-table.el
22411 (defun org-adaptive-fill-function ()
22412 "Compute a fill prefix for the current line.
22413 Return fill prefix, as a string, or nil if current line isn't
22414 meant to be filled. For convenience, if `adaptive-fill-regexp'
22415 matches in paragraphs or comments, use it."
22416 (catch 'exit
22417 (when (derived-mode-p 'message-mode)
22418 (save-excursion
22419 (beginning-of-line)
22420 (cond ((or (not (message-in-body-p))
22421 (looking-at orgtbl-line-start-regexp))
22422 (throw 'exit nil))
22423 ((looking-at message-cite-prefix-regexp)
22424 (throw 'exit (match-string-no-properties 0)))
22425 ((looking-at org-outline-regexp)
22426 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22427 (org-with-wide-buffer
22428 (let* ((p (line-beginning-position))
22429 (element (save-excursion
22430 (beginning-of-line)
22431 (or (ignore-errors (org-element-at-point))
22432 (user-error "An element cannot be parsed line %d"
22433 (line-number-at-pos (point))))))
22434 (type (org-element-type element))
22435 (post-affiliated (org-element-property :post-affiliated element)))
22436 (unless (and post-affiliated (< p post-affiliated))
22437 (case type
22438 (comment
22439 (save-excursion
22440 (beginning-of-line)
22441 (looking-at "[ \t]*")
22442 (concat (match-string 0) "# ")))
22443 (footnote-definition "")
22444 ((item plain-list)
22445 (make-string (org-list-item-body-column
22446 (or post-affiliated
22447 (org-element-property :begin element)))
22448 ? ))
22449 (paragraph
22450 ;; Fill prefix is usually the same as the current line,
22451 ;; unless the paragraph is at the beginning of an item.
22452 (let ((parent (org-element-property :parent element)))
22453 (save-excursion
22454 (beginning-of-line)
22455 (cond ((eq (org-element-type parent) 'item)
22456 (make-string (org-list-item-body-column
22457 (org-element-property :begin parent))
22458 ? ))
22459 ((and adaptive-fill-regexp
22460 ;; Locally disable
22461 ;; `adaptive-fill-function' to let
22462 ;; `fill-context-prefix' handle
22463 ;; `adaptive-fill-regexp' variable.
22464 (let (adaptive-fill-function)
22465 (fill-context-prefix
22466 post-affiliated
22467 (org-element-property :end element)))))
22468 ((looking-at "[ \t]+") (match-string 0))
22469 (t "")))))
22470 (comment-block
22471 ;; Only fill contents if P is within block boundaries.
22472 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22473 (forward-line)
22474 (point)))
22475 (cend (save-excursion
22476 (goto-char (org-element-property :end element))
22477 (skip-chars-backward " \r\t\n")
22478 (line-beginning-position))))
22479 (when (and (>= p cbeg) (< p cend))
22480 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22481 (match-string 0)
22482 ""))))))))))
22484 (declare-function message-goto-body "message" ())
22485 (defvar message-cite-prefix-regexp) ; From message.el
22486 (defun org-fill-paragraph (&optional justify)
22487 "Fill element at point, when applicable.
22489 This function only applies to comment blocks, comments, example
22490 blocks and paragraphs. Also, as a special case, re-align table
22491 when point is at one.
22493 If JUSTIFY is non-nil (interactively, with prefix argument),
22494 justify as well. If `sentence-end-double-space' is non-nil, then
22495 period followed by one space does not end a sentence, so don't
22496 break a line there. The variable `fill-column' controls the
22497 width for filling.
22499 For convenience, when point is at a plain list, an item or
22500 a footnote definition, try to fill the first paragraph within."
22501 (interactive)
22502 (if (and (derived-mode-p 'message-mode)
22503 (or (not (message-in-body-p))
22504 (save-excursion (move-beginning-of-line 1)
22505 (looking-at message-cite-prefix-regexp))))
22506 ;; First ensure filling is correct in message-mode.
22507 (let ((fill-paragraph-function
22508 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22509 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22510 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22511 (paragraph-separate
22512 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22513 (fill-paragraph nil))
22514 (with-syntax-table org-mode-transpose-word-syntax-table
22515 ;; Move to end of line in order to get the first paragraph
22516 ;; within a plain list or a footnote definition.
22517 (let ((element (save-excursion
22518 (end-of-line)
22519 (or (ignore-errors (org-element-at-point))
22520 (user-error "An element cannot be parsed line %d"
22521 (line-number-at-pos (point)))))))
22522 ;; First check if point is in a blank line at the beginning of
22523 ;; the buffer. In that case, ignore filling.
22524 (case (org-element-type element)
22525 ;; Use major mode filling function is src blocks.
22526 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22527 ;; Align Org tables, leave table.el tables as-is.
22528 (table-row (org-table-align) t)
22529 (table
22530 (when (eq (org-element-property :type element) 'org)
22531 (save-excursion
22532 (goto-char (org-element-property :post-affiliated element))
22533 (org-table-align)))
22535 (paragraph
22536 ;; Paragraphs may contain `line-break' type objects.
22537 (let ((beg (max (point-min)
22538 (org-element-property :contents-begin element)))
22539 (end (min (point-max)
22540 (org-element-property :contents-end element))))
22541 ;; Do nothing if point is at an affiliated keyword.
22542 (if (< (line-end-position) beg) t
22543 (when (derived-mode-p 'message-mode)
22544 ;; In `message-mode', do not fill following citation
22545 ;; in current paragraph nor text before message body.
22546 (let ((body-start (save-excursion (message-goto-body))))
22547 (when body-start (setq beg (max body-start beg))))
22548 (when (save-excursion
22549 (re-search-forward
22550 (concat "^" message-cite-prefix-regexp) end t))
22551 (setq end (match-beginning 0))))
22552 ;; Fill paragraph, taking line breaks into account.
22553 ;; For that, slice the paragraph using line breaks as
22554 ;; separators, and fill the parts in reverse order to
22555 ;; avoid messing with markers.
22556 (save-excursion
22557 (goto-char end)
22558 (mapc
22559 (lambda (pos)
22560 (fill-region-as-paragraph pos (point) justify)
22561 (goto-char pos))
22562 ;; Find the list of ending positions for line breaks
22563 ;; in the current paragraph. Add paragraph
22564 ;; beginning to include first slice.
22565 (nreverse
22566 (cons beg
22567 (org-element-map
22568 (org-element--parse-objects
22569 beg end nil (org-element-restriction 'paragraph))
22570 'line-break
22571 (lambda (lb) (org-element-property :end lb)))))))
22572 t)))
22573 ;; Contents of `comment-block' type elements should be
22574 ;; filled as plain text, but only if point is within block
22575 ;; markers.
22576 (comment-block
22577 (let* ((case-fold-search t)
22578 (beg (save-excursion
22579 (goto-char (org-element-property :begin element))
22580 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22581 (forward-line)
22582 (point)))
22583 (end (save-excursion
22584 (goto-char (org-element-property :end element))
22585 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22586 (line-beginning-position))))
22587 (if (or (< (point) beg) (> (point) end)) t
22588 (fill-region-as-paragraph
22589 (save-excursion (end-of-line)
22590 (re-search-backward "^[ \t]*$" beg 'move)
22591 (line-beginning-position))
22592 (save-excursion (beginning-of-line)
22593 (re-search-forward "^[ \t]*$" end 'move)
22594 (line-beginning-position))
22595 justify))))
22596 ;; Fill comments.
22597 (comment
22598 (let ((begin (org-element-property :post-affiliated element))
22599 (end (org-element-property :end element)))
22600 (when (and (>= (point) begin) (<= (point) end))
22601 (let ((begin (save-excursion
22602 (end-of-line)
22603 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22604 (progn (forward-line) (point))
22605 begin)))
22606 (end (save-excursion
22607 (end-of-line)
22608 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22609 (1- (line-beginning-position))
22610 (skip-chars-backward " \r\t\n")
22611 (line-end-position)))))
22612 ;; Do not fill comments when at a blank line.
22613 (when (> end begin)
22614 (let ((fill-prefix
22615 (save-excursion
22616 (beginning-of-line)
22617 (looking-at "[ \t]*#")
22618 (let ((comment-prefix (match-string 0)))
22619 (goto-char (match-end 0))
22620 (if (looking-at adaptive-fill-regexp)
22621 (concat comment-prefix (match-string 0))
22622 (concat comment-prefix " "))))))
22623 (save-excursion
22624 (fill-region-as-paragraph begin end justify))))))
22626 ;; Ignore every other element.
22627 (otherwise t))))))
22629 (defun org-auto-fill-function ()
22630 "Auto-fill function."
22631 ;; Check if auto-filling is meaningful.
22632 (let ((fc (current-fill-column)))
22633 (when (and fc (> (current-column) fc))
22634 (let* ((fill-prefix (org-adaptive-fill-function))
22635 ;; Enforce empty fill prefix, if required. Otherwise, it
22636 ;; will be computed again.
22637 (adaptive-fill-mode (not (equal fill-prefix ""))))
22638 (when fill-prefix (do-auto-fill))))))
22640 (defun org-comment-line-break-function (&optional soft)
22641 "Break line at point and indent, continuing comment if within one.
22642 The inserted newline is marked hard if variable
22643 `use-hard-newlines' is true, unless optional argument SOFT is
22644 non-nil."
22645 (if soft (insert-and-inherit ?\n) (newline 1))
22646 (save-excursion (forward-char -1) (delete-horizontal-space))
22647 (delete-horizontal-space)
22648 (indent-to-left-margin)
22649 (insert-before-markers-and-inherit fill-prefix))
22652 ;;; Fixed Width Areas
22654 (defun org-toggle-fixed-width ()
22655 "Toggle fixed-width markup.
22657 Add or remove fixed-width markup on current line, whenever it
22658 makes sense. Return an error otherwise.
22660 If a region is active and if it contains only fixed-width areas
22661 or blank lines, remove all fixed-width markup in it. If the
22662 region contains anything else, convert all non-fixed-width lines
22663 to fixed-width ones.
22665 Blank lines at the end of the region are ignored unless the
22666 region only contains such lines."
22667 (interactive)
22668 (if (not (org-region-active-p))
22669 ;; No region:
22671 ;; Remove fixed width marker only in a fixed-with element.
22673 ;; Add fixed width maker in paragraphs, in blank lines after
22674 ;; elements or at the beginning of a headline or an inlinetask,
22675 ;; and before any one-line elements (e.g., a clock).
22676 (progn
22677 (beginning-of-line)
22678 (let* ((element (org-element-at-point))
22679 (type (org-element-type element)))
22680 (cond
22681 ((and (eq type 'fixed-width)
22682 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22683 (replace-match
22684 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22685 ((and (memq type '(babel-call clock comment diary-sexp headline
22686 horizontal-rule keyword paragraph
22687 planning))
22688 (or (not (org-element-property :post-affiliated element))
22689 (<= (org-element-property :post-affiliated element)
22690 (point))))
22691 (skip-chars-forward " \t")
22692 (insert ": "))
22693 ((and (org-looking-at-p "[ \t]*$")
22694 (or (eq type 'inlinetask)
22695 (save-excursion
22696 (skip-chars-forward " \r\t\n")
22697 (<= (org-element-property :end element) (point)))))
22698 (delete-region (point) (line-end-position))
22699 (org-indent-line)
22700 (insert ": "))
22701 (t (user-error "Cannot insert a fixed-width line here")))))
22702 ;; Region active.
22703 (let* ((begin (save-excursion
22704 (goto-char (region-beginning))
22705 (line-beginning-position)))
22706 (end (copy-marker
22707 (save-excursion
22708 (goto-char (region-end))
22709 (unless (eolp) (beginning-of-line))
22710 (if (save-excursion (re-search-backward "\\S-" begin t))
22711 (progn (skip-chars-backward " \r\t\n") (point))
22712 (point)))))
22713 (all-fixed-width-p
22714 (catch 'not-all-p
22715 (save-excursion
22716 (goto-char begin)
22717 (skip-chars-forward " \r\t\n")
22718 (when (eobp) (throw 'not-all-p nil))
22719 (while (< (point) end)
22720 (let ((element (org-element-at-point)))
22721 (if (eq (org-element-type element) 'fixed-width)
22722 (goto-char (org-element-property :end element))
22723 (throw 'not-all-p nil))))
22724 t))))
22725 (if all-fixed-width-p
22726 (save-excursion
22727 (goto-char begin)
22728 (while (< (point) end)
22729 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22730 (replace-match
22731 "" nil nil nil
22732 (if (= (line-end-position) (match-end 0)) 0 1)))
22733 (forward-line)))
22734 (let ((min-ind (point-max)))
22735 ;; Find minimum indentation across all lines.
22736 (save-excursion
22737 (goto-char begin)
22738 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22739 (setq min-ind 0)
22740 (catch 'zerop
22741 (while (< (point) end)
22742 (unless (org-looking-at-p "[ \t]*$")
22743 (let ((ind (org-get-indentation)))
22744 (setq min-ind (min min-ind ind))
22745 (when (zerop ind) (throw 'zerop t))))
22746 (forward-line)))))
22747 ;; Loop over all lines and add fixed-width markup everywhere
22748 ;; but in fixed-width lines.
22749 (save-excursion
22750 (goto-char begin)
22751 (while (< (point) end)
22752 (cond
22753 ((org-at-heading-p)
22754 (insert ": ")
22755 (forward-line)
22756 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
22757 (insert ":")
22758 (forward-line)))
22759 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
22760 (let* ((element (org-element-at-point))
22761 (element-end (org-element-property :end element)))
22762 (if (eq (org-element-type element) 'fixed-width)
22763 (progn (goto-char element-end)
22764 (skip-chars-backward " \r\t\n")
22765 (forward-line))
22766 (let ((limit (min end element-end)))
22767 (while (< (point) limit)
22768 (org-move-to-column min-ind t)
22769 (insert ": ")
22770 (forward-line))))))
22772 (org-move-to-column min-ind t)
22773 (insert ": ")
22774 (forward-line)))))))
22775 (set-marker end nil))))
22778 ;;; Comments
22780 ;; Org comments syntax is quite complex. It requires the entire line
22781 ;; to be just a comment. Also, even with the right syntax at the
22782 ;; beginning of line, some some elements (i.e. verse-block or
22783 ;; example-block) don't accept comments. Usual Emacs comment commands
22784 ;; cannot cope with those requirements. Therefore, Org replaces them.
22786 ;; Org still relies on `comment-dwim', but cannot trust
22787 ;; `comment-only-p'. So, `comment-region-function' and
22788 ;; `uncomment-region-function' both point
22789 ;; to`org-comment-or-uncomment-region'. Eventually,
22790 ;; `org-insert-comment' takes care of insertion of comments at the
22791 ;; beginning of line.
22793 ;; `org-setup-comments-handling' install comments related variables
22794 ;; during `org-mode' initialization.
22796 (defun org-setup-comments-handling ()
22797 (interactive)
22798 (org-set-local 'comment-use-syntax nil)
22799 (org-set-local 'comment-start "# ")
22800 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22801 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22802 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22803 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22805 (defun org-insert-comment ()
22806 "Insert an empty comment above current line.
22807 If the line is empty, insert comment at its beginning. When
22808 point is within a source block, comment according to the related
22809 major mode."
22810 (if (let ((element (org-element-at-point)))
22811 (and (eq (org-element-type element) 'src-block)
22812 (< (save-excursion
22813 (goto-char (org-element-property :post-affiliated element))
22814 (line-end-position))
22815 (point))
22816 (> (save-excursion
22817 (goto-char (org-element-property :end element))
22818 (skip-chars-backward " \r\t\n")
22819 (line-beginning-position))
22820 (point))))
22821 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22822 (beginning-of-line)
22823 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22824 (open-line 1))
22825 (org-indent-line)
22826 (insert "# ")))
22828 (defvar comment-empty-lines) ; From newcomment.el.
22829 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22830 "Comment or uncomment each non-blank line in the region.
22831 Uncomment each non-blank line between BEG and END if it only
22832 contains commented lines. Otherwise, comment them. If region is
22833 strictly within a source block, use appropriate comment syntax."
22834 (if (let ((element (org-element-at-point)))
22835 (and (eq (org-element-type element) 'src-block)
22836 (< (save-excursion
22837 (goto-char (org-element-property :post-affiliated element))
22838 (line-end-position))
22839 beg)
22840 (>= (save-excursion
22841 (goto-char (org-element-property :end element))
22842 (skip-chars-backward " \r\t\n")
22843 (line-beginning-position))
22844 end)))
22845 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22846 (save-restriction
22847 ;; Restrict region
22848 (narrow-to-region (save-excursion (goto-char beg)
22849 (skip-chars-forward " \r\t\n" end)
22850 (line-beginning-position))
22851 (save-excursion (goto-char end)
22852 (skip-chars-backward " \r\t\n" beg)
22853 (line-end-position)))
22854 (let ((uncommentp
22855 ;; UNCOMMENTP is non-nil when every non blank line between
22856 ;; BEG and END is a comment.
22857 (save-excursion
22858 (goto-char (point-min))
22859 (while (and (not (eobp))
22860 (let ((element (org-element-at-point)))
22861 (and (eq (org-element-type element) 'comment)
22862 (goto-char (min (point-max)
22863 (org-element-property
22864 :end element)))))))
22865 (eobp))))
22866 (if uncommentp
22867 ;; Only blank lines and comments in region: uncomment it.
22868 (save-excursion
22869 (goto-char (point-min))
22870 (while (not (eobp))
22871 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22872 (replace-match "" nil nil nil 1))
22873 (forward-line)))
22874 ;; Comment each line in region.
22875 (let ((min-indent (point-max)))
22876 ;; First find the minimum indentation across all lines.
22877 (save-excursion
22878 (goto-char (point-min))
22879 (while (and (not (eobp)) (not (zerop min-indent)))
22880 (unless (looking-at "[ \t]*$")
22881 (setq min-indent (min min-indent (current-indentation))))
22882 (forward-line)))
22883 ;; Then loop over all lines.
22884 (save-excursion
22885 (goto-char (point-min))
22886 (while (not (eobp))
22887 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22888 ;; Don't get fooled by invisible text (e.g. link path)
22889 ;; when moving to column MIN-INDENT.
22890 (let ((buffer-invisibility-spec nil))
22891 (org-move-to-column min-indent t))
22892 (insert comment-start))
22893 (forward-line)))))))))
22895 (defun org-comment-dwim (arg)
22896 (interactive "*P")
22897 "Call `comment-dwim' within a source edit buffer if needed."
22898 (if (org-in-src-block-p)
22899 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22900 (call-interactively #'comment-dwim)))
22903 ;;; Planning
22905 ;; This section contains tools to operate on timestamp objects, as
22906 ;; returned by, e.g. `org-element-context'.
22908 (defun org-timestamp-has-time-p (timestamp)
22909 "Non-nil when TIMESTAMP has a time specified."
22910 (org-element-property :hour-start timestamp))
22912 (defun org-timestamp-format (timestamp format &optional end utc)
22913 "Format a TIMESTAMP element into a string.
22915 FORMAT is a format specifier to be passed to
22916 `format-time-string'.
22918 When optional argument END is non-nil, use end of date-range or
22919 time-range, if possible.
22921 When optional argument UTC is non-nil, time will be expressed as
22922 Universal Time."
22923 (format-time-string
22924 format
22925 (apply 'encode-time
22926 (cons 0
22927 (mapcar
22928 (lambda (prop) (or (org-element-property prop timestamp) 0))
22929 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22930 '(:minute-start :hour-start :day-start :month-start
22931 :year-start)))))
22932 utc))
22934 (defun org-timestamp-split-range (timestamp &optional end)
22935 "Extract a timestamp object from a date or time range.
22937 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22938 the end of the range. Otherwise, extract its start.
22940 Return a new timestamp object sharing the same parent as
22941 TIMESTAMP."
22942 (let ((type (org-element-property :type timestamp)))
22943 (if (memq type '(active inactive diary)) timestamp
22944 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22945 ;; Set new type.
22946 (org-element-put-property
22947 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22948 ;; Copy start properties over end properties if END is
22949 ;; non-nil. Otherwise, copy end properties over `start' ones.
22950 (let ((p-alist '((:minute-start . :minute-end)
22951 (:hour-start . :hour-end)
22952 (:day-start . :day-end)
22953 (:month-start . :month-end)
22954 (:year-start . :year-end))))
22955 (dolist (p-cell p-alist)
22956 (org-element-put-property
22957 split-ts
22958 (funcall (if end 'car 'cdr) p-cell)
22959 (org-element-property
22960 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22961 ;; Eventually refresh `:raw-value'.
22962 (org-element-put-property split-ts :raw-value nil)
22963 (org-element-put-property
22964 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22966 (defun org-timestamp-translate (timestamp &optional boundary)
22967 "Apply `org-translate-time' on a TIMESTAMP object.
22968 When optional argument BOUNDARY is non-nil, it is either the
22969 symbol `start' or `end'. In this case, only translate the
22970 starting or ending part of TIMESTAMP if it is a date or time
22971 range. Otherwise, translate both parts."
22972 (if (and (not boundary)
22973 (memq (org-element-property :type timestamp)
22974 '(active-range inactive-range)))
22975 (concat
22976 (org-translate-time
22977 (org-element-property :raw-value
22978 (org-timestamp-split-range timestamp)))
22979 "--"
22980 (org-translate-time
22981 (org-element-property :raw-value
22982 (org-timestamp-split-range timestamp t))))
22983 (org-translate-time
22984 (org-element-property
22985 :raw-value
22986 (if (not boundary) timestamp
22987 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22991 ;;; Other stuff.
22993 (defun org-reftex-citation ()
22994 "Use reftex-citation to insert a citation into the buffer.
22995 This looks for a line like
22997 #+BIBLIOGRAPHY: foo plain option:-d
22999 and derives from it that foo.bib is the bibliography file relevant
23000 for this document. It then installs the necessary environment for RefTeX
23001 to work in this buffer and calls `reftex-citation' to insert a citation
23002 into the buffer.
23004 Export of such citations to both LaTeX and HTML is handled by the contributed
23005 package ox-bibtex by Taru Karttunen."
23006 (interactive)
23007 (let ((reftex-docstruct-symbol 'rds)
23008 (reftex-cite-format "\\cite{%l}")
23009 rds bib)
23010 (save-excursion
23011 (save-restriction
23012 (widen)
23013 (let ((case-fold-search t)
23014 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23015 (if (not (save-excursion
23016 (or (re-search-forward re nil t)
23017 (re-search-backward re nil t))))
23018 (user-error "No bibliography defined in file")
23019 (setq bib (concat (match-string 1) ".bib")
23020 rds (list (list 'bib bib)))))))
23021 (call-interactively 'reftex-citation)))
23023 ;;;; Functions extending outline functionality
23025 (defun org-beginning-of-line (&optional arg)
23026 "Go to the beginning of the current line. If that is invisible, continue
23027 to a visible line beginning. This makes the function of C-a more intuitive.
23028 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23029 first attempt, and only move to after the tags when the cursor is already
23030 beyond the end of the headline."
23031 (interactive "P")
23032 (let ((pos (point))
23033 (special (if (consp org-special-ctrl-a/e)
23034 (car org-special-ctrl-a/e)
23035 org-special-ctrl-a/e))
23036 deactivate-mark refpos)
23037 (if (org-bound-and-true-p visual-line-mode)
23038 (beginning-of-visual-line 1)
23039 (beginning-of-line 1))
23040 (if (and arg (fboundp 'move-beginning-of-line))
23041 (call-interactively 'move-beginning-of-line)
23042 (if (bobp)
23044 (backward-char 1)
23045 (if (org-truely-invisible-p)
23046 (while (and (not (bobp)) (org-truely-invisible-p))
23047 (backward-char 1)
23048 (beginning-of-line 1))
23049 (forward-char 1))))
23050 (when special
23051 (cond
23052 ((and (looking-at org-complex-heading-regexp)
23053 (= (char-after (match-end 1)) ?\ ))
23054 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23055 (point-at-eol)))
23056 (goto-char
23057 (if (eq special t)
23058 (cond ((> pos refpos) refpos)
23059 ((= pos (point)) refpos)
23060 (t (point)))
23061 (cond ((> pos (point)) (point))
23062 ((not (eq last-command this-command)) (point))
23063 (t refpos)))))
23064 ((org-at-item-p)
23065 ;; Being at an item and not looking at an the item means point
23066 ;; was previously moved to beginning of a visual line, which
23067 ;; doesn't contain the item. Therefore, do nothing special,
23068 ;; just stay here.
23069 (when (looking-at org-list-full-item-re)
23070 ;; Set special position at first white space character after
23071 ;; bullet, and check-box, if any.
23072 (let ((after-bullet
23073 (let ((box (match-end 3)))
23074 (if (not box) (match-end 1)
23075 (let ((after (char-after box)))
23076 (if (and after (= after ? )) (1+ box) box))))))
23077 ;; Special case: Move point to special position when
23078 ;; currently after it or at beginning of line.
23079 (if (eq special t)
23080 (when (or (> pos after-bullet) (= (point) pos))
23081 (goto-char after-bullet))
23082 ;; Reversed case: Move point to special position when
23083 ;; point was already at beginning of line and command is
23084 ;; repeated.
23085 (when (and (= (point) pos) (eq last-command this-command))
23086 (goto-char after-bullet))))))))
23087 (org-no-warnings
23088 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23089 (setq disable-point-adjustment
23090 (or (not (invisible-p (point)))
23091 (not (invisible-p (max (point-min) (1- (point))))))))
23093 (defun org-end-of-line (&optional arg)
23094 "Go to the end of the line.
23095 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23096 tags on the first attempt, and only move to after the tags when
23097 the cursor is already beyond the end of the headline."
23098 (interactive "P")
23099 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23100 org-special-ctrl-a/e))
23101 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23102 'end-of-visual-line)
23103 ((fboundp 'move-end-of-line) 'move-end-of-line)
23104 (t 'end-of-line)))
23105 deactivate-mark)
23106 (if (or (not special) arg) (call-interactively move-fun)
23107 (let* ((element (save-excursion (beginning-of-line)
23108 (org-element-at-point)))
23109 (type (org-element-type element)))
23110 (cond
23111 ((memq type '(headline inlinetask))
23112 (let ((pos (point)))
23113 (beginning-of-line 1)
23114 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23115 (if (eq special t)
23116 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23117 (goto-char (match-beginning 1))
23118 (goto-char (match-end 0)))
23119 (if (or (< pos (match-end 0))
23120 (not (eq this-command last-command)))
23121 (goto-char (match-end 0))
23122 (goto-char (match-beginning 1))))
23123 (call-interactively move-fun))))
23124 ((outline-invisible-p (line-end-position))
23125 ;; If element is hidden, `move-end-of-line' would put point
23126 ;; after it. Use `end-of-line' to stay on current line.
23127 (call-interactively 'end-of-line))
23128 (t (call-interactively move-fun)))))
23129 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23130 (setq disable-point-adjustment
23131 (or (not (invisible-p (point)))
23132 (not (invisible-p (max (point-min) (1- (point))))))))
23134 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23135 (define-key org-mode-map "\C-e" 'org-end-of-line)
23137 (defun org-backward-sentence (&optional arg)
23138 "Go to beginning of sentence, or beginning of table field.
23139 This will call `backward-sentence' or `org-table-beginning-of-field',
23140 depending on context."
23141 (interactive "P")
23142 (cond
23143 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23144 (t (call-interactively 'backward-sentence))))
23146 (defun org-forward-sentence (&optional arg)
23147 "Go to end of sentence, or end of table field.
23148 This will call `forward-sentence' or `org-table-end-of-field',
23149 depending on context."
23150 (interactive "P")
23151 (cond
23152 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23153 (t (call-interactively 'forward-sentence))))
23155 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23156 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23158 (defun org-kill-line (&optional arg)
23159 "Kill line, to tags or end of line."
23160 (interactive "P")
23161 (cond
23162 ((or (not org-special-ctrl-k)
23163 (bolp)
23164 (not (org-at-heading-p)))
23165 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23166 org-ctrl-k-protect-subtree)
23167 (if (or (eq org-ctrl-k-protect-subtree 'error)
23168 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23169 (user-error "C-k aborted as it would kill a hidden subtree")))
23170 (call-interactively
23171 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23172 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23173 (kill-region (point) (match-beginning 1))
23174 (org-set-tags nil t))
23175 (t (kill-region (point) (point-at-eol)))))
23177 (define-key org-mode-map "\C-k" 'org-kill-line)
23179 (defun org-yank (&optional arg)
23180 "Yank. If the kill is a subtree, treat it specially.
23181 This command will look at the current kill and check if is a single
23182 subtree, or a series of subtrees[1]. If it passes the test, and if the
23183 cursor is at the beginning of a line or after the stars of a currently
23184 empty headline, then the yank is handled specially. How exactly depends
23185 on the value of the following variables, both set by default.
23187 org-yank-folded-subtrees
23188 When set, the subtree(s) will be folded after insertion, but only
23189 if doing so would now swallow text after the yanked text.
23191 org-yank-adjusted-subtrees
23192 When set, the subtree will be promoted or demoted in order to
23193 fit into the local outline tree structure, which means that the level
23194 will be adjusted so that it becomes the smaller one of the two
23195 *visible* surrounding headings.
23197 Any prefix to this command will cause `yank' to be called directly with
23198 no special treatment. In particular, a simple \\[universal-argument] prefix \
23199 will just
23200 plainly yank the text as it is.
23202 \[1] The test checks if the first non-white line is a heading
23203 and if there are no other headings with fewer stars."
23204 (interactive "P")
23205 (org-yank-generic 'yank arg))
23207 (defun org-yank-generic (command arg)
23208 "Perform some yank-like command.
23210 This function implements the behavior described in the `org-yank'
23211 documentation. However, it has been generalized to work for any
23212 interactive command with similar behavior."
23214 ;; pretend to be command COMMAND
23215 (setq this-command command)
23217 (if arg
23218 (call-interactively command)
23220 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23221 (and (org-kill-is-subtree-p)
23222 (or (bolp)
23223 (and (looking-at "[ \t]*$")
23224 (string-match
23225 "\\`\\*+\\'"
23226 (buffer-substring (point-at-bol) (point)))))))
23227 swallowp)
23228 (cond
23229 ((and subtreep org-yank-folded-subtrees)
23230 (let ((beg (point))
23231 end)
23232 (if (and subtreep org-yank-adjusted-subtrees)
23233 (org-paste-subtree nil nil 'for-yank)
23234 (call-interactively command))
23236 (setq end (point))
23237 (goto-char beg)
23238 (when (and (bolp) subtreep
23239 (not (setq swallowp
23240 (org-yank-folding-would-swallow-text beg end))))
23241 (org-with-limited-levels
23242 (or (looking-at org-outline-regexp)
23243 (re-search-forward org-outline-regexp-bol end t))
23244 (while (and (< (point) end) (looking-at org-outline-regexp))
23245 (hide-subtree)
23246 (org-cycle-show-empty-lines 'folded)
23247 (condition-case nil
23248 (outline-forward-same-level 1)
23249 (error (goto-char end))))))
23250 (when swallowp
23251 (message
23252 "Inserted text not folded because that would swallow text"))
23254 (goto-char end)
23255 (skip-chars-forward " \t\n\r")
23256 (beginning-of-line 1)
23257 (push-mark beg 'nomsg)))
23258 ((and subtreep org-yank-adjusted-subtrees)
23259 (let ((beg (point-at-bol)))
23260 (org-paste-subtree nil nil 'for-yank)
23261 (push-mark beg 'nomsg)))
23263 (call-interactively command))))))
23265 (defun org-yank-folding-would-swallow-text (beg end)
23266 "Would hide-subtree at BEG swallow any text after END?"
23267 (let (level)
23268 (org-with-limited-levels
23269 (save-excursion
23270 (goto-char beg)
23271 (when (or (looking-at org-outline-regexp)
23272 (re-search-forward org-outline-regexp-bol end t))
23273 (setq level (org-outline-level)))
23274 (goto-char end)
23275 (skip-chars-forward " \t\r\n\v\f")
23276 (if (or (eobp)
23277 (and (bolp) (looking-at org-outline-regexp)
23278 (<= (org-outline-level) level)))
23279 nil ; Nothing would be swallowed
23280 t))))) ; something would swallow
23282 (define-key org-mode-map "\C-y" 'org-yank)
23284 (defun org-truely-invisible-p ()
23285 "Check if point is at a character currently not visible.
23286 This version does not only check the character property, but also
23287 `visible-mode'."
23288 ;; Early versions of noutline don't have `outline-invisible-p'.
23289 (if (org-bound-and-true-p visible-mode)
23291 (outline-invisible-p)))
23293 (defun org-invisible-p2 ()
23294 "Check if point is at a character currently not visible."
23295 (save-excursion
23296 (if (and (eolp) (not (bobp))) (backward-char 1))
23297 ;; Early versions of noutline don't have `outline-invisible-p'.
23298 (outline-invisible-p)))
23300 (defun org-back-to-heading (&optional invisible-ok)
23301 "Call `outline-back-to-heading', but provide a better error message."
23302 (condition-case nil
23303 (outline-back-to-heading invisible-ok)
23304 (error (error "Before first headline at position %d in buffer %s"
23305 (point) (current-buffer)))))
23307 (defun org-before-first-heading-p ()
23308 "Before first heading?"
23309 (save-excursion
23310 (end-of-line)
23311 (null (re-search-backward org-outline-regexp-bol nil t))))
23313 (defun org-at-heading-p (&optional ignored)
23314 (outline-on-heading-p t))
23315 ;; Compatibility alias with Org versions < 7.8.03
23316 (defalias 'org-on-heading-p 'org-at-heading-p)
23318 (defun org-in-commented-heading-p (&optional no-inheritance)
23319 "Non-nil if point is under a commented heading.
23320 This function also checks ancestors of the current headline,
23321 unless optional argument NO-INHERITANCE is non-nil."
23322 (cond
23323 ((org-before-first-heading-p) nil)
23324 ((let ((headline (nth 4 (org-heading-components))))
23325 (and headline
23326 (let ((case-fold-search nil))
23327 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23328 headline)))))
23329 (no-inheritance nil)
23331 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23333 (defun org-at-comment-p nil
23334 "Is cursor in a line starting with a # character?"
23335 (save-excursion
23336 (beginning-of-line)
23337 (looking-at "^#")))
23339 (defun org-at-drawer-p nil
23340 "Is cursor at a drawer keyword?"
23341 (save-excursion
23342 (move-beginning-of-line 1)
23343 (looking-at org-drawer-regexp)))
23345 (defun org-at-block-p nil
23346 "Is cursor at a block keyword?"
23347 (save-excursion
23348 (move-beginning-of-line 1)
23349 (looking-at org-block-regexp)))
23351 (defun org-point-at-end-of-empty-headline ()
23352 "If point is at the end of an empty headline, return t, else nil.
23353 If the heading only contains a TODO keyword, it is still still considered
23354 empty."
23355 (and (looking-at "[ \t]*$")
23356 (when org-todo-line-regexp
23357 (save-excursion
23358 (beginning-of-line 1)
23359 (let ((case-fold-search nil))
23360 (looking-at org-todo-line-regexp)
23361 (string= (match-string 3) ""))))))
23363 (defun org-at-heading-or-item-p ()
23364 (or (org-at-heading-p) (org-at-item-p)))
23366 (defun org-at-target-p ()
23367 (or (org-in-regexp org-radio-target-regexp)
23368 (org-in-regexp org-target-regexp)))
23369 ;; Compatibility alias with Org versions < 7.8.03
23370 (defalias 'org-on-target-p 'org-at-target-p)
23372 (defun org-up-heading-all (arg)
23373 "Move to the heading line of which the present line is a subheading.
23374 This function considers both visible and invisible heading lines.
23375 With argument, move up ARG levels."
23376 (if (fboundp 'outline-up-heading-all)
23377 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23378 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23380 (defun org-up-heading-safe ()
23381 "Move to the heading line of which the present line is a subheading.
23382 This version will not throw an error. It will return the level of the
23383 headline found, or nil if no higher level is found.
23385 Also, this function will be a lot faster than `outline-up-heading',
23386 because it relies on stars being the outline starters. This can really
23387 make a significant difference in outlines with very many siblings."
23388 (let (start-level re)
23389 (org-back-to-heading t)
23390 (setq start-level (funcall outline-level))
23391 (if (equal start-level 1)
23393 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23394 (if (re-search-backward re nil t)
23395 (funcall outline-level)))))
23397 (defun org-first-sibling-p ()
23398 "Is this heading the first child of its parents?"
23399 (interactive)
23400 (let ((re org-outline-regexp-bol)
23401 level l)
23402 (unless (org-at-heading-p t)
23403 (user-error "Not at a heading"))
23404 (setq level (funcall outline-level))
23405 (save-excursion
23406 (if (not (re-search-backward re nil t))
23408 (setq l (funcall outline-level))
23409 (< l level)))))
23411 (defun org-goto-sibling (&optional previous)
23412 "Goto the next sibling, even if it is invisible.
23413 When PREVIOUS is set, go to the previous sibling instead. Returns t
23414 when a sibling was found. When none is found, return nil and don't
23415 move point."
23416 (let ((fun (if previous 're-search-backward 're-search-forward))
23417 (pos (point))
23418 (re org-outline-regexp-bol)
23419 level l)
23420 (when (condition-case nil (org-back-to-heading t) (error nil))
23421 (setq level (funcall outline-level))
23422 (catch 'exit
23423 (or previous (forward-char 1))
23424 (while (funcall fun re nil t)
23425 (setq l (funcall outline-level))
23426 (when (< l level) (goto-char pos) (throw 'exit nil))
23427 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23428 (goto-char pos)
23429 nil))))
23431 (defun org-show-siblings ()
23432 "Show all siblings of the current headline."
23433 (save-excursion
23434 (while (org-goto-sibling) (org-flag-heading nil)))
23435 (save-excursion
23436 (while (org-goto-sibling 'previous)
23437 (org-flag-heading nil))))
23439 (defun org-goto-first-child ()
23440 "Goto the first child, even if it is invisible.
23441 Return t when a child was found. Otherwise don't move point and
23442 return nil."
23443 (let (level (pos (point)) (re org-outline-regexp-bol))
23444 (when (condition-case nil (org-back-to-heading t) (error nil))
23445 (setq level (outline-level))
23446 (forward-char 1)
23447 (if (and (re-search-forward re nil t) (> (outline-level) level))
23448 (progn (goto-char (match-beginning 0)) t)
23449 (goto-char pos) nil))))
23451 (defun org-show-hidden-entry ()
23452 "Show an entry where even the heading is hidden."
23453 (save-excursion
23454 (org-show-entry)))
23456 (defun org-flag-heading (flag &optional entry)
23457 "Flag the current heading. FLAG non-nil means make invisible.
23458 When ENTRY is non-nil, show the entire entry."
23459 (save-excursion
23460 (org-back-to-heading t)
23461 ;; Check if we should show the entire entry
23462 (if entry
23463 (progn
23464 (org-show-entry)
23465 (save-excursion
23466 (and (outline-next-heading)
23467 (org-flag-heading nil))))
23468 (outline-flag-region (max (point-min) (1- (point)))
23469 (save-excursion (outline-end-of-heading) (point))
23470 flag))))
23472 (defun org-get-next-sibling ()
23473 "Move to next heading of the same level, and return point.
23474 If there is no such heading, return nil.
23475 This is like outline-next-sibling, but invisible headings are ok."
23476 (let ((level (funcall outline-level)))
23477 (outline-next-heading)
23478 (while (and (not (eobp)) (> (funcall outline-level) level))
23479 (outline-next-heading))
23480 (if (or (eobp) (< (funcall outline-level) level))
23482 (point))))
23484 (defun org-get-last-sibling ()
23485 "Move to previous heading of the same level, and return point.
23486 If there is no such heading, return nil."
23487 (let ((opoint (point))
23488 (level (funcall outline-level)))
23489 (outline-previous-heading)
23490 (when (and (/= (point) opoint) (outline-on-heading-p t))
23491 (while (and (> (funcall outline-level) level)
23492 (not (bobp)))
23493 (outline-previous-heading))
23494 (if (< (funcall outline-level) level)
23496 (point)))))
23498 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23499 "Goto to the end of a subtree."
23500 ;; This contains an exact copy of the original function, but it uses
23501 ;; `org-back-to-heading', to make it work also in invisible
23502 ;; trees. And is uses an invisible-ok argument.
23503 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23504 ;; Furthermore, when used inside Org, finding the end of a large subtree
23505 ;; with many children and grandchildren etc, this can be much faster
23506 ;; than the outline version.
23507 (org-back-to-heading invisible-ok)
23508 (let ((first t)
23509 (level (funcall outline-level)))
23510 (if (and (derived-mode-p 'org-mode) (< level 1000))
23511 ;; A true heading (not a plain list item), in Org-mode
23512 ;; This means we can easily find the end by looking
23513 ;; only for the right number of stars. Using a regexp to do
23514 ;; this is so much faster than using a Lisp loop.
23515 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23516 (forward-char 1)
23517 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23518 ;; something else, do it the slow way
23519 (while (and (not (eobp))
23520 (or first (> (funcall outline-level) level)))
23521 (setq first nil)
23522 (outline-next-heading)))
23523 (unless to-heading
23524 (if (memq (preceding-char) '(?\n ?\^M))
23525 (progn
23526 ;; Go to end of line before heading
23527 (forward-char -1)
23528 (if (memq (preceding-char) '(?\n ?\^M))
23529 ;; leave blank line before heading
23530 (forward-char -1))))))
23531 (point))
23533 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23534 "Use Org version in org-mode, for dramatic speed-up."
23535 (if (derived-mode-p 'org-mode)
23536 (progn
23537 (org-end-of-subtree nil t)
23538 (unless (eobp) (backward-char 1)))
23539 ad-do-it))
23541 (defun org-end-of-meta-data-and-drawers ()
23542 "Jump to the first text after meta data and drawers in the current entry.
23543 This will move over empty lines, lines with planning time stamps,
23544 clocking lines, and drawers."
23545 (org-back-to-heading t)
23546 (let ((end (save-excursion (outline-next-heading) (point)))
23547 (re (concat "\\(" org-drawer-regexp "\\)"
23548 "\\|" "[ \t]*" org-keyword-time-regexp)))
23549 (forward-line 1)
23550 (while (re-search-forward re end t)
23551 (if (not (match-end 1))
23552 ;; empty or planning line
23553 (forward-line 1)
23554 ;; a drawer, find the end
23555 (re-search-forward "^[ \t]*:END:" end 'move)
23556 (forward-line 1)))
23557 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23558 (point)))
23560 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23561 "Move forward to the ARG'th subheading at same level as this one.
23562 Stop at the first and last subheadings of a superior heading.
23563 Normally this only looks at visible headings, but when INVISIBLE-OK is
23564 non-nil it will also look at invisible ones."
23565 (interactive "p")
23566 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23567 (if (and arg (< arg 0))
23568 (goto-char (point-min))
23569 (outline-next-heading))
23570 (org-at-heading-p)
23571 (let ((level (- (match-end 0) (match-beginning 0) 1))
23572 (f (if (and arg (< arg 0))
23573 're-search-backward
23574 're-search-forward))
23575 (count (if arg (abs arg) 1))
23576 (result (point)))
23577 (while (and (prog1 (> count 0)
23578 (forward-char (if (and arg (< arg 0)) -1 1)))
23579 (funcall f org-outline-regexp-bol nil 'move))
23580 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23581 (cond ((< l level) (setq count 0))
23582 ((and (= l level)
23583 (or invisible-ok
23584 (progn
23585 (goto-char (line-beginning-position))
23586 (not (outline-invisible-p)))))
23587 (setq count (1- count))
23588 (when (eq l level)
23589 (setq result (point)))))))
23590 (goto-char result))
23591 (beginning-of-line 1)))
23593 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23594 "Move backward to the ARG'th subheading at same level as this one.
23595 Stop at the first and last subheadings of a superior heading."
23596 (interactive "p")
23597 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23599 (defun org-next-block (arg &optional backward block-regexp)
23600 "Jump to the next block.
23601 With a prefix argument ARG, jump forward ARG many source blocks.
23602 When BACKWARD is non-nil, jump to the previous block.
23603 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23604 (interactive "p")
23605 (let ((re (or block-regexp org-block-regexp))
23606 (re-search-fn (or (and backward 're-search-backward)
23607 're-search-forward)))
23608 (if (looking-at re) (forward-char 1))
23609 (condition-case nil
23610 (funcall re-search-fn re nil nil arg)
23611 (error (user-error "No %s code blocks"
23612 (if backward "previous" "further" ))))
23613 (goto-char (match-beginning 0)) (org-show-context)))
23615 (defun org-previous-block (arg &optional block-regexp)
23616 "Jump to the previous block.
23617 With a prefix argument ARG, jump backward ARG many source blocks.
23618 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23619 (interactive "p")
23620 (org-next-block arg t block-regexp))
23622 (defun org-forward-paragraph ()
23623 "Move forward to beginning of next paragraph or equivalent.
23625 The function moves point to the beginning of the next visible
23626 structural element, which can be a paragraph, a table, a list
23627 item, etc. It also provides some special moves for convenience:
23629 - On an affiliated keyword, jump to the beginning of the
23630 relative element.
23631 - On an item or a footnote definition, move to the second
23632 element inside, if any.
23633 - On a table or a property drawer, jump after it.
23634 - On a verse or source block, stop after blank lines."
23635 (interactive)
23636 (when (eobp) (user-error "Cannot move further down"))
23637 (let* ((deactivate-mark nil)
23638 (element (org-element-at-point))
23639 (type (org-element-type element))
23640 (post-affiliated (org-element-property :post-affiliated element))
23641 (contents-begin (org-element-property :contents-begin element))
23642 (contents-end (org-element-property :contents-end element))
23643 (end (let ((end (org-element-property :end element)) (parent element))
23644 (while (and (setq parent (org-element-property :parent parent))
23645 (= (org-element-property :contents-end parent) end))
23646 (setq end (org-element-property :end parent)))
23647 end)))
23648 (cond ((not element)
23649 (skip-chars-forward " \r\t\n")
23650 (or (eobp) (beginning-of-line)))
23651 ;; On affiliated keywords, move to element's beginning.
23652 ((and post-affiliated (< (point) post-affiliated))
23653 (goto-char post-affiliated))
23654 ;; At a table row, move to the end of the table. Similarly,
23655 ;; at a node property, move to the end of the property
23656 ;; drawer.
23657 ((memq type '(node-property table-row))
23658 (goto-char (org-element-property
23659 :end (org-element-property :parent element))))
23660 ((memq type '(property-drawer table)) (goto-char end))
23661 ;; Consider blank lines as separators in verse and source
23662 ;; blocks to ease editing.
23663 ((memq type '(src-block verse-block))
23664 (when (eq type 'src-block)
23665 (setq contents-end
23666 (save-excursion (goto-char end)
23667 (skip-chars-backward " \r\t\n")
23668 (line-beginning-position))))
23669 (beginning-of-line)
23670 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23671 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23672 (goto-char end)
23673 (skip-chars-forward " \r\t\n")
23674 (if (= (point) contents-end) (goto-char end)
23675 (beginning-of-line))))
23676 ;; With no contents, just skip element.
23677 ((not contents-begin) (goto-char end))
23678 ;; If contents are invisible, skip the element altogether.
23679 ((outline-invisible-p (line-end-position))
23680 (case type
23681 (headline
23682 (org-with-limited-levels (outline-next-visible-heading 1)))
23683 ;; At a plain list, make sure we move to the next item
23684 ;; instead of skipping the whole list.
23685 (plain-list (forward-char)
23686 (org-forward-paragraph))
23687 (otherwise (goto-char end))))
23688 ((>= (point) contents-end) (goto-char end))
23689 ((>= (point) contents-begin)
23690 ;; This can only happen on paragraphs and plain lists.
23691 (case type
23692 (paragraph (goto-char end))
23693 ;; At a plain list, try to move to second element in
23694 ;; first item, if possible.
23695 (plain-list (end-of-line)
23696 (org-forward-paragraph))))
23697 ;; When contents start on the middle of a line (e.g. in
23698 ;; items and footnote definitions), try to reach first
23699 ;; element starting after current line.
23700 ((> (line-end-position) contents-begin)
23701 (end-of-line)
23702 (org-forward-paragraph))
23703 (t (goto-char contents-begin)))))
23705 (defun org-backward-paragraph ()
23706 "Move backward to start of previous paragraph or equivalent.
23708 The function moves point to the beginning of the current
23709 structural element, which can be a paragraph, a table, a list
23710 item, etc., or to the beginning of the previous visible one if
23711 point is already there. It also provides some special moves for
23712 convenience:
23714 - On an affiliated keyword, jump to the first one.
23715 - On a table or a property drawer, move to its beginning.
23716 - On a verse or source block, stop before blank lines."
23717 (interactive)
23718 (when (bobp) (user-error "Cannot move further up"))
23719 (let* ((deactivate-mark nil)
23720 (element (org-element-at-point))
23721 (type (org-element-type element))
23722 (contents-begin (org-element-property :contents-begin element))
23723 (contents-end (org-element-property :contents-end element))
23724 (post-affiliated (org-element-property :post-affiliated element))
23725 (begin (org-element-property :begin element)))
23726 (cond
23727 ((not element) (goto-char (point-min)))
23728 ((= (point) begin)
23729 (backward-char)
23730 (org-backward-paragraph))
23731 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23732 ((memq type '(node-property table-row))
23733 (goto-char (org-element-property
23734 :post-affiliated (org-element-property :parent element))))
23735 ((memq type '(property-drawer table)) (goto-char begin))
23736 ((memq type '(src-block verse-block))
23737 (when (eq type 'src-block)
23738 (setq contents-begin
23739 (save-excursion (goto-char begin) (forward-line) (point))))
23740 (if (= (point) contents-begin) (goto-char post-affiliated)
23741 ;; Inside a verse block, see blank lines as paragraph
23742 ;; separators.
23743 (let ((origin (point)))
23744 (skip-chars-backward " \r\t\n" contents-begin)
23745 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23746 (skip-chars-forward " \r\t\n" origin)
23747 (if (= (point) origin) (goto-char contents-begin)
23748 (beginning-of-line))))))
23749 ((not contents-begin) (goto-char (or post-affiliated begin)))
23750 ((eq type 'paragraph)
23751 (goto-char contents-begin)
23752 ;; When at first paragraph in an item or a footnote definition,
23753 ;; move directly to beginning of line.
23754 (let ((parent-contents
23755 (org-element-property
23756 :contents-begin (org-element-property :parent element))))
23757 (when (and parent-contents (= parent-contents contents-begin))
23758 (beginning-of-line))))
23759 ;; At the end of a greater element, move to the beginning of the
23760 ;; last element within.
23761 ((>= (point) contents-end)
23762 (goto-char (1- contents-end))
23763 (org-backward-paragraph))
23764 (t (goto-char (or post-affiliated begin))))
23765 ;; Ensure we never leave point invisible.
23766 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23768 (defun org-forward-element ()
23769 "Move forward by one element.
23770 Move to the next element at the same level, when possible."
23771 (interactive)
23772 (cond ((eobp) (user-error "Cannot move further down"))
23773 ((org-with-limited-levels (org-at-heading-p))
23774 (let ((origin (point)))
23775 (goto-char (org-end-of-subtree nil t))
23776 (unless (org-with-limited-levels (org-at-heading-p))
23777 (goto-char origin)
23778 (user-error "Cannot move further down"))))
23780 (let* ((elem (org-element-at-point))
23781 (end (org-element-property :end elem))
23782 (parent (org-element-property :parent elem)))
23783 (cond ((and parent (= (org-element-property :contents-end parent) end))
23784 (goto-char (org-element-property :end parent)))
23785 ((integer-or-marker-p end) (goto-char end))
23786 (t (message "No element at point")))))))
23788 (defun org-backward-element ()
23789 "Move backward by one element.
23790 Move to the previous element at the same level, when possible."
23791 (interactive)
23792 (cond ((bobp) (user-error "Cannot move further up"))
23793 ((org-with-limited-levels (org-at-heading-p))
23794 ;; At a headline, move to the previous one, if any, or stay
23795 ;; here.
23796 (let ((origin (point)))
23797 (org-with-limited-levels (org-backward-heading-same-level 1))
23798 ;; When current headline has no sibling above, move to its
23799 ;; parent.
23800 (when (= (point) origin)
23801 (or (org-with-limited-levels (org-up-heading-safe))
23802 (progn (goto-char origin)
23803 (user-error "Cannot move further up"))))))
23805 (let* ((elem (org-element-at-point))
23806 (beg (org-element-property :begin elem)))
23807 (cond
23808 ;; Move to beginning of current element if point isn't
23809 ;; there already.
23810 ((null beg) (message "No element at point"))
23811 ((/= (point) beg) (goto-char beg))
23812 (t (goto-char beg)
23813 (skip-chars-backward " \r\t\n")
23814 (unless (bobp)
23815 (let ((prev (org-element-at-point)))
23816 (goto-char (org-element-property :begin prev))
23817 (while (and (setq prev (org-element-property :parent prev))
23818 (<= (org-element-property :end prev) beg))
23819 (goto-char (org-element-property :begin prev)))))))))))
23821 (defun org-up-element ()
23822 "Move to upper element."
23823 (interactive)
23824 (if (org-with-limited-levels (org-at-heading-p))
23825 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23826 (let* ((elem (org-element-at-point))
23827 (parent (org-element-property :parent elem)))
23828 (if parent (goto-char (org-element-property :begin parent))
23829 (if (org-with-limited-levels (org-before-first-heading-p))
23830 (user-error "No surrounding element")
23831 (org-with-limited-levels (org-back-to-heading)))))))
23833 (defvar org-element-greater-elements)
23834 (defun org-down-element ()
23835 "Move to inner element."
23836 (interactive)
23837 (let ((element (org-element-at-point)))
23838 (cond
23839 ((memq (org-element-type element) '(plain-list table))
23840 (goto-char (org-element-property :contents-begin element))
23841 (forward-char))
23842 ((memq (org-element-type element) org-element-greater-elements)
23843 ;; If contents are hidden, first disclose them.
23844 (when (outline-invisible-p (line-end-position)) (org-cycle))
23845 (goto-char (or (org-element-property :contents-begin element)
23846 (user-error "No content for this element"))))
23847 (t (user-error "No inner element")))))
23849 (defun org-drag-element-backward ()
23850 "Move backward element at point."
23851 (interactive)
23852 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23853 (let* ((elem (org-element-at-point))
23854 (prev-elem
23855 (save-excursion
23856 (goto-char (org-element-property :begin elem))
23857 (skip-chars-backward " \r\t\n")
23858 (unless (bobp)
23859 (let* ((beg (org-element-property :begin elem))
23860 (prev (org-element-at-point))
23861 (up prev))
23862 (while (and (setq up (org-element-property :parent up))
23863 (<= (org-element-property :end prev) beg))
23864 (setq prev up))
23865 prev)))))
23866 ;; Error out if no previous element or previous element is
23867 ;; a parent of the current one.
23868 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23869 (user-error "Cannot drag element backward")
23870 (let ((pos (point)))
23871 (org-element-swap-A-B prev-elem elem)
23872 (goto-char (+ (org-element-property :begin prev-elem)
23873 (- pos (org-element-property :begin elem)))))))))
23875 (defun org-drag-element-forward ()
23876 "Move forward element at point."
23877 (interactive)
23878 (let* ((pos (point))
23879 (elem (org-element-at-point)))
23880 (when (= (point-max) (org-element-property :end elem))
23881 (user-error "Cannot drag element forward"))
23882 (goto-char (org-element-property :end elem))
23883 (let ((next-elem (org-element-at-point)))
23884 (when (or (org-element-nested-p elem next-elem)
23885 (and (eq (org-element-type next-elem) 'headline)
23886 (not (eq (org-element-type elem) 'headline))))
23887 (goto-char pos)
23888 (user-error "Cannot drag element forward"))
23889 ;; Compute new position of point: it's shifted by NEXT-ELEM
23890 ;; body's length (without final blanks) and by the length of
23891 ;; blanks between ELEM and NEXT-ELEM.
23892 (let ((size-next (- (save-excursion
23893 (goto-char (org-element-property :end next-elem))
23894 (skip-chars-backward " \r\t\n")
23895 (forward-line)
23896 ;; Small correction if buffer doesn't end
23897 ;; with a newline character.
23898 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23899 (org-element-property :begin next-elem)))
23900 (size-blank (- (org-element-property :end elem)
23901 (save-excursion
23902 (goto-char (org-element-property :end elem))
23903 (skip-chars-backward " \r\t\n")
23904 (forward-line)
23905 (point)))))
23906 (org-element-swap-A-B elem next-elem)
23907 (goto-char (+ pos size-next size-blank))))))
23909 (defun org-drag-line-forward (arg)
23910 "Drag the line at point ARG lines forward."
23911 (interactive "p")
23912 (dotimes (n (abs arg))
23913 (let ((c (current-column)))
23914 (if (< 0 arg)
23915 (progn
23916 (beginning-of-line 2)
23917 (transpose-lines 1)
23918 (beginning-of-line 0))
23919 (transpose-lines 1)
23920 (beginning-of-line -1))
23921 (org-move-to-column c))))
23923 (defun org-drag-line-backward (arg)
23924 "Drag the line at point ARG lines backward."
23925 (interactive "p")
23926 (org-drag-line-forward (- arg)))
23928 (defun org-mark-element ()
23929 "Put point at beginning of this element, mark at end.
23931 Interactively, if this command is repeated or (in Transient Mark
23932 mode) if the mark is active, it marks the next element after the
23933 ones already marked."
23934 (interactive)
23935 (let (deactivate-mark)
23936 (if (and (org-called-interactively-p 'any)
23937 (or (and (eq last-command this-command) (mark t))
23938 (and transient-mark-mode mark-active)))
23939 (set-mark
23940 (save-excursion
23941 (goto-char (mark))
23942 (goto-char (org-element-property :end (org-element-at-point)))))
23943 (let ((element (org-element-at-point)))
23944 (end-of-line)
23945 (push-mark (org-element-property :end element) t t)
23946 (goto-char (org-element-property :begin element))))))
23948 (defun org-narrow-to-element ()
23949 "Narrow buffer to current element."
23950 (interactive)
23951 (let ((elem (org-element-at-point)))
23952 (cond
23953 ((eq (car elem) 'headline)
23954 (narrow-to-region
23955 (org-element-property :begin elem)
23956 (org-element-property :end elem)))
23957 ((memq (car elem) org-element-greater-elements)
23958 (narrow-to-region
23959 (org-element-property :contents-begin elem)
23960 (org-element-property :contents-end elem)))
23962 (narrow-to-region
23963 (org-element-property :begin elem)
23964 (org-element-property :end elem))))))
23966 (defun org-transpose-element ()
23967 "Transpose current and previous elements, keeping blank lines between.
23968 Point is moved after both elements."
23969 (interactive)
23970 (org-skip-whitespace)
23971 (let ((end (org-element-property :end (org-element-at-point))))
23972 (org-drag-element-backward)
23973 (goto-char end)))
23975 (defun org-unindent-buffer ()
23976 "Un-indent the visible part of the buffer.
23977 Relative indentation (between items, inside blocks, etc.) isn't
23978 modified."
23979 (interactive)
23980 (unless (eq major-mode 'org-mode)
23981 (user-error "Cannot un-indent a buffer not in Org mode"))
23982 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23983 unindent-tree ; For byte-compiler.
23984 (unindent-tree
23985 (function
23986 (lambda (contents)
23987 (mapc
23988 (lambda (element)
23989 (if (memq (org-element-type element) '(headline section))
23990 (funcall unindent-tree (org-element-contents element))
23991 (save-excursion
23992 (save-restriction
23993 (narrow-to-region
23994 (org-element-property :begin element)
23995 (org-element-property :end element))
23996 (org-do-remove-indentation)))))
23997 (reverse contents))))))
23998 (funcall unindent-tree (org-element-contents parse-tree))))
24000 (defun org-show-subtree ()
24001 "Show everything after this heading at deeper levels."
24002 (interactive)
24003 (outline-flag-region
24004 (point)
24005 (save-excursion
24006 (org-end-of-subtree t t))
24007 nil))
24009 (defun org-show-entry ()
24010 "Show the body directly following this heading.
24011 Show the heading too, if it is currently invisible."
24012 (interactive)
24013 (save-excursion
24014 (condition-case nil
24015 (progn
24016 (org-back-to-heading t)
24017 (outline-flag-region
24018 (max (point-min) (1- (point)))
24019 (save-excursion
24020 (if (re-search-forward
24021 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24022 (match-beginning 1)
24023 (point-max)))
24024 nil)
24025 (org-cycle-hide-drawers 'children))
24026 (error nil))))
24028 (defun org-make-options-regexp (kwds &optional extra)
24029 "Make a regular expression for keyword lines."
24030 (concat
24031 "^[ \t]*#\\+\\("
24032 (mapconcat 'regexp-quote kwds "\\|")
24033 (if extra (concat "\\|" extra))
24034 "\\):[ \t]*\\(.*\\)"))
24036 ;; Make isearch reveal the necessary context
24037 (defun org-isearch-end ()
24038 "Reveal context after isearch exits."
24039 (when isearch-success ; only if search was successful
24040 (if (featurep 'xemacs)
24041 ;; Under XEmacs, the hook is run in the correct place,
24042 ;; we directly show the context.
24043 (org-show-context 'isearch)
24044 ;; In Emacs the hook runs *before* restoring the overlays.
24045 ;; So we have to use a one-time post-command-hook to do this.
24046 ;; (Emacs 22 has a special variable, see function `org-mode')
24047 (unless (and (boundp 'isearch-mode-end-hook-quit)
24048 isearch-mode-end-hook-quit)
24049 ;; Only when the isearch was not quitted.
24050 (org-add-hook 'post-command-hook 'org-isearch-post-command
24051 'append 'local)))
24052 (org-fix-ellipsis-at-bol)))
24054 (defun org-isearch-post-command ()
24055 "Remove self from hook, and show context."
24056 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24057 (org-show-context 'isearch))
24060 ;;;; Integration with and fixes for other packages
24062 ;;; Imenu support
24064 (defvar org-imenu-markers nil
24065 "All markers currently used by Imenu.")
24066 (make-variable-buffer-local 'org-imenu-markers)
24068 (defun org-imenu-new-marker (&optional pos)
24069 "Return a new marker for use by Imenu, and remember the marker."
24070 (let ((m (make-marker)))
24071 (move-marker m (or pos (point)))
24072 (push m org-imenu-markers)
24075 (defun org-imenu-get-tree ()
24076 "Produce the index for Imenu."
24077 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24078 (setq org-imenu-markers nil)
24079 (let* ((n org-imenu-depth)
24080 (re (concat "^" (org-get-limited-outline-regexp)))
24081 (subs (make-vector (1+ n) nil))
24082 (last-level 0)
24083 m level head0 head)
24084 (save-excursion
24085 (save-restriction
24086 (widen)
24087 (goto-char (point-max))
24088 (while (re-search-backward re nil t)
24089 (setq level (org-reduced-level (funcall outline-level)))
24090 (when (and (<= level n)
24091 (looking-at org-complex-heading-regexp)
24092 (setq head0 (org-match-string-no-properties 4)))
24093 (setq head (org-link-display-format head0)
24094 m (org-imenu-new-marker))
24095 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24096 (if (>= level last-level)
24097 (push (cons head m) (aref subs level))
24098 (push (cons head (aref subs (1+ level))) (aref subs level))
24099 (loop for i from (1+ level) to n do (aset subs i nil)))
24100 (setq last-level level)))))
24101 (aref subs 1)))
24103 (eval-after-load "imenu"
24104 '(progn
24105 (add-hook 'imenu-after-jump-hook
24106 (lambda ()
24107 (if (derived-mode-p 'org-mode)
24108 (org-show-context 'org-goto))))))
24110 (defun org-link-display-format (link)
24111 "Replace a link with its the description.
24112 If there is no description, use the link target."
24113 (save-match-data
24114 (if (string-match org-bracket-link-analytic-regexp link)
24115 (replace-match (if (match-end 5)
24116 (match-string 5 link)
24117 (concat (match-string 1 link)
24118 (match-string 3 link)))
24119 nil t link)
24120 link)))
24122 (defun org-toggle-link-display ()
24123 "Toggle the literal or descriptive display of links."
24124 (interactive)
24125 (if org-descriptive-links
24126 (progn (org-remove-from-invisibility-spec '(org-link))
24127 (org-restart-font-lock)
24128 (setq org-descriptive-links nil))
24129 (progn (add-to-invisibility-spec '(org-link))
24130 (org-restart-font-lock)
24131 (setq org-descriptive-links t))))
24133 ;; Speedbar support
24135 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24136 "Overlay marking the agenda restriction line in speedbar.")
24137 (overlay-put org-speedbar-restriction-lock-overlay
24138 'face 'org-agenda-restriction-lock)
24139 (overlay-put org-speedbar-restriction-lock-overlay
24140 'help-echo "Agendas are currently limited to this item.")
24141 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24143 (defun org-speedbar-set-agenda-restriction ()
24144 "Restrict future agenda commands to the location at point in speedbar.
24145 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24146 (interactive)
24147 (require 'org-agenda)
24148 (let (p m tp np dir txt)
24149 (cond
24150 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24151 'org-imenu t))
24152 (setq m (get-text-property p 'org-imenu-marker))
24153 (with-current-buffer (marker-buffer m)
24154 (goto-char m)
24155 (org-agenda-set-restriction-lock 'subtree)))
24156 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24157 'speedbar-function 'speedbar-find-file))
24158 (setq tp (previous-single-property-change
24159 (1+ p) 'speedbar-function)
24160 np (next-single-property-change
24161 tp 'speedbar-function)
24162 dir (speedbar-line-directory)
24163 txt (buffer-substring-no-properties (or tp (point-min))
24164 (or np (point-max))))
24165 (with-current-buffer (find-file-noselect
24166 (let ((default-directory dir))
24167 (expand-file-name txt)))
24168 (unless (derived-mode-p 'org-mode)
24169 (user-error "Cannot restrict to non-Org-mode file"))
24170 (org-agenda-set-restriction-lock 'file)))
24171 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24172 (move-overlay org-speedbar-restriction-lock-overlay
24173 (point-at-bol) (point-at-eol))
24174 (setq current-prefix-arg nil)
24175 (org-agenda-maybe-redo)))
24177 (defvar speedbar-file-key-map)
24178 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24179 (eval-after-load "speedbar"
24180 '(progn
24181 (speedbar-add-supported-extension ".org")
24182 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24183 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24184 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24185 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24186 (add-hook 'speedbar-visiting-tag-hook
24187 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24189 ;;; Fixes and Hacks for problems with other packages
24191 (defun org-mode-flyspell-verify ()
24192 "Function used for `flyspell-generic-check-word-predicate'."
24193 (if (org-at-heading-p)
24194 ;; At a headline or an inlinetask, check title only. This is
24195 ;; faster than relying on `org-element-at-point'.
24196 (and (save-excursion (beginning-of-line)
24197 (and (let ((case-fold-search t))
24198 (not (looking-at "\\*+ END[ \t]*$")))
24199 (looking-at org-complex-heading-regexp)))
24200 (match-beginning 4)
24201 (>= (point) (match-beginning 4))
24202 (or (not (match-beginning 5))
24203 (< (point) (match-beginning 5))))
24204 (let* ((element (org-element-at-point))
24205 (post-affiliated (org-element-property :post-affiliated element))
24206 (object-check
24207 (function
24208 ;; Non-nil if checks can be done for object at point.
24209 (lambda ()
24210 (let ((object (save-excursion
24211 (when (org-looking-at-p "\\>") (backward-char))
24212 (org-element-context element))))
24213 (case (org-element-type object)
24214 ;; Prevent checks in links due to keybinding conflict
24215 ;; with Flyspell.
24216 ((code entity export-snippet inline-babel-call
24217 inline-src-block line-break latex-fragment link macro
24218 statistics-cookie target timestamp verbatim)
24219 nil)
24220 (footnote-reference
24221 ;; Only in inline footnotes, within the definition.
24222 (and (eq (org-element-property :type object) 'inline)
24223 (< (save-excursion
24224 (goto-char (org-element-property :begin object))
24225 (search-forward ":" nil t 2))
24226 (point))))
24227 (otherwise t)))))))
24228 (cond
24229 ;; Ignore checks in all affiliated keywords but captions.
24230 ((and post-affiliated (< (point) post-affiliated))
24231 (and (save-excursion
24232 (beginning-of-line)
24233 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24234 (> (point) (match-end 0))
24235 (funcall object-check)))
24236 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24237 ((and org-log-into-drawer
24238 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24239 (parent element))
24240 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24241 (setq parent (org-element-property :parent parent)))
24242 (and parent
24243 (eq (compare-strings
24244 log nil nil
24245 (org-element-property :drawer-name parent) nil nil t)
24246 t))))
24247 nil)
24249 (case (org-element-type element)
24250 ((comment quote-section) t)
24251 (comment-block
24252 ;; Allow checks between block markers, not on them.
24253 (and (> (line-beginning-position)
24254 (org-element-property :post-affiliated element))
24255 (save-excursion
24256 (end-of-line)
24257 (skip-chars-forward " \r\t\n")
24258 (< (point) (org-element-property :end element)))))
24259 ;; Arbitrary list of keywords where checks are meaningful.
24260 ;; Make sure point is on the value part of the element.
24261 (keyword
24262 (and (member (org-element-property :key element)
24263 '("DESCRIPTION" "TITLE"))
24264 (< (save-excursion
24265 (beginning-of-line) (search-forward ":") (point))
24266 (point))))
24267 ;; Check is globally allowed in paragraphs verse blocks and
24268 ;; table rows (after affiliated keywords) but some objects
24269 ;; must not be affected.
24270 ((paragraph table-row verse-block)
24271 (and (>= (point) (org-element-property :contents-begin element))
24272 (< (point) (org-element-property :contents-end element))
24273 (funcall object-check)))))))))
24274 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24276 (defun org-remove-flyspell-overlays-in (beg end)
24277 "Remove flyspell overlays in region."
24278 (and (org-bound-and-true-p flyspell-mode)
24279 (fboundp 'flyspell-delete-region-overlays)
24280 (flyspell-delete-region-overlays beg end)))
24282 (defvar flyspell-delayed-commands)
24283 (eval-after-load "flyspell"
24284 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24286 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24287 (eval-after-load "bookmark"
24288 '(if (boundp 'bookmark-after-jump-hook)
24289 ;; We can use the hook
24290 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24291 ;; Hook not available, use advice
24292 (defadvice bookmark-jump (after org-make-visible activate)
24293 "Make the position visible."
24294 (org-bookmark-jump-unhide))))
24296 ;; Make sure saveplace shows the location if it was hidden
24297 (eval-after-load "saveplace"
24298 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24299 "Make the position visible."
24300 (org-bookmark-jump-unhide)))
24302 ;; Make sure ecb shows the location if it was hidden
24303 (eval-after-load "ecb"
24304 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24305 "Make hierarchy visible when jumping into location from ECB tree buffer."
24306 (if (derived-mode-p 'org-mode)
24307 (org-show-context))))
24309 (defun org-bookmark-jump-unhide ()
24310 "Unhide the current position, to show the bookmark location."
24311 (and (derived-mode-p 'org-mode)
24312 (or (outline-invisible-p)
24313 (save-excursion (goto-char (max (point-min) (1- (point))))
24314 (outline-invisible-p)))
24315 (org-show-context 'bookmark-jump)))
24317 ;; Make session.el ignore our circular variable
24318 (defvar session-globals-exclude)
24319 (eval-after-load "session"
24320 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24322 ;;;; Finish up
24324 (provide 'org)
24326 (run-hooks 'org-load-hook)
24328 ;;; org.el ends here