Merge branch 'master' into comment-cache
[emacs.git] / lisp / org / org.el
blob02a7a0c09af15a51ebc787915083016d212eff1d
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 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-add-archive-files "org-archive" (files))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
121 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
122 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
123 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
125 (declare-function org-clock-update-time-maybe "org-clock" ())
126 (declare-function org-clocktable-shift "org-clock" (dir n))
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" (&optional prefix) t)
131 (declare-function org-table-edit-field "org-table" (arg))
132 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
133 (declare-function org-table-set-constants "org-table" ())
134 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
135 (declare-function org-id-get-create "org-id" (&optional force))
136 (declare-function org-id-find-id-file "org-id" (id))
137 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
138 (declare-function org-agenda-list "org-agenda"
139 (&optional arg start-day span with-hour))
140 (declare-function org-agenda-redo "org-agenda" (&optional all))
141 (declare-function org-table-align "org-table" ())
142 (declare-function org-table-begin "org-table" (&optional table-type))
143 (declare-function org-table-blank-field "org-table" ())
144 (declare-function org-table-end "org-table" (&optional table-type))
145 (declare-function org-table-insert-row "org-table" (&optional arg))
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" (&optional keep-trail))
153 (declare-function org-element-contents "org-element" (element))
154 (declare-function org-element-context "org-element" (&optional element))
155 (declare-function org-element-interpret-data "org-element"
156 (data &optional parent))
157 (declare-function org-element-map "org-element"
158 (data types fun &optional
159 info first-match no-recursion with-affiliated))
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 ;; load languages based on value of `org-babel-load-languages'
175 (defvar org-babel-load-languages)
177 ;;;###autoload
178 (defun org-babel-do-load-languages (sym value)
179 "Load the languages defined in `org-babel-load-languages'."
180 (set-default sym value)
181 (mapc (lambda (pair)
182 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
183 (if active
184 (progn
185 (require (intern (concat "ob-" lang))))
186 (progn
187 (funcall 'fmakunbound
188 (intern (concat "org-babel-execute:" lang)))
189 (funcall 'fmakunbound
190 (intern (concat "org-babel-expand-body:" lang)))))))
191 org-babel-load-languages))
193 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
194 ;;;###autoload
195 (defun org-babel-load-file (file &optional compile)
196 "Load Emacs Lisp source code blocks in the Org-mode FILE.
197 This function exports the source code using `org-babel-tangle'
198 and then loads the resulting file using `load-file'. With prefix
199 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
200 file to byte-code before it is loaded."
201 (interactive "fFile to load: \nP")
202 (require 'ob-core)
203 (let* ((age (lambda (file)
204 (float-time
205 (time-subtract (current-time)
206 (nth 5 (or (file-attributes (file-truename file))
207 (file-attributes file)))))))
208 (base-name (file-name-sans-extension file))
209 (exported-file (concat base-name ".el")))
210 ;; tangle if the org-mode file is newer than the elisp file
211 (unless (and (file-exists-p exported-file)
212 (> (funcall age file) (funcall age exported-file)))
213 (setq exported-file
214 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
215 (message "%s %s"
216 (if compile
217 (progn (byte-compile-file exported-file 'load)
218 "Compiled and loaded")
219 (progn (load-file exported-file) "Loaded"))
220 exported-file)))
222 (defcustom org-babel-load-languages '((emacs-lisp . t))
223 "Languages which can be evaluated in Org-mode buffers.
224 This list can be used to load support for any of the languages
225 below, note that each language will depend on a different set of
226 system executables and/or Emacs modes. When a language is
227 \"loaded\", then code blocks in that language can be evaluated
228 with `org-babel-execute-src-block' bound by default to C-c
229 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
230 be set to remove code block evaluation from the C-c C-c
231 keybinding. By default only Emacs Lisp (which has no
232 requirements) is loaded."
233 :group 'org-babel
234 :set 'org-babel-do-load-languages
235 :version "24.1"
236 :type '(alist :tag "Babel Languages"
237 :key-type
238 (choice
239 (const :tag "Awk" awk)
240 (const :tag "C" C)
241 (const :tag "R" R)
242 (const :tag "Asymptote" asymptote)
243 (const :tag "Calc" calc)
244 (const :tag "Clojure" clojure)
245 (const :tag "CSS" css)
246 (const :tag "Ditaa" ditaa)
247 (const :tag "Dot" dot)
248 (const :tag "Emacs Lisp" emacs-lisp)
249 (const :tag "Fortran" fortran)
250 (const :tag "Gnuplot" gnuplot)
251 (const :tag "Haskell" haskell)
252 (const :tag "IO" io)
253 (const :tag "Java" java)
254 (const :tag "Javascript" js)
255 (const :tag "LaTeX" latex)
256 (const :tag "Ledger" ledger)
257 (const :tag "Lilypond" lilypond)
258 (const :tag "Lisp" lisp)
259 (const :tag "Makefile" makefile)
260 (const :tag "Maxima" maxima)
261 (const :tag "Matlab" matlab)
262 (const :tag "Mscgen" mscgen)
263 (const :tag "Ocaml" ocaml)
264 (const :tag "Octave" octave)
265 (const :tag "Org" org)
266 (const :tag "Perl" perl)
267 (const :tag "Pico Lisp" picolisp)
268 (const :tag "PlantUML" plantuml)
269 (const :tag "Python" python)
270 (const :tag "Ruby" ruby)
271 (const :tag "Sass" sass)
272 (const :tag "Scala" scala)
273 (const :tag "Scheme" scheme)
274 (const :tag "Screen" screen)
275 (const :tag "Shell Script" sh)
276 (const :tag "Shen" shen)
277 (const :tag "Sql" sql)
278 (const :tag "Sqlite" sqlite))
279 :value-type (boolean :tag "Activate" :value t)))
281 ;;;; Customization variables
282 (defcustom org-clone-delete-id nil
283 "Remove ID property of clones of a subtree.
284 When non-nil, clones of a subtree don't inherit the ID property.
285 Otherwise they inherit the ID property with a new unique
286 identifier."
287 :type 'boolean
288 :version "24.1"
289 :group 'org-id)
291 ;;; Version
292 (org-check-version)
294 ;;;###autoload
295 (defun org-version (&optional here full message)
296 "Show the org-mode version in the echo area.
297 With prefix argument HERE, insert it at point.
298 When FULL is non-nil, use a verbose version string.
299 When MESSAGE is non-nil, display a message with the version."
300 (interactive "P")
301 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
302 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
303 (load-suffixes (list ".el"))
304 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
305 (org-trash (or
306 (and (fboundp 'org-release) (fboundp 'org-git-version))
307 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
308 (load-suffixes save-load-suffixes)
309 (org-version (org-release))
310 (git-version (org-git-version))
311 (version (format "Org-mode version %s (%s @ %s)"
312 org-version
313 git-version
314 (if org-install-dir
315 (if (string= org-dir org-install-dir)
316 org-install-dir
317 (concat "mixed installation! " org-install-dir " and " org-dir))
318 "org-loaddefs.el can not be found!")))
319 (version1 (if full version org-version)))
320 (if (org-called-interactively-p 'interactive)
321 (if here
322 (insert version)
323 (message version))
324 (if message (message version1))
325 version1)))
327 (defconst org-version (org-version))
329 ;;; Compatibility constants
331 ;;; The custom variables
333 (defgroup org nil
334 "Outline-based notes management and organizer."
335 :tag "Org"
336 :group 'outlines
337 :group 'calendar)
339 (defcustom org-mode-hook nil
340 "Mode hook for Org-mode, run after the mode was turned on."
341 :group 'org
342 :type 'hook)
344 (defcustom org-load-hook nil
345 "Hook that is run after org.el has been loaded."
346 :group 'org
347 :type 'hook)
349 (defcustom org-log-buffer-setup-hook nil
350 "Hook that is run after an Org log buffer is created."
351 :group 'org
352 :version "24.1"
353 :type 'hook)
355 (defvar org-modules) ; defined below
356 (defvar org-modules-loaded nil
357 "Have the modules been loaded already?")
359 (defun org-load-modules-maybe (&optional force)
360 "Load all extensions listed in `org-modules'."
361 (when (or force (not org-modules-loaded))
362 (mapc (lambda (ext)
363 (condition-case nil (require ext)
364 (error (message "Problems while trying to load feature `%s'" ext))))
365 org-modules)
366 (setq org-modules-loaded t)))
368 (defun org-set-modules (var value)
369 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
370 (set var value)
371 (when (featurep 'org)
372 (org-load-modules-maybe 'force)))
374 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
375 "Modules that should always be loaded together with org.el.
377 If a description starts with <C>, the file is not part of Emacs
378 and loading it will require that you have downloaded and properly
379 installed the Org mode distribution.
381 You can also use this system to load external packages (i.e. neither Org
382 core modules, nor modules from the CONTRIB directory). Just add symbols
383 to the end of the list. If the package is called org-xyz.el, then you need
384 to add the symbol `xyz', and the package must have a call to:
386 (provide \\='org-xyz)
388 For export specific modules, see also `org-export-backends'."
389 :group 'org
390 :set 'org-set-modules
391 :version "24.4"
392 :package-version '(Org . "8.0")
393 :type
394 '(set :greedy t
395 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
396 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
397 (const :tag " crypt: Encryption of subtrees" org-crypt)
398 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
399 (const :tag " docview: Links to doc-view buffers" org-docview)
400 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
401 (const :tag " habit: Track your consistency with habits" org-habit)
402 (const :tag " id: Global IDs for identifying entries" org-id)
403 (const :tag " info: Links to Info nodes" org-info)
404 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
405 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
406 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
407 (const :tag " mouse: Additional mouse support" org-mouse)
408 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
409 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
410 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
412 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
413 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
414 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
415 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
416 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
417 (const :tag "C collector: Collect properties into tables" org-collector)
418 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
419 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
420 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
421 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
422 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
423 (const :tag "C eval: Include command output as text" org-eval)
424 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
425 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
426 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
427 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
428 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
429 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
430 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
431 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
432 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
433 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
434 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
435 (const :tag "C mew: Links to Mew folders/messages" org-mew)
436 (const :tag "C mtags: Support for muse-like tags" org-mtags)
437 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
438 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
439 (const :tag "C registry: A registry for Org-mode links" org-registry)
440 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
441 (const :tag "C secretary: Team management with org-mode" org-secretary)
442 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
443 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
444 (const :tag "C track: Keep up with Org-mode development" org-track)
445 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
446 (const :tag "C vm: Links to VM folders/messages" org-vm)
447 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
448 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
449 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
451 (defvar org-export--registered-backends) ; From ox.el.
452 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
453 (declare-function org-export-backend-name "ox" (backend) t)
454 (declare-function org-export-backend-options "ox" (cl-x) t)
455 (defcustom org-export-backends '(ascii html icalendar latex)
456 "List of export back-ends that should be always available.
458 If a description starts with <C>, the file is not part of Emacs
459 and loading it will require that you have downloaded and properly
460 installed the Org mode distribution.
462 Unlike to `org-modules', libraries in this list will not be
463 loaded along with Org, but only once the export framework is
464 needed.
466 This variable needs to be set before org.el is loaded. If you
467 need to make a change while Emacs is running, use the customize
468 interface or run the following code, where VAL stands for the new
469 value of the variable, after updating it:
471 (progn
472 (setq org-export--registered-backends
473 (org-remove-if-not
474 (lambda (backend)
475 (let ((name (org-export-backend-name backend)))
476 (or (memq name val)
477 (catch \\='parentp
478 (dolist (b val)
479 (and (org-export-derived-backend-p b name)
480 (throw \\='parentp t)))))))
481 org-export--registered-backends))
482 (let ((new-list (mapcar \\='org-export-backend-name
483 org-export--registered-backends)))
484 (dolist (backend val)
485 (cond
486 ((not (load (format \"ox-%s\" backend) t t))
487 (message \"Problems while trying to load export back-end \\=`%s\\='\"
488 backend))
489 ((not (memq backend new-list)) (push backend new-list))))
490 (set-default \\='org-export-backends new-list)))
492 Adding a back-end to this list will also pull the back-end it
493 depends on, if any."
494 :group 'org
495 :group 'org-export
496 :version "24.4"
497 :package-version '(Org . "8.0")
498 :initialize 'custom-initialize-set
499 :set (lambda (var val)
500 (if (not (featurep 'ox)) (set-default var val)
501 ;; Any back-end not required anymore (not present in VAL and not
502 ;; a parent of any back-end in the new value) is removed from the
503 ;; list of registered back-ends.
504 (setq org-export--registered-backends
505 (org-remove-if-not
506 (lambda (backend)
507 (let ((name (org-export-backend-name backend)))
508 (or (memq name val)
509 (catch 'parentp
510 (dolist (b val)
511 (and (org-export-derived-backend-p b name)
512 (throw 'parentp t)))))))
513 org-export--registered-backends))
514 ;; Now build NEW-LIST of both new back-ends and required
515 ;; parents.
516 (let ((new-list (mapcar 'org-export-backend-name
517 org-export--registered-backends)))
518 (dolist (backend val)
519 (cond
520 ((not (load (format "ox-%s" backend) t t))
521 (message "Problems while trying to load export back-end `%s'"
522 backend))
523 ((not (memq backend new-list)) (push backend new-list))))
524 ;; Set VAR to that list with fixed dependencies.
525 (set-default var new-list))))
526 :type '(set :greedy t
527 (const :tag " ascii Export buffer to ASCII format" ascii)
528 (const :tag " beamer Export buffer to Beamer presentation" beamer)
529 (const :tag " html Export buffer to HTML format" html)
530 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
531 (const :tag " latex Export buffer to LaTeX format" latex)
532 (const :tag " man Export buffer to MAN format" man)
533 (const :tag " md Export buffer to Markdown format" md)
534 (const :tag " odt Export buffer to ODT format" odt)
535 (const :tag " org Export buffer to Org format" org)
536 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
537 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
538 (const :tag "C deck Export buffer to deck.js presentations" deck)
539 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
540 (const :tag "C groff Export buffer to Groff format" groff)
541 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
542 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
543 (const :tag "C s5 Export buffer to s5 presentations" s5)
544 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
546 (eval-after-load 'ox
547 '(mapc
548 (lambda (backend)
549 (condition-case nil (require (intern (format "ox-%s" backend)))
550 (error (message "Problems while trying to load export back-end `%s'"
551 backend))))
552 org-export-backends))
554 (defcustom org-support-shift-select nil
555 "Non-nil means make shift-cursor commands select text when possible.
557 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
558 start selecting a region, or enlarge regions started in this way.
559 In Org-mode, in special contexts, these same keys are used for
560 other purposes, important enough to compete with shift selection.
561 Org tries to balance these needs by supporting `shift-select-mode'
562 outside these special contexts, under control of this variable.
564 The default of this variable is nil, to avoid confusing behavior. Shifted
565 cursor keys will then execute Org commands in the following contexts:
566 - on a headline, changing TODO state (left/right) and priority (up/down)
567 - on a time stamp, changing the time
568 - in a plain list item, changing the bullet type
569 - in a property definition line, switching between allowed values
570 - in the BEGIN line of a clock table (changing the time block).
571 Outside these contexts, the commands will throw an error.
573 When this variable is t and the cursor is not in a special
574 context, Org-mode will support shift-selection for making and
575 enlarging regions. To make this more effective, the bullet
576 cycling will no longer happen anywhere in an item line, but only
577 if the cursor is exactly on the bullet.
579 If you set this variable to the symbol `always', then the keys
580 will not be special in headlines, property lines, and item lines,
581 to make shift selection work there as well. If this is what you
582 want, you can use the following alternative commands: `C-c C-t'
583 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
584 can be used to switch TODO sets, `C-c -' to cycle item bullet
585 types, and properties can be edited by hand or in column view.
587 However, when the cursor is on a timestamp, shift-cursor commands
588 will still edit the time stamp - this is just too good to give up.
590 XEmacs user should have this variable set to nil, because
591 `shift-select-mode' is in Emacs 23 or later only."
592 :group 'org
593 :type '(choice
594 (const :tag "Never" nil)
595 (const :tag "When outside special context" t)
596 (const :tag "Everywhere except timestamps" always)))
598 (defcustom org-loop-over-headlines-in-active-region nil
599 "Shall some commands act upon headlines in the active region?
601 When set to t, some commands will be performed in all headlines
602 within the active region.
604 When set to `start-level', some commands will be performed in all
605 headlines within the active region, provided that these headlines
606 are of the same level than the first one.
608 When set to a string, those commands will be performed on the
609 matching headlines within the active region. Such string must be
610 a tags/property/todo match as it is used in the agenda tags view.
612 The list of commands is: `org-schedule', `org-deadline',
613 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
614 `org-archive-to-archive-sibling'. The archiving commands skip
615 already archived entries."
616 :type '(choice (const :tag "Don't loop" nil)
617 (const :tag "All headlines in active region" t)
618 (const :tag "In active region, headlines at the same level than the first one" start-level)
619 (string :tag "Tags/Property/Todo matcher"))
620 :version "24.1"
621 :group 'org-todo
622 :group 'org-archive)
624 (defgroup org-startup nil
625 "Options concerning startup of Org-mode."
626 :tag "Org Startup"
627 :group 'org)
629 (defcustom org-startup-folded t
630 "Non-nil means entering Org-mode will switch to OVERVIEW.
631 This can also be configured on a per-file basis by adding one of
632 the following lines anywhere in the buffer:
634 #+STARTUP: fold (or `overview', this is equivalent)
635 #+STARTUP: nofold (or `showall', this is equivalent)
636 #+STARTUP: content
637 #+STARTUP: showeverything
639 By default, this option is ignored when Org opens agenda files
640 for the first time. If you want the agenda to honor the startup
641 option, set `org-agenda-inhibit-startup' to nil."
642 :group 'org-startup
643 :type '(choice
644 (const :tag "nofold: show all" nil)
645 (const :tag "fold: overview" t)
646 (const :tag "content: all headlines" content)
647 (const :tag "show everything, even drawers" showeverything)))
649 (defcustom org-startup-truncated t
650 "Non-nil means entering Org-mode will set `truncate-lines'.
651 This is useful since some lines containing links can be very long and
652 uninteresting. Also tables look terrible when wrapped."
653 :group 'org-startup
654 :type 'boolean)
656 (defcustom org-startup-indented nil
657 "Non-nil means turn on `org-indent-mode' on startup.
658 This can also be configured on a per-file basis by adding one of
659 the following lines anywhere in the buffer:
661 #+STARTUP: indent
662 #+STARTUP: noindent"
663 :group 'org-structure
664 :type '(choice
665 (const :tag "Not" nil)
666 (const :tag "Globally (slow on startup in large files)" t)))
668 (defcustom org-use-sub-superscripts t
669 "Non-nil means interpret \"_\" and \"^\" for display.
671 If you want to control how Org exports those characters, see
672 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
673 used to be an alias for `org-export-with-sub-superscripts' in
674 Org <8.0, it is not anymore.
676 When this option is turned on, you can use TeX-like syntax for
677 sub- and superscripts within the buffer. Several characters after
678 \"_\" or \"^\" will be considered as a single item - so grouping
679 with {} is normally not needed. For example, the following things
680 will be parsed as single sub- or superscripts:
682 10^24 or 10^tau several digits will be considered 1 item.
683 10^-12 or 10^-tau a leading sign with digits or a word
684 x^2-y^3 will be read as x^2 - y^3, because items are
685 terminated by almost any nonword/nondigit char.
686 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
688 Still, ambiguity is possible. So when in doubt, use {} to enclose
689 the sub/superscript. If you set this variable to the symbol `{}',
690 the braces are *required* in order to trigger interpretations as
691 sub/superscript. This can be helpful in documents that need \"_\"
692 frequently in plain text."
693 :group 'org-startup
694 :version "24.4"
695 :package-version '(Org . "8.0")
696 :type '(choice
697 (const :tag "Always interpret" t)
698 (const :tag "Only with braces" {})
699 (const :tag "Never interpret" nil)))
701 (defcustom org-startup-with-beamer-mode nil
702 "Non-nil means turn on `org-beamer-mode' on startup.
703 This can also be configured on a per-file basis by adding one of
704 the following lines anywhere in the buffer:
706 #+STARTUP: beamer"
707 :group 'org-startup
708 :version "24.1"
709 :type 'boolean)
711 (defcustom org-startup-align-all-tables nil
712 "Non-nil means align all tables when visiting a file.
713 This is useful when the column width in tables is forced with <N> cookies
714 in table fields. Such tables will look correct only after the first re-align.
715 This can also be configured on a per-file basis by adding one of
716 the following lines anywhere in the buffer:
717 #+STARTUP: align
718 #+STARTUP: noalign"
719 :group 'org-startup
720 :type 'boolean)
722 (defcustom org-startup-with-inline-images nil
723 "Non-nil means show inline images when loading a new Org file.
724 This can also be configured on a per-file basis by adding one of
725 the following lines anywhere in the buffer:
726 #+STARTUP: inlineimages
727 #+STARTUP: noinlineimages"
728 :group 'org-startup
729 :version "24.1"
730 :type 'boolean)
732 (defcustom org-startup-with-latex-preview nil
733 "Non-nil means preview LaTeX fragments when loading a new Org file.
735 This can also be configured on a per-file basis by adding one of
736 the following lines anywhere in the buffer:
737 #+STARTUP: latexpreview
738 #+STARTUP: nolatexpreview"
739 :group 'org-startup
740 :version "24.4"
741 :package-version '(Org . "8.0")
742 :type 'boolean)
744 (defcustom org-insert-mode-line-in-empty-file nil
745 "Non-nil means insert the first line setting Org-mode in empty files.
746 When the function `org-mode' is called interactively in an empty file, this
747 normally means that the file name does not automatically trigger Org-mode.
748 To ensure that the file will always be in Org-mode in the future, a
749 line enforcing Org-mode will be inserted into the buffer, if this option
750 has been set."
751 :group 'org-startup
752 :type 'boolean)
754 (defcustom org-replace-disputed-keys nil
755 "Non-nil means use alternative key bindings for some keys.
756 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
757 These keys are also used by other packages like shift-selection-mode'
758 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
759 If you want to use Org-mode together with one of these other modes,
760 or more generally if you would like to move some Org-mode commands to
761 other keys, set this variable and configure the keys with the variable
762 `org-disputed-keys'.
764 This option is only relevant at load-time of Org-mode, and must be set
765 *before* org.el is loaded. Changing it requires a restart of Emacs to
766 become effective."
767 :group 'org-startup
768 :type 'boolean)
770 (defcustom org-use-extra-keys nil
771 "Non-nil means use extra key sequence definitions for certain commands.
772 This happens automatically if you run XEmacs or if `window-system'
773 is nil. This variable lets you do the same manually. You must
774 set it before loading org.
776 Example: on Carbon Emacs 22 running graphically, with an external
777 keyboard on a Powerbook, the default way of setting M-left might
778 not work for either Alt or ESC. Setting this variable will make
779 it work for ESC."
780 :group 'org-startup
781 :type 'boolean)
783 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
785 (defcustom org-disputed-keys
786 '(([(shift up)] . [(meta p)])
787 ([(shift down)] . [(meta n)])
788 ([(shift left)] . [(meta -)])
789 ([(shift right)] . [(meta +)])
790 ([(control shift right)] . [(meta shift +)])
791 ([(control shift left)] . [(meta shift -)]))
792 "Keys for which Org-mode and other modes compete.
793 This is an alist, cars are the default keys, second element specifies
794 the alternative to use when `org-replace-disputed-keys' is t.
796 Keys can be specified in any syntax supported by `define-key'.
797 The value of this option takes effect only at Org-mode's startup,
798 therefore you'll have to restart Emacs to apply it after changing."
799 :group 'org-startup
800 :type 'alist)
802 (defun org-key (key)
803 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
804 Or return the original if not disputed.
805 Also apply the translations defined in `org-xemacs-key-equivalents'."
806 (when org-replace-disputed-keys
807 (let* ((nkey (key-description key))
808 (x (org-find-if (lambda (x)
809 (equal (key-description (car x)) nkey))
810 org-disputed-keys)))
811 (setq key (if x (cdr x) key))))
812 (when (featurep 'xemacs)
813 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
814 key)
816 (defun org-find-if (predicate seq)
817 (catch 'exit
818 (while seq
819 (if (funcall predicate (car seq))
820 (throw 'exit (car seq))
821 (pop seq)))))
823 (defun org-defkey (keymap key def)
824 "Define a key, possibly translated, as returned by `org-key'."
825 (define-key keymap (org-key key) def))
827 (defcustom org-ellipsis nil
828 "The ellipsis to use in the Org-mode outline.
829 When nil, just use the standard three dots.
830 When a string, use that string instead.
831 When a face, use the standard 3 dots, but with the specified face.
832 The change affects only Org-mode (which will then use its own display table).
833 Changing this requires executing `\\[org-mode]' in a buffer to become
834 effective."
835 :group 'org-startup
836 :type '(choice (const :tag "Default" nil)
837 (face :tag "Face" :value org-warning)
838 (string :tag "String" :value "...#")))
840 (defvar org-display-table nil
841 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
843 (defgroup org-keywords nil
844 "Keywords in Org-mode."
845 :tag "Org Keywords"
846 :group 'org)
848 (defcustom org-deadline-string "DEADLINE:"
849 "String to mark deadline entries.
850 A deadline is this string, followed by a time stamp. Should be a word,
851 terminated by a colon. You can insert a schedule keyword and
852 a timestamp with \\[org-deadline].
853 Changes become only effective after restarting Emacs."
854 :group 'org-keywords
855 :type 'string)
857 (defcustom org-scheduled-string "SCHEDULED:"
858 "String to mark scheduled TODO entries.
859 A schedule is this string, followed by a time stamp. Should be a word,
860 terminated by a colon. You can insert a schedule keyword and
861 a timestamp with \\[org-schedule].
862 Changes become only effective after restarting Emacs."
863 :group 'org-keywords
864 :type 'string)
866 (defcustom org-closed-string "CLOSED:"
867 "String used as the prefix for timestamps logging closing a TODO entry."
868 :group 'org-keywords
869 :type 'string)
871 (defcustom org-clock-string "CLOCK:"
872 "String used as prefix for timestamps clocking work hours on an item."
873 :group 'org-keywords
874 :type 'string)
876 (defcustom org-closed-keep-when-no-todo nil
877 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
878 :group 'org-todo
879 :group 'org-keywords
880 :version "24.4"
881 :package-version '(Org . "8.0")
882 :type 'boolean)
884 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
885 org-scheduled-string "\\|"
886 org-deadline-string "\\|"
887 org-closed-string "\\|"
888 org-clock-string "\\)")
889 "Matches a line with planning or clock info.")
891 (defcustom org-comment-string "COMMENT"
892 "Entries starting with this keyword will never be exported.
893 An entry can be toggled between COMMENT and normal with
894 \\[org-toggle-comment].
895 Changes become only effective after restarting Emacs."
896 :group 'org-keywords
897 :type 'string)
899 (defcustom org-quote-string "QUOTE"
900 "Entries starting with this keyword will be exported in fixed-width font.
901 Quoting applies only to the text in the entry following the headline, and does
902 not extend beyond the next headline, even if that is lower level.
903 An entry can be toggled between QUOTE and normal with
904 \\[org-toggle-fixed-width-section]."
905 :group 'org-keywords
906 :type 'string)
908 (defconst org-repeat-re
909 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
910 "Regular expression for specifying repeated events.
911 After a match, group 1 contains the repeat expression.")
913 (defgroup org-structure nil
914 "Options concerning the general structure of Org-mode files."
915 :tag "Org Structure"
916 :group 'org)
918 (defgroup org-reveal-location nil
919 "Options about how to make context of a location visible."
920 :tag "Org Reveal Location"
921 :group 'org-structure)
923 (defconst org-context-choice
924 '(choice
925 (const :tag "Always" t)
926 (const :tag "Never" nil)
927 (repeat :greedy t :tag "Individual contexts"
928 (cons
929 (choice :tag "Context"
930 (const agenda)
931 (const org-goto)
932 (const occur-tree)
933 (const tags-tree)
934 (const link-search)
935 (const mark-goto)
936 (const bookmark-jump)
937 (const isearch)
938 (const default))
939 (boolean))))
940 "Contexts for the reveal options.")
942 (defcustom org-show-hierarchy-above '((default . t))
943 "Non-nil means show full hierarchy when revealing a location.
944 Org-mode often shows locations in an org-mode file which might have
945 been invisible before. When this is set, the hierarchy of headings
946 above the exposed location is shown.
947 Turning this off for example for sparse trees makes them very compact.
948 Instead of t, this can also be an alist specifying this option for different
949 contexts. Valid contexts are
950 agenda when exposing an entry from the agenda
951 org-goto when using the command `org-goto' on key C-c C-j
952 occur-tree when using the command `org-occur' on key C-c /
953 tags-tree when constructing a sparse tree based on tags matches
954 link-search when exposing search matches associated with a link
955 mark-goto when exposing the jump goal of a mark
956 bookmark-jump when exposing a bookmark location
957 isearch when exiting from an incremental search
958 default default for all contexts not set explicitly"
959 :group 'org-reveal-location
960 :type org-context-choice)
962 (defcustom org-show-following-heading '((default . nil))
963 "Non-nil means show following heading when revealing a location.
964 Org-mode often shows locations in an org-mode file which might have
965 been invisible before. When this is set, the heading following the
966 match is shown.
967 Turning this off for example for sparse trees makes them very compact,
968 but makes it harder to edit the location of the match. In such a case,
969 use the command \\[org-reveal] to show more context.
970 Instead of t, this can also be an alist specifying this option for different
971 contexts. See `org-show-hierarchy-above' for valid contexts."
972 :group 'org-reveal-location
973 :type org-context-choice)
975 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
976 "Non-nil means show all sibling heading when revealing a location.
977 Org-mode often shows locations in an org-mode file which might have
978 been invisible before. When this is set, the sibling of the current entry
979 heading are all made visible. If `org-show-hierarchy-above' is t,
980 the same happens on each level of the hierarchy above the current entry.
982 By default this is on for the isearch context, off for all other contexts.
983 Turning this off for example for sparse trees makes them very compact,
984 but makes it harder to edit the location of the match. In such a case,
985 use the command \\[org-reveal] to show more context.
986 Instead of t, this can also be an alist specifying this option for different
987 contexts. See `org-show-hierarchy-above' for valid contexts."
988 :group 'org-reveal-location
989 :type org-context-choice
990 :version "24.4"
991 :package-version '(Org . "8.0"))
993 (defcustom org-show-entry-below '((default . nil))
994 "Non-nil means show the entry below a headline when revealing a location.
995 Org-mode often shows locations in an org-mode file which might have
996 been invisible before. When this is set, the text below the headline that is
997 exposed is also shown.
999 By default this is off for all contexts.
1000 Instead of t, this can also be an alist specifying this option for different
1001 contexts. See `org-show-hierarchy-above' for valid contexts."
1002 :group 'org-reveal-location
1003 :type org-context-choice)
1005 (defcustom org-indirect-buffer-display 'other-window
1006 "How should indirect tree buffers be displayed?
1007 This applies to indirect buffers created with the commands
1008 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1009 Valid values are:
1010 current-window Display in the current window
1011 other-window Just display in another window.
1012 dedicated-frame Create one new frame, and re-use it each time.
1013 new-frame Make a new frame each time. Note that in this case
1014 previously-made indirect buffers are kept, and you need to
1015 kill these buffers yourself."
1016 :group 'org-structure
1017 :group 'org-agenda-windows
1018 :type '(choice
1019 (const :tag "In current window" current-window)
1020 (const :tag "In current frame, other window" other-window)
1021 (const :tag "Each time a new frame" new-frame)
1022 (const :tag "One dedicated frame" dedicated-frame)))
1024 (defcustom org-use-speed-commands nil
1025 "Non-nil means activate single letter commands at beginning of a headline.
1026 This may also be a function to test for appropriate locations where speed
1027 commands should be active."
1028 :group 'org-structure
1029 :type '(choice
1030 (const :tag "Never" nil)
1031 (const :tag "At beginning of headline stars" t)
1032 (function)))
1034 (defcustom org-speed-commands-user nil
1035 "Alist of additional speed commands.
1036 This list will be checked before `org-speed-commands-default'
1037 when the variable `org-use-speed-commands' is non-nil
1038 and when the cursor is at the beginning of a headline.
1039 The car if each entry is a string with a single letter, which must
1040 be assigned to `self-insert-command' in the global map.
1041 The cdr is either a command to be called interactively, a function
1042 to be called, or a form to be evaluated.
1043 An entry that is just a list with a single string will be interpreted
1044 as a descriptive headline that will be added when listing the speed
1045 commands in the Help buffer using the `?' speed command."
1046 :group 'org-structure
1047 :type '(repeat :value ("k" . ignore)
1048 (choice :value ("k" . ignore)
1049 (list :tag "Descriptive Headline" (string :tag "Headline"))
1050 (cons :tag "Letter and Command"
1051 (string :tag "Command letter")
1052 (choice
1053 (function)
1054 (sexp))))))
1056 (defcustom org-bookmark-names-plist
1057 '(:last-capture "org-capture-last-stored"
1058 :last-refile "org-refile-last-stored"
1059 :last-capture-marker "org-capture-last-stored-marker")
1060 "Names for bookmarks automatically set by some Org commands.
1061 This can provide strings as names for a number of bookmarks Org sets
1062 automatically. The following keys are currently implemented:
1063 :last-capture
1064 :last-capture-marker
1065 :last-refile
1066 When a key does not show up in the property list, the corresponding bookmark
1067 is not set."
1068 :group 'org-structure
1069 :type 'plist)
1071 (defgroup org-cycle nil
1072 "Options concerning visibility cycling in Org-mode."
1073 :tag "Org Cycle"
1074 :group 'org-structure)
1076 (defcustom org-cycle-skip-children-state-if-no-children t
1077 "Non-nil means skip CHILDREN state in entries that don't have any."
1078 :group 'org-cycle
1079 :type 'boolean)
1081 (defcustom org-cycle-max-level nil
1082 "Maximum level which should still be subject to visibility cycling.
1083 Levels higher than this will, for cycling, be treated as text, not a headline.
1084 When `org-odd-levels-only' is set, a value of N in this variable actually
1085 means 2N-1 stars as the limiting headline.
1086 When nil, cycle all levels.
1087 Note that the limiting level of cycling is also influenced by
1088 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1089 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1090 than its value."
1091 :group 'org-cycle
1092 :type '(choice
1093 (const :tag "No limit" nil)
1094 (integer :tag "Maximum level")))
1096 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1097 "Names of drawers. Drawers are not opened by cycling on the headline above.
1098 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1099 this:
1100 :DRAWERNAME:
1101 .....
1102 :END:
1103 The drawer \"PROPERTIES\" is special for capturing properties through
1104 the property API.
1106 Drawers can be defined on the per-file basis with a line like:
1108 #+DRAWERS: HIDDEN STATE PROPERTIES"
1109 :group 'org-structure
1110 :group 'org-cycle
1111 :type '(repeat (string :tag "Drawer Name")))
1113 (defcustom org-hide-block-startup nil
1114 "Non-nil means entering Org-mode will fold all blocks.
1115 This can also be set in on a per-file basis with
1117 #+STARTUP: hideblocks
1118 #+STARTUP: showblocks"
1119 :group 'org-startup
1120 :group 'org-cycle
1121 :type 'boolean)
1123 (defcustom org-cycle-global-at-bob nil
1124 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1125 This makes it possible to do global cycling without having to use S-TAB or
1126 \\[universal-argument] TAB. For this special case to work, the first line
1127 of the buffer must not be a headline -- it may be empty or some other text.
1128 When used in this way, `org-cycle-hook' is disabled temporarily to make
1129 sure the cursor stays at the beginning of the buffer. When this option is
1130 nil, don't do anything special at the beginning of the buffer."
1131 :group 'org-cycle
1132 :type 'boolean)
1134 (defcustom org-cycle-level-after-item/entry-creation t
1135 "Non-nil means cycle entry level or item indentation in new empty entries.
1137 When the cursor is at the end of an empty headline, i.e., with only stars
1138 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1139 and then all possible ancestor states, before returning to the original state.
1140 This makes data entry extremely fast: M-RET to create a new headline,
1141 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1143 When the cursor is at the end of an empty plain list item, one TAB will
1144 make it a subitem, two or more tabs will back up to make this an item
1145 higher up in the item hierarchy."
1146 :group 'org-cycle
1147 :type 'boolean)
1149 (defcustom org-cycle-emulate-tab t
1150 "Where should `org-cycle' emulate TAB.
1151 nil Never
1152 white Only in completely white lines
1153 whitestart Only at the beginning of lines, before the first non-white char
1154 t Everywhere except in headlines
1155 exc-hl-bol Everywhere except at the start of a headline
1156 If TAB is used in a place where it does not emulate TAB, the current subtree
1157 visibility is cycled."
1158 :group 'org-cycle
1159 :type '(choice (const :tag "Never" nil)
1160 (const :tag "Only in completely white lines" white)
1161 (const :tag "Before first char in a line" whitestart)
1162 (const :tag "Everywhere except in headlines" t)
1163 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1165 (defcustom org-cycle-separator-lines 2
1166 "Number of empty lines needed to keep an empty line between collapsed trees.
1167 If you leave an empty line between the end of a subtree and the following
1168 headline, this empty line is hidden when the subtree is folded.
1169 Org-mode will leave (exactly) one empty line visible if the number of
1170 empty lines is equal or larger to the number given in this variable.
1171 So the default 2 means at least 2 empty lines after the end of a subtree
1172 are needed to produce free space between a collapsed subtree and the
1173 following headline.
1175 If the number is negative, and the number of empty lines is at least -N,
1176 all empty lines are shown.
1178 Special case: when 0, never leave empty lines in collapsed view."
1179 :group 'org-cycle
1180 :type 'integer)
1181 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1183 (defcustom org-pre-cycle-hook nil
1184 "Hook that is run before visibility cycling is happening.
1185 The function(s) in this hook must accept a single argument which indicates
1186 the new state that will be set right after running this hook. The
1187 argument is a symbol. Before a global state change, it can have the values
1188 `overview', `content', or `all'. Before a local state change, it can have
1189 the values `folded', `children', or `subtree'."
1190 :group 'org-cycle
1191 :type 'hook)
1193 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1194 org-cycle-hide-drawers
1195 org-cycle-hide-inline-tasks
1196 org-cycle-show-empty-lines
1197 org-optimize-window-after-visibility-change)
1198 "Hook that is run after `org-cycle' has changed the buffer visibility.
1199 The function(s) in this hook must accept a single argument which indicates
1200 the new state that was set by the most recent `org-cycle' command. The
1201 argument is a symbol. After a global state change, it can have the values
1202 `overview', `contents', or `all'. After a local state change, it can have
1203 the values `folded', `children', or `subtree'."
1204 :group 'org-cycle
1205 :type 'hook)
1207 (defgroup org-edit-structure nil
1208 "Options concerning structure editing in Org-mode."
1209 :tag "Org Edit Structure"
1210 :group 'org-structure)
1212 (defcustom org-odd-levels-only nil
1213 "Non-nil means skip even levels and only use odd levels for the outline.
1214 This has the effect that two stars are being added/taken away in
1215 promotion/demotion commands. It also influences how levels are
1216 handled by the exporters.
1217 Changing it requires restart of `font-lock-mode' to become effective
1218 for fontification also in regions already fontified.
1219 You may also set this on a per-file basis by adding one of the following
1220 lines to the buffer:
1222 #+STARTUP: odd
1223 #+STARTUP: oddeven"
1224 :group 'org-edit-structure
1225 :group 'org-appearance
1226 :type 'boolean)
1228 (defcustom org-adapt-indentation t
1229 "Non-nil means adapt indentation to outline node level.
1231 When this variable is set, Org assumes that you write outlines by
1232 indenting text in each node to align with the headline (after the stars).
1233 The following issues are influenced by this variable:
1235 - When this is set and the *entire* text in an entry is indented, the
1236 indentation is increased by one space in a demotion command, and
1237 decreased by one in a promotion command. If any line in the entry
1238 body starts with text at column 0, indentation is not changed at all.
1240 - Property drawers and planning information is inserted indented when
1241 this variable s set. When nil, they will not be indented.
1243 - TAB indents a line relative to context. The lines below a headline
1244 will be indented when this variable is set.
1246 Note that this is all about true indentation, by adding and removing
1247 space characters. See also `org-indent.el' which does level-dependent
1248 indentation in a virtual way, i.e. at display time in Emacs."
1249 :group 'org-edit-structure
1250 :type 'boolean)
1252 (defcustom org-special-ctrl-a/e nil
1253 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1255 When t, `C-a' will bring back the cursor to the beginning of the
1256 headline text, i.e. after the stars and after a possible TODO
1257 keyword. In an item, this will be the position after bullet and
1258 check-box, if any. When the cursor is already at that position,
1259 another `C-a' will bring it to the beginning of the line.
1261 `C-e' will jump to the end of the headline, ignoring the presence
1262 of tags in the headline. A second `C-e' will then jump to the
1263 true end of the line, after any tags. This also means that, when
1264 this variable is non-nil, `C-e' also will never jump beyond the
1265 end of the heading of a folded section, i.e. not after the
1266 ellipses.
1268 When set to the symbol `reversed', the first `C-a' or `C-e' works
1269 normally, going to the true line boundary first. Only a directly
1270 following, identical keypress will bring the cursor to the
1271 special positions.
1273 This may also be a cons cell where the behavior for `C-a' and
1274 `C-e' is set separately."
1275 :group 'org-edit-structure
1276 :type '(choice
1277 (const :tag "off" nil)
1278 (const :tag "on: after stars/bullet and before tags first" t)
1279 (const :tag "reversed: true line boundary first" reversed)
1280 (cons :tag "Set C-a and C-e separately"
1281 (choice :tag "Special C-a"
1282 (const :tag "off" nil)
1283 (const :tag "on: after stars/bullet first" t)
1284 (const :tag "reversed: before stars/bullet first" reversed))
1285 (choice :tag "Special C-e"
1286 (const :tag "off" nil)
1287 (const :tag "on: before tags first" t)
1288 (const :tag "reversed: after tags first" reversed)))))
1289 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1291 (defcustom org-special-ctrl-k nil
1292 "Non-nil means `C-k' will behave specially in headlines.
1293 When nil, `C-k' will call the default `kill-line' command.
1294 When t, the following will happen while the cursor is in the headline:
1296 - When the cursor is at the beginning of a headline, kill the entire
1297 line and possible the folded subtree below the line.
1298 - When in the middle of the headline text, kill the headline up to the tags.
1299 - When after the headline text, kill the tags."
1300 :group 'org-edit-structure
1301 :type 'boolean)
1303 (defcustom org-ctrl-k-protect-subtree nil
1304 "Non-nil means, do not delete a hidden subtree with C-k.
1305 When set to the symbol `error', simply throw an error when C-k is
1306 used to kill (part-of) a headline that has hidden text behind it.
1307 Any other non-nil value will result in a query to the user, if it is
1308 OK to kill that hidden subtree. When nil, kill without remorse."
1309 :group 'org-edit-structure
1310 :version "24.1"
1311 :type '(choice
1312 (const :tag "Do not protect hidden subtrees" nil)
1313 (const :tag "Protect hidden subtrees with a security query" t)
1314 (const :tag "Never kill a hidden subtree with C-k" error)))
1316 (defcustom org-special-ctrl-o t
1317 "Non-nil means, make `C-o' insert a row in tables."
1318 :group 'org-edit-structure
1319 :type 'boolean)
1321 (defcustom org-catch-invisible-edits nil
1322 "Check if in invisible region before inserting or deleting a character.
1323 Valid values are:
1325 nil Do not check, so just do invisible edits.
1326 error Throw an error and do nothing.
1327 show Make point visible, and do the requested edit.
1328 show-and-error Make point visible, then throw an error and abort the edit.
1329 smart Make point visible, and do insertion/deletion if it is
1330 adjacent to visible text and the change feels predictable.
1331 Never delete a previously invisible character or add in the
1332 middle or right after an invisible region. Basically, this
1333 allows insertion and backward-delete right before ellipses.
1334 FIXME: maybe in this case we should not even show?"
1335 :group 'org-edit-structure
1336 :version "24.1"
1337 :type '(choice
1338 (const :tag "Do not check" nil)
1339 (const :tag "Throw error when trying to edit" error)
1340 (const :tag "Unhide, but do not do the edit" show-and-error)
1341 (const :tag "Show invisible part and do the edit" show)
1342 (const :tag "Be smart and do the right thing" smart)))
1344 (defcustom org-yank-folded-subtrees t
1345 "Non-nil means when yanking subtrees, fold them.
1346 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1347 it starts with a heading and all other headings in it are either children
1348 or siblings, then fold all the subtrees. However, do this only if no
1349 text after the yank would be swallowed into a folded tree by this action."
1350 :group 'org-edit-structure
1351 :type 'boolean)
1353 (defcustom org-yank-adjusted-subtrees nil
1354 "Non-nil means when yanking subtrees, adjust the level.
1355 With this setting, `org-paste-subtree' is used to insert the subtree, see
1356 this function for details."
1357 :group 'org-edit-structure
1358 :type 'boolean)
1360 (defcustom org-M-RET-may-split-line '((default . t))
1361 "Non-nil means M-RET will split the line at the cursor position.
1362 When nil, it will go to the end of the line before making a
1363 new line.
1364 You may also set this option in a different way for different
1365 contexts. Valid contexts are:
1367 headline when creating a new headline
1368 item when creating a new item
1369 table in a table field
1370 default the value to be used for all contexts not explicitly
1371 customized"
1372 :group 'org-structure
1373 :group 'org-table
1374 :type '(choice
1375 (const :tag "Always" t)
1376 (const :tag "Never" nil)
1377 (repeat :greedy t :tag "Individual contexts"
1378 (cons
1379 (choice :tag "Context"
1380 (const headline)
1381 (const item)
1382 (const table)
1383 (const default))
1384 (boolean)))))
1387 (defcustom org-insert-heading-respect-content nil
1388 "Non-nil means insert new headings after the current subtree.
1389 When nil, the new heading is created directly after the current line.
1390 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1391 this variable on for the duration of the command."
1392 :group 'org-structure
1393 :type 'boolean)
1395 (defcustom org-blank-before-new-entry '((heading . auto)
1396 (plain-list-item . auto))
1397 "Should `org-insert-heading' leave a blank line before new heading/item?
1398 The value is an alist, with `heading' and `plain-list-item' as CAR,
1399 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1400 which case Org will look at the surrounding headings/items and try to
1401 make an intelligent decision whether to insert a blank line or not.
1403 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1404 the setting here is ignored and no empty line is inserted to avoid breaking
1405 the list structure."
1406 :group 'org-edit-structure
1407 :type '(list
1408 (cons (const heading)
1409 (choice (const :tag "Never" nil)
1410 (const :tag "Always" t)
1411 (const :tag "Auto" auto)))
1412 (cons (const plain-list-item)
1413 (choice (const :tag "Never" nil)
1414 (const :tag "Always" t)
1415 (const :tag "Auto" auto)))))
1417 (defcustom org-insert-heading-hook nil
1418 "Hook being run after inserting a new heading."
1419 :group 'org-edit-structure
1420 :type 'hook)
1422 (defcustom org-enable-fixed-width-editor t
1423 "Non-nil means lines starting with \":\" are treated as fixed-width.
1424 This currently only means they are never auto-wrapped.
1425 When nil, such lines will be treated like ordinary lines.
1426 See also the QUOTE keyword."
1427 :group 'org-edit-structure
1428 :type 'boolean)
1430 (defcustom org-goto-auto-isearch t
1431 "Non-nil means typing characters in `org-goto' starts incremental search.
1432 When nil, you can use these keybindings to navigate the buffer:
1434 q Quit the org-goto interface
1435 n Go to the next visible heading
1436 p Go to the previous visible heading
1437 f Go one heading forward on same level
1438 b Go one heading backward on same level
1439 u Go one heading up"
1440 :group 'org-edit-structure
1441 :type 'boolean)
1443 (defgroup org-sparse-trees nil
1444 "Options concerning sparse trees in Org-mode."
1445 :tag "Org Sparse Trees"
1446 :group 'org-structure)
1448 (defcustom org-highlight-sparse-tree-matches t
1449 "Non-nil means highlight all matches that define a sparse tree.
1450 The highlights will automatically disappear the next time the buffer is
1451 changed by an edit command."
1452 :group 'org-sparse-trees
1453 :type 'boolean)
1455 (defcustom org-remove-highlights-with-change t
1456 "Non-nil means any change to the buffer will remove temporary highlights.
1457 Such highlights are created by `org-occur' and `org-clock-display'.
1458 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1459 The highlights created by `org-preview-latex-fragment' always need
1460 `C-c C-c' to be removed."
1461 :group 'org-sparse-trees
1462 :group 'org-time
1463 :type 'boolean)
1466 (defcustom org-occur-hook '(org-first-headline-recenter)
1467 "Hook that is run after `org-occur' has constructed a sparse tree.
1468 This can be used to recenter the window to show as much of the structure
1469 as possible."
1470 :group 'org-sparse-trees
1471 :type 'hook)
1473 (defgroup org-imenu-and-speedbar nil
1474 "Options concerning imenu and speedbar in Org-mode."
1475 :tag "Org Imenu and Speedbar"
1476 :group 'org-structure)
1478 (defcustom org-imenu-depth 2
1479 "The maximum level for Imenu access to Org-mode headlines.
1480 This also applied for speedbar access."
1481 :group 'org-imenu-and-speedbar
1482 :type 'integer)
1484 (defgroup org-table nil
1485 "Options concerning tables in Org-mode."
1486 :tag "Org Table"
1487 :group 'org)
1489 (defcustom org-enable-table-editor 'optimized
1490 "Non-nil means lines starting with \"|\" are handled by the table editor.
1491 When nil, such lines will be treated like ordinary lines.
1493 When equal to the symbol `optimized', the table editor will be optimized to
1494 do the following:
1495 - Automatic overwrite mode in front of whitespace in table fields.
1496 This makes the structure of the table stay in tact as long as the edited
1497 field does not exceed the column width.
1498 - Minimize the number of realigns. Normally, the table is aligned each time
1499 TAB or RET are pressed to move to another field. With optimization this
1500 happens only if changes to a field might have changed the column width.
1501 Optimization requires replacing the functions `self-insert-command',
1502 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1503 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1504 very good at guessing when a re-align will be necessary, but you can always
1505 force one with \\[org-ctrl-c-ctrl-c].
1507 If you would like to use the optimized version in Org-mode, but the
1508 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1510 This variable can be used to turn on and off the table editor during a session,
1511 but in order to toggle optimization, a restart is required.
1513 See also the variable `org-table-auto-blank-field'."
1514 :group 'org-table
1515 :type '(choice
1516 (const :tag "off" nil)
1517 (const :tag "on" t)
1518 (const :tag "on, optimized" optimized)))
1520 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1521 (version<= emacs-version "24.1"))
1522 "Non-nil means cluster self-insert commands for undo when possible.
1523 If this is set, then, like in the Emacs command loop, 20 consecutive
1524 characters will be undone together.
1525 This is configurable, because there is some impact on typing performance."
1526 :group 'org-table
1527 :type 'boolean)
1529 (defcustom org-table-tab-recognizes-table.el t
1530 "Non-nil means TAB will automatically notice a table.el table.
1531 When it sees such a table, it moves point into it and - if necessary -
1532 calls `table-recognize-table'."
1533 :group 'org-table-editing
1534 :type 'boolean)
1536 (defgroup org-link nil
1537 "Options concerning links in Org-mode."
1538 :tag "Org Link"
1539 :group 'org)
1541 (defvar org-link-abbrev-alist-local nil
1542 "Buffer-local version of `org-link-abbrev-alist', which see.
1543 The value of this is taken from the #+LINK lines.")
1544 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1546 (defcustom org-link-abbrev-alist nil
1547 "Alist of link abbreviations.
1548 The car of each element is a string, to be replaced at the start of a link.
1549 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1550 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1552 [[linkkey:tag][description]]
1554 The `linkkey' must be a word word, starting with a letter, followed
1555 by letters, numbers, `-' or `_'.
1557 If REPLACE is a string, the tag will simply be appended to create the link.
1558 If the string contains \"%s\", the tag will be inserted there. If the string
1559 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1560 at that point (see the function `url-hexify-string'). If the string contains
1561 the specifier \"%(my-function)\", then the custom function `my-function' will
1562 be invoked: this function takes the tag as its only argument and must return
1563 a string.
1565 REPLACE may also be a function that will be called with the tag as the
1566 only argument to create the link, which should be returned as a string.
1568 See the manual for examples."
1569 :group 'org-link
1570 :type '(repeat
1571 (cons
1572 (string :tag "Protocol")
1573 (choice
1574 (string :tag "Format")
1575 (function)))))
1577 (defcustom org-descriptive-links t
1578 "Non-nil means Org will display descriptive links.
1579 E.g. [[http://orgmode.org][Org website]] will be displayed as
1580 \"Org Website\", hiding the link itself and just displaying its
1581 description. When set to nil, Org will display the full links
1582 literally.
1584 You can interactively set the value of this variable by calling
1585 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1586 :group 'org-link
1587 :type 'boolean)
1589 (defcustom org-link-file-path-type 'adaptive
1590 "How the path name in file links should be stored.
1591 Valid values are:
1593 relative Relative to the current directory, i.e. the directory of the file
1594 into which the link is being inserted.
1595 absolute Absolute path, if possible with ~ for home directory.
1596 noabbrev Absolute path, no abbreviation of home directory.
1597 adaptive Use relative path for files in the current directory and sub-
1598 directories of it. For other files, use an absolute path."
1599 :group 'org-link
1600 :type '(choice
1601 (const relative)
1602 (const absolute)
1603 (const noabbrev)
1604 (const adaptive)))
1606 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1607 "Types of links that should be activated in Org-mode files.
1608 This is a list of symbols, each leading to the activation of a certain link
1609 type. In principle, it does not hurt to turn on most link types - there may
1610 be a small gain when turning off unused link types. The types are:
1612 bracket The recommended [[link][description]] or [[link]] links with hiding.
1613 angle Links in angular brackets that may contain whitespace like
1614 <bbdb:Carsten Dominik>.
1615 plain Plain links in normal text, no whitespace, like http://google.com.
1616 radio Text that is matched by a radio target, see manual for details.
1617 tag Tag settings in a headline (link to tag search).
1618 date Time stamps (link to calendar).
1619 footnote Footnote labels.
1621 Changing this variable requires a restart of Emacs to become effective."
1622 :group 'org-link
1623 :type '(set :greedy t
1624 (const :tag "Double bracket links" bracket)
1625 (const :tag "Angular bracket links" angle)
1626 (const :tag "Plain text links" plain)
1627 (const :tag "Radio target matches" radio)
1628 (const :tag "Tags" tag)
1629 (const :tag "Timestamps" date)
1630 (const :tag "Footnotes" footnote)))
1632 (defcustom org-make-link-description-function nil
1633 "Function to use for generating link descriptions from links.
1634 When nil, the link location will be used. This function must take
1635 two parameters: the first one is the link, the second one is the
1636 description generated by `org-insert-link'. The function should
1637 return the description to use."
1638 :group 'org-link
1639 :type '(choice (const nil) (function)))
1641 (defgroup org-link-store nil
1642 "Options concerning storing links in Org-mode."
1643 :tag "Org Store Link"
1644 :group 'org-link)
1646 (defcustom org-url-hexify-p t
1647 "When non-nil, hexify URL when creating a link."
1648 :type 'boolean
1649 :version "24.3"
1650 :group 'org-link-store)
1652 (defcustom org-email-link-description-format "Email %c: %.30s"
1653 "Format of the description part of a link to an email or usenet message.
1654 The following %-escapes will be replaced by corresponding information:
1656 %F full \"From\" field
1657 %f name, taken from \"From\" field, address if no name
1658 %T full \"To\" field
1659 %t first name in \"To\" field, address if no name
1660 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1661 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1662 %s subject
1663 %d date
1664 %m message-id.
1666 You may use normal field width specification between the % and the letter.
1667 This is for example useful to limit the length of the subject.
1669 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1670 :group 'org-link-store
1671 :type 'string)
1673 (defcustom org-from-is-user-regexp
1674 (let (r1 r2)
1675 (when (and user-mail-address (not (string= user-mail-address "")))
1676 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1677 (when (and user-full-name (not (string= user-full-name "")))
1678 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1679 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1680 "Regexp matched against the \"From:\" header of an email or usenet message.
1681 It should match if the message is from the user him/herself."
1682 :group 'org-link-store
1683 :type 'regexp)
1685 (defcustom org-context-in-file-links t
1686 "Non-nil means file links from `org-store-link' contain context.
1687 A search string will be added to the file name with :: as separator and
1688 used to find the context when the link is activated by the command
1689 `org-open-at-point'. When this option is t, the entire active region
1690 will be placed in the search string of the file link. If set to a
1691 positive integer, only the first n lines of context will be stored.
1693 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1694 negates this setting for the duration of the command."
1695 :group 'org-link-store
1696 :type '(choice boolean integer))
1698 (defcustom org-keep-stored-link-after-insertion nil
1699 "Non-nil means keep link in list for entire session.
1701 The command `org-store-link' adds a link pointing to the current
1702 location to an internal list. These links accumulate during a session.
1703 The command `org-insert-link' can be used to insert links into any
1704 Org-mode file (offering completion for all stored links). When this
1705 option is nil, every link which has been inserted once using \\[org-insert-link]
1706 will be removed from the list, to make completing the unused links
1707 more efficient."
1708 :group 'org-link-store
1709 :type 'boolean)
1711 (defgroup org-link-follow nil
1712 "Options concerning following links in Org-mode."
1713 :tag "Org Follow Link"
1714 :group 'org-link)
1716 (defcustom org-link-translation-function nil
1717 "Function to translate links with different syntax to Org syntax.
1718 This can be used to translate links created for example by the Planner
1719 or emacs-wiki packages to Org syntax.
1720 The function must accept two parameters, a TYPE containing the link
1721 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1722 which is everything after the link protocol. It should return a cons
1723 with possibly modified values of type and path.
1724 Org contains a function for this, so if you set this variable to
1725 `org-translate-link-from-planner', you should be able follow many
1726 links created by planner."
1727 :group 'org-link-follow
1728 :type '(choice (const nil) (function)))
1730 (defcustom org-follow-link-hook nil
1731 "Hook that is run after a link has been followed."
1732 :group 'org-link-follow
1733 :type 'hook)
1735 (defcustom org-tab-follows-link nil
1736 "Non-nil means on links TAB will follow the link.
1737 Needs to be set before org.el is loaded.
1738 This really should not be used, it does not make sense, and the
1739 implementation is bad."
1740 :group 'org-link-follow
1741 :type 'boolean)
1743 (defcustom org-return-follows-link nil
1744 "Non-nil means on links RET will follow the link.
1745 In tables, the special behavior of RET has precedence."
1746 :group 'org-link-follow
1747 :type 'boolean)
1749 (defcustom org-mouse-1-follows-link
1750 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1751 "Non-nil means mouse-1 on a link will follow the link.
1752 A longer mouse click will still set point. Does not work on XEmacs.
1753 Needs to be set before org.el is loaded."
1754 :group 'org-link-follow
1755 :version "24.4"
1756 :package-version '(Org . "8.3")
1757 :type '(choice
1758 (const :tag "A double click follows the link" double)
1759 (const :tag "Unconditionally follow the link with mouse-1" t)
1760 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1762 (defcustom org-mark-ring-length 4
1763 "Number of different positions to be recorded in the ring.
1764 Changing this requires a restart of Emacs to work correctly."
1765 :group 'org-link-follow
1766 :type 'integer)
1768 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1769 "Non-nil means internal links in Org files must exactly match a headline.
1770 When nil, the link search tries to match a phrase with all words
1771 in the search text."
1772 :group 'org-link-follow
1773 :version "24.1"
1774 :type '(choice
1775 (const :tag "Use fuzzy text search" nil)
1776 (const :tag "Match only exact headline" t)
1777 (const :tag "Match exact headline or query to create it"
1778 query-to-create)))
1780 (defcustom org-link-frame-setup
1781 '((vm . vm-visit-folder-other-frame)
1782 (vm-imap . vm-visit-imap-folder-other-frame)
1783 (gnus . org-gnus-no-new-news)
1784 (file . find-file-other-window)
1785 (wl . wl-other-frame))
1786 "Setup the frame configuration for following links.
1787 When following a link with Emacs, it may often be useful to display
1788 this link in another window or frame. This variable can be used to
1789 set this up for the different types of links.
1790 For VM, use any of
1791 `vm-visit-folder'
1792 `vm-visit-folder-other-window'
1793 `vm-visit-folder-other-frame'
1794 For Gnus, use any of
1795 `gnus'
1796 `gnus-other-frame'
1797 `org-gnus-no-new-news'
1798 For FILE, use any of
1799 `find-file'
1800 `find-file-other-window'
1801 `find-file-other-frame'
1802 For Wanderlust use any of
1803 `wl'
1804 `wl-other-frame'
1805 For the calendar, use the variable `calendar-setup'.
1806 For BBDB, it is currently only possible to display the matches in
1807 another window."
1808 :group 'org-link-follow
1809 :type '(list
1810 (cons (const vm)
1811 (choice
1812 (const vm-visit-folder)
1813 (const vm-visit-folder-other-window)
1814 (const vm-visit-folder-other-frame)))
1815 (cons (const vm-imap)
1816 (choice
1817 (const vm-visit-imap-folder)
1818 (const vm-visit-imap-folder-other-window)
1819 (const vm-visit-imap-folder-other-frame)))
1820 (cons (const gnus)
1821 (choice
1822 (const gnus)
1823 (const gnus-other-frame)
1824 (const org-gnus-no-new-news)))
1825 (cons (const file)
1826 (choice
1827 (const find-file)
1828 (const find-file-other-window)
1829 (const find-file-other-frame)))
1830 (cons (const wl)
1831 (choice
1832 (const wl)
1833 (const wl-other-frame)))))
1835 (defcustom org-display-internal-link-with-indirect-buffer nil
1836 "Non-nil means use indirect buffer to display infile links.
1837 Activating internal links (from one location in a file to another location
1838 in the same file) normally just jumps to the location. When the link is
1839 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1840 is displayed in
1841 another window. When this option is set, the other window actually displays
1842 an indirect buffer clone of the current buffer, to avoid any visibility
1843 changes to the current buffer."
1844 :group 'org-link-follow
1845 :type 'boolean)
1847 (defcustom org-open-non-existing-files nil
1848 "Non-nil means `org-open-file' will open non-existing files.
1849 When nil, an error will be generated.
1850 This variable applies only to external applications because they
1851 might choke on non-existing files. If the link is to a file that
1852 will be opened in Emacs, the variable is ignored."
1853 :group 'org-link-follow
1854 :type 'boolean)
1856 (defcustom org-open-directory-means-index-dot-org nil
1857 "Non-nil means a link to a directory really means to index.org.
1858 When nil, following a directory link will run dired or open a finder/explorer
1859 window on that directory."
1860 :group 'org-link-follow
1861 :type 'boolean)
1863 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1864 "Function and arguments to call for following mailto links.
1865 This is a list with the first element being a Lisp function, and the
1866 remaining elements being arguments to the function. In string arguments,
1867 %a will be replaced by the address, and %s will be replaced by the subject
1868 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1869 :group 'org-link-follow
1870 :type '(choice
1871 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1872 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1873 (const :tag "message-mail" (message-mail "%a" "%s"))
1874 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1876 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1877 "Non-nil means ask for confirmation before executing shell links.
1878 Shell links can be dangerous: just think about a link
1880 [[shell:rm -rf ~/*][Google Search]]
1882 This link would show up in your Org-mode document as \"Google Search\",
1883 but really it would remove your entire home directory.
1884 Therefore we advise against setting this variable to nil.
1885 Just change it to `y-or-n-p' if you want to confirm with a
1886 single keystroke rather than having to type \"yes\"."
1887 :group 'org-link-follow
1888 :type '(choice
1889 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1890 (const :tag "with y-or-n (faster)" y-or-n-p)
1891 (const :tag "no confirmation (dangerous)" nil)))
1892 (put 'org-confirm-shell-link-function
1893 'safe-local-variable
1894 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1896 (defcustom org-confirm-shell-link-not-regexp ""
1897 "A regexp to skip confirmation for shell links."
1898 :group 'org-link-follow
1899 :version "24.1"
1900 :type 'regexp)
1902 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1903 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1904 Elisp links can be dangerous: just think about a link
1906 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1908 This link would show up in your Org-mode document as \"Google Search\",
1909 but really it would remove your entire home directory.
1910 Therefore we advise against setting this variable to nil.
1911 Just change it to `y-or-n-p' if you want to confirm with a
1912 single keystroke rather than having to type \"yes\"."
1913 :group 'org-link-follow
1914 :type '(choice
1915 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1916 (const :tag "with y-or-n (faster)" y-or-n-p)
1917 (const :tag "no confirmation (dangerous)" nil)))
1918 (put 'org-confirm-shell-link-function
1919 'safe-local-variable
1920 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1922 (defcustom org-confirm-elisp-link-not-regexp ""
1923 "A regexp to skip confirmation for Elisp links."
1924 :group 'org-link-follow
1925 :version "24.1"
1926 :type 'regexp)
1928 (defconst org-file-apps-defaults-gnu
1929 '((remote . emacs)
1930 (system . mailcap)
1931 (t . mailcap))
1932 "Default file applications on a UNIX or GNU/Linux system.
1933 See `org-file-apps'.")
1935 (defconst org-file-apps-defaults-macosx
1936 '((remote . emacs)
1937 (t . "open %s")
1938 (system . "open %s")
1939 ("ps.gz" . "gv %s")
1940 ("eps.gz" . "gv %s")
1941 ("dvi" . "xdvi %s")
1942 ("fig" . "xfig %s"))
1943 "Default file applications on a macOS system.
1944 The system \"open\" is known as a default, but we use X11 applications
1945 for some files for which the OS does not have a good default.
1946 See `org-file-apps'.")
1948 (defconst org-file-apps-defaults-windowsnt
1949 (list
1950 '(remote . emacs)
1951 (cons t
1952 (list (if (featurep 'xemacs)
1953 'mswindows-shell-execute
1954 'w32-shell-execute)
1955 "open" 'file))
1956 (cons 'system
1957 (list (if (featurep 'xemacs)
1958 'mswindows-shell-execute
1959 'w32-shell-execute)
1960 "open" 'file)))
1961 "Default file applications on a Windows NT system.
1962 The system \"open\" is used for most files.
1963 See `org-file-apps'.")
1965 (defcustom org-file-apps
1966 '((auto-mode . emacs)
1967 ("\\.mm\\'" . default)
1968 ("\\.x?html?\\'" . default)
1969 ("\\.pdf\\'" . default))
1970 "External applications for opening `file:path' items in a document.
1971 Org-mode uses system defaults for different file types, but
1972 you can use this variable to set the application for a given file
1973 extension. The entries in this list are cons cells where the car identifies
1974 files and the cdr the corresponding command. Possible values for the
1975 file identifier are
1976 \"string\" A string as a file identifier can be interpreted in different
1977 ways, depending on its contents:
1979 - Alphanumeric characters only:
1980 Match links with this file extension.
1981 Example: (\"pdf\" . \"evince %s\")
1982 to open PDFs with evince.
1984 - Regular expression: Match links where the
1985 filename matches the regexp. If you want to
1986 use groups here, use shy groups.
1988 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
1989 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1990 to open *.html and *.xhtml with firefox.
1992 - Regular expression which contains (non-shy) groups:
1993 Match links where the whole link, including \"::\", and
1994 anything after that, matches the regexp.
1995 In a custom command string, %1, %2, etc. are replaced with
1996 the parts of the link that were matched by the groups.
1997 For backwards compatibility, if a command string is given
1998 that does not use any of the group matches, this case is
1999 handled identically to the second one (i.e. match against
2000 file name only).
2001 In a custom lisp form, you can access the group matches with
2002 (match-string n link).
2004 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2005 to open [[file:document.pdf::5]] with evince at page 5.
2007 `directory' Matches a directory
2008 `remote' Matches a remote file, accessible through tramp or efs.
2009 Remote files most likely should be visited through Emacs
2010 because external applications cannot handle such paths.
2011 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2012 so all files Emacs knows how to handle. Using this with
2013 command `emacs' will open most files in Emacs. Beware that this
2014 will also open html files inside Emacs, unless you add
2015 (\"html\" . default) to the list as well.
2016 t Default for files not matched by any of the other options.
2017 `system' The system command to open files, like `open' on Windows
2018 and macOS, and mailcap under GNU/Linux. This is the command
2019 that will be selected if you call `C-c C-o' with a double
2020 \\[universal-argument] \\[universal-argument] prefix.
2022 Possible values for the command are:
2023 `emacs' The file will be visited by the current Emacs process.
2024 `default' Use the default application for this file type, which is the
2025 association for t in the list, most likely in the system-specific
2026 part.
2027 This can be used to overrule an unwanted setting in the
2028 system-specific variable.
2029 `system' Use the system command for opening files, like \"open\".
2030 This command is specified by the entry whose car is `system'.
2031 Most likely, the system-specific version of this variable
2032 does define this command, but you can overrule/replace it
2033 here.
2034 string A command to be executed by a shell; %s will be replaced
2035 by the path to the file.
2036 sexp A Lisp form which will be evaluated. The file path will
2037 be available in the Lisp variable `file'.
2038 For more examples, see the system specific constants
2039 `org-file-apps-defaults-macosx'
2040 `org-file-apps-defaults-windowsnt'
2041 `org-file-apps-defaults-gnu'."
2042 :group 'org-link-follow
2043 :type '(repeat
2044 (cons (choice :value ""
2045 (string :tag "Extension")
2046 (const :tag "System command to open files" system)
2047 (const :tag "Default for unrecognized files" t)
2048 (const :tag "Remote file" remote)
2049 (const :tag "Links to a directory" directory)
2050 (const :tag "Any files that have Emacs modes"
2051 auto-mode))
2052 (choice :value ""
2053 (const :tag "Visit with Emacs" emacs)
2054 (const :tag "Use default" default)
2055 (const :tag "Use the system command" system)
2056 (string :tag "Command")
2057 (sexp :tag "Lisp form")))))
2059 (defcustom org-doi-server-url "http://dx.doi.org/"
2060 "The URL of the DOI server."
2061 :type 'string
2062 :version "24.3"
2063 :group 'org-link-follow)
2065 (defgroup org-refile nil
2066 "Options concerning refiling entries in Org-mode."
2067 :tag "Org Refile"
2068 :group 'org)
2070 (defcustom org-directory "~/org"
2071 "Directory with org files.
2072 This is just a default location to look for Org files. There is no need
2073 at all to put your files into this directory. It is only used in the
2074 following situations:
2076 1. When a capture template specifies a target file that is not an
2077 absolute path. The path will then be interpreted relative to
2078 `org-directory'
2079 2. When a capture note is filed away in an interactive way (when exiting the
2080 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2081 with `org-directory' as the default path."
2082 :group 'org-refile
2083 :group 'org-capture
2084 :type 'directory)
2086 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2087 "Default target for storing notes.
2088 Used as a fall back file for org-capture.el, for templates that
2089 do not specify a target file."
2090 :group 'org-refile
2091 :group 'org-capture
2092 :type '(choice
2093 (const :tag "Default from remember-data-file" nil)
2094 file))
2096 (defcustom org-goto-interface 'outline
2097 "The default interface to be used for `org-goto'.
2098 Allowed values are:
2099 outline The interface shows an outline of the relevant file
2100 and the correct heading is found by moving through
2101 the outline or by searching with incremental search.
2102 outline-path-completion Headlines in the current buffer are offered via
2103 completion. This is the interface also used by
2104 the refile command."
2105 :group 'org-refile
2106 :type '(choice
2107 (const :tag "Outline" outline)
2108 (const :tag "Outline-path-completion" outline-path-completion)))
2110 (defcustom org-goto-max-level 5
2111 "Maximum target level when running `org-goto' with refile interface."
2112 :group 'org-refile
2113 :type 'integer)
2115 (defcustom org-reverse-note-order nil
2116 "Non-nil means store new notes at the beginning of a file or entry.
2117 When nil, new notes will be filed to the end of a file or entry.
2118 This can also be a list with cons cells of regular expressions that
2119 are matched against file names, and values."
2120 :group 'org-capture
2121 :group 'org-refile
2122 :type '(choice
2123 (const :tag "Reverse always" t)
2124 (const :tag "Reverse never" nil)
2125 (repeat :tag "By file name regexp"
2126 (cons regexp boolean))))
2128 (defcustom org-log-refile nil
2129 "Information to record when a task is refiled.
2131 Possible values are:
2133 nil Don't add anything
2134 time Add a time stamp to the task
2135 note Prompt for a note and add it with template `org-log-note-headings'
2137 This option can also be set with on a per-file-basis with
2139 #+STARTUP: nologrefile
2140 #+STARTUP: logrefile
2141 #+STARTUP: lognoterefile
2143 You can have local logging settings for a subtree by setting the LOGGING
2144 property to one or more of these keywords.
2146 When bulk-refiling from the agenda, the value `note' is forbidden and
2147 will temporarily be changed to `time'."
2148 :group 'org-refile
2149 :group 'org-progress
2150 :version "24.1"
2151 :type '(choice
2152 (const :tag "No logging" nil)
2153 (const :tag "Record timestamp" time)
2154 (const :tag "Record timestamp with note." note)))
2156 (defcustom org-refile-targets nil
2157 "Targets for refiling entries with \\[org-refile].
2158 This is a list of cons cells. Each cell contains:
2159 - a specification of the files to be considered, either a list of files,
2160 or a symbol whose function or variable value will be used to retrieve
2161 a file name or a list of file names. If you use `org-agenda-files' for
2162 that, all agenda files will be scanned for targets. Nil means consider
2163 headings in the current buffer.
2164 - A specification of how to find candidate refile targets. This may be
2165 any of:
2166 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2167 This tag has to be present in all target headlines, inheritance will
2168 not be considered.
2169 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2170 todo keyword.
2171 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2172 headlines that are refiling targets.
2173 - a cons cell (:level . N). Any headline of level N is considered a target.
2174 Note that, when `org-odd-levels-only' is set, level corresponds to
2175 order in hierarchy, not to the number of stars.
2176 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2177 Note that, when `org-odd-levels-only' is set, level corresponds to
2178 order in hierarchy, not to the number of stars.
2180 Each element of this list generates a set of possible targets.
2181 The union of these sets is presented (with completion) to
2182 the user by `org-refile'.
2184 You can set the variable `org-refile-target-verify-function' to a function
2185 to verify each headline found by the simple criteria above.
2187 When this variable is nil, all top-level headlines in the current buffer
2188 are used, equivalent to the value `((nil . (:level . 1))'."
2189 :group 'org-refile
2190 :type '(repeat
2191 (cons
2192 (choice :value org-agenda-files
2193 (const :tag "All agenda files" org-agenda-files)
2194 (const :tag "Current buffer" nil)
2195 (function) (variable) (file))
2196 (choice :tag "Identify target headline by"
2197 (cons :tag "Specific tag" (const :value :tag) (string))
2198 (cons :tag "TODO keyword" (const :value :todo) (string))
2199 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2200 (cons :tag "Level number" (const :value :level) (integer))
2201 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2203 (defcustom org-refile-target-verify-function nil
2204 "Function to verify if the headline at point should be a refile target.
2205 The function will be called without arguments, with point at the
2206 beginning of the headline. It should return t and leave point
2207 where it is if the headline is a valid target for refiling.
2209 If the target should not be selected, the function must return nil.
2210 In addition to this, it may move point to a place from where the search
2211 should be continued. For example, the function may decide that the entire
2212 subtree of the current entry should be excluded and move point to the end
2213 of the subtree."
2214 :group 'org-refile
2215 :type '(choice
2216 (const nil)
2217 (function)))
2219 (defcustom org-refile-use-cache nil
2220 "Non-nil means cache refile targets to speed up the process.
2221 The cache for a particular file will be updated automatically when
2222 the buffer has been killed, or when any of the marker used for flagging
2223 refile targets no longer points at a live buffer.
2224 If you have added new entries to a buffer that might themselves be targets,
2225 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2226 find that easier, `C-u C-u C-u C-c C-w'."
2227 :group 'org-refile
2228 :version "24.1"
2229 :type 'boolean)
2231 (defcustom org-refile-use-outline-path nil
2232 "Non-nil means provide refile targets as paths.
2233 So a level 3 headline will be available as level1/level2/level3.
2235 When the value is `file', also include the file name (without directory)
2236 into the path. In this case, you can also stop the completion after
2237 the file name, to get entries inserted as top level in the file.
2239 When `full-file-path', include the full file path."
2240 :group 'org-refile
2241 :type '(choice
2242 (const :tag "Not" nil)
2243 (const :tag "Yes" t)
2244 (const :tag "Start with file name" file)
2245 (const :tag "Start with full file path" full-file-path)))
2247 (defcustom org-outline-path-complete-in-steps t
2248 "Non-nil means complete the outline path in hierarchical steps.
2249 When Org-mode uses the refile interface to select an outline path
2250 \(see variable `org-refile-use-outline-path'), the completion of
2251 the path can be done is a single go, or if can be done in steps down
2252 the headline hierarchy. Going in steps is probably the best if you
2253 do not use a special completion package like `ido' or `icicles'.
2254 However, when using these packages, going in one step can be very
2255 fast, while still showing the whole path to the entry."
2256 :group 'org-refile
2257 :type 'boolean)
2259 (defcustom org-refile-allow-creating-parent-nodes nil
2260 "Non-nil means allow the creation of new nodes as refile targets.
2261 New nodes are then created by adding \"/new node name\" to the completion
2262 of an existing node. When the value of this variable is `confirm',
2263 new node creation must be confirmed by the user (recommended).
2264 When nil, the completion must match an existing entry.
2266 Note that, if the new heading is not seen by the criteria
2267 listed in `org-refile-targets', multiple instances of the same
2268 heading would be created by trying again to file under the new
2269 heading."
2270 :group 'org-refile
2271 :type '(choice
2272 (const :tag "Never" nil)
2273 (const :tag "Always" t)
2274 (const :tag "Prompt for confirmation" confirm)))
2276 (defcustom org-refile-active-region-within-subtree nil
2277 "Non-nil means also refile active region within a subtree.
2279 By default `org-refile' doesn't allow refiling regions if they
2280 don't contain a set of subtrees, but it might be convenient to
2281 do so sometimes: in that case, the first line of the region is
2282 converted to a headline before refiling."
2283 :group 'org-refile
2284 :version "24.1"
2285 :type 'boolean)
2287 (defgroup org-todo nil
2288 "Options concerning TODO items in Org-mode."
2289 :tag "Org TODO"
2290 :group 'org)
2292 (defgroup org-progress nil
2293 "Options concerning Progress logging in Org-mode."
2294 :tag "Org Progress"
2295 :group 'org-time)
2297 (defvar org-todo-interpretation-widgets
2298 '((:tag "Sequence (cycling hits every state)" sequence)
2299 (:tag "Type (cycling directly to DONE)" type))
2300 "The available interpretation symbols for customizing `org-todo-keywords'.
2301 Interested libraries should add to this list.")
2303 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2304 "List of TODO entry keyword sequences and their interpretation.
2305 \\<org-mode-map>This is a list of sequences.
2307 Each sequence starts with a symbol, either `sequence' or `type',
2308 indicating if the keywords should be interpreted as a sequence of
2309 action steps, or as different types of TODO items. The first
2310 keywords are states requiring action - these states will select a headline
2311 for inclusion into the global TODO list Org-mode produces. If one of
2312 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2313 signify that no further action is necessary. If \"|\" is not found,
2314 the last keyword is treated as the only DONE state of the sequence.
2316 The command \\[org-todo] cycles an entry through these states, and one
2317 additional state where no keyword is present. For details about this
2318 cycling, see the manual.
2320 TODO keywords and interpretation can also be set on a per-file basis with
2321 the special #+SEQ_TODO and #+TYP_TODO lines.
2323 Each keyword can optionally specify a character for fast state selection
2324 \(in combination with the variable `org-use-fast-todo-selection')
2325 and specifiers for state change logging, using the same syntax that
2326 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2327 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2328 indicates to record a time stamp each time this state is selected.
2330 Each keyword may also specify if a timestamp or a note should be
2331 recorded when entering or leaving the state, by adding additional
2332 characters in the parenthesis after the keyword. This looks like this:
2333 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2334 record only the time of the state change. With X and Y being either
2335 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2336 Y when leaving the state if and only if the *target* state does not
2337 define X. You may omit any of the fast-selection key or X or /Y,
2338 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2340 For backward compatibility, this variable may also be just a list
2341 of keywords. In this case the interpretation (sequence or type) will be
2342 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2343 :group 'org-todo
2344 :group 'org-keywords
2345 :type '(choice
2346 (repeat :tag "Old syntax, just keywords"
2347 (string :tag "Keyword"))
2348 (repeat :tag "New syntax"
2349 (cons
2350 (choice
2351 :tag "Interpretation"
2352 ;;Quick and dirty way to see
2353 ;;`org-todo-interpretations'. This takes the
2354 ;;place of item arguments
2355 :convert-widget
2356 (lambda (widget)
2357 (widget-put widget
2358 :args (mapcar
2359 #'(lambda (x)
2360 (widget-convert
2361 (cons 'const x)))
2362 org-todo-interpretation-widgets))
2363 widget))
2364 (repeat
2365 (string :tag "Keyword"))))))
2367 (defvar org-todo-keywords-1 nil
2368 "All TODO and DONE keywords active in a buffer.")
2369 (make-variable-buffer-local 'org-todo-keywords-1)
2370 (defvar org-todo-keywords-for-agenda nil)
2371 (defvar org-done-keywords-for-agenda nil)
2372 (defvar org-drawers-for-agenda nil)
2373 (defvar org-todo-keyword-alist-for-agenda nil)
2374 (defvar org-tag-alist-for-agenda nil
2375 "Alist of all tags from all agenda files.")
2376 (defvar org-tag-groups-alist-for-agenda nil
2377 "Alist of all groups tags from all current agenda files.")
2378 (defvar org-tag-groups-alist nil)
2379 (make-variable-buffer-local 'org-tag-groups-alist)
2380 (defvar org-agenda-contributing-files nil)
2381 (defvar org-not-done-keywords nil)
2382 (make-variable-buffer-local 'org-not-done-keywords)
2383 (defvar org-done-keywords nil)
2384 (make-variable-buffer-local 'org-done-keywords)
2385 (defvar org-todo-heads nil)
2386 (make-variable-buffer-local 'org-todo-heads)
2387 (defvar org-todo-sets nil)
2388 (make-variable-buffer-local 'org-todo-sets)
2389 (defvar org-todo-log-states nil)
2390 (make-variable-buffer-local 'org-todo-log-states)
2391 (defvar org-todo-kwd-alist nil)
2392 (make-variable-buffer-local 'org-todo-kwd-alist)
2393 (defvar org-todo-key-alist nil)
2394 (make-variable-buffer-local 'org-todo-key-alist)
2395 (defvar org-todo-key-trigger nil)
2396 (make-variable-buffer-local 'org-todo-key-trigger)
2398 (defcustom org-todo-interpretation 'sequence
2399 "Controls how TODO keywords are interpreted.
2400 This variable is in principle obsolete and is only used for
2401 backward compatibility, if the interpretation of todo keywords is
2402 not given already in `org-todo-keywords'. See that variable for
2403 more information."
2404 :group 'org-todo
2405 :group 'org-keywords
2406 :type '(choice (const sequence)
2407 (const type)))
2409 (defcustom org-use-fast-todo-selection t
2410 "Non-nil means use the fast todo selection scheme with C-c C-t.
2411 This variable describes if and under what circumstances the cycling
2412 mechanism for TODO keywords will be replaced by a single-key, direct
2413 selection scheme.
2415 When nil, fast selection is never used.
2417 When the symbol `prefix', it will be used when `org-todo' is called
2418 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2419 `C-u t' in an agenda buffer.
2421 When t, fast selection is used by default. In this case, the prefix
2422 argument forces cycling instead.
2424 In all cases, the special interface is only used if access keys have
2425 actually been assigned by the user, i.e. if keywords in the configuration
2426 are followed by a letter in parenthesis, like TODO(t)."
2427 :group 'org-todo
2428 :type '(choice
2429 (const :tag "Never" nil)
2430 (const :tag "By default" t)
2431 (const :tag "Only with C-u C-c C-t" prefix)))
2433 (defcustom org-provide-todo-statistics t
2434 "Non-nil means update todo statistics after insert and toggle.
2435 ALL-HEADLINES means update todo statistics by including headlines
2436 with no TODO keyword as well, counting them as not done.
2437 A list of TODO keywords means the same, but skip keywords that are
2438 not in this list.
2440 When this is set, todo statistics is updated in the parent of the
2441 current entry each time a todo state is changed."
2442 :group 'org-todo
2443 :type '(choice
2444 (const :tag "Yes, only for TODO entries" t)
2445 (const :tag "Yes, including all entries" all-headlines)
2446 (repeat :tag "Yes, for TODOs in this list"
2447 (string :tag "TODO keyword"))
2448 (other :tag "No TODO statistics" nil)))
2450 (defcustom org-hierarchical-todo-statistics t
2451 "Non-nil means TODO statistics covers just direct children.
2452 When nil, all entries in the subtree are considered.
2453 This has only an effect if `org-provide-todo-statistics' is set.
2454 To set this to nil for only a single subtree, use a COOKIE_DATA
2455 property and include the word \"recursive\" into the value."
2456 :group 'org-todo
2457 :type 'boolean)
2459 (defcustom org-after-todo-state-change-hook nil
2460 "Hook which is run after the state of a TODO item was changed.
2461 The new state (a string with a TODO keyword, or nil) is available in the
2462 Lisp variable `org-state'."
2463 :group 'org-todo
2464 :type 'hook)
2466 (defvar org-blocker-hook nil
2467 "Hook for functions that are allowed to block a state change.
2469 Functions in this hook should not modify the buffer.
2470 Each function gets as its single argument a property list,
2471 see `org-trigger-hook' for more information about this list.
2473 If any of the functions in this hook returns nil, the state change
2474 is blocked.")
2476 (defvar org-trigger-hook nil
2477 "Hook for functions that are triggered by a state change.
2479 Each function gets as its single argument a property list with at
2480 least the following elements:
2482 (:type type-of-change :position pos-at-entry-start
2483 :from old-state :to new-state)
2485 Depending on the type, more properties may be present.
2487 This mechanism is currently implemented for:
2489 TODO state changes
2490 ------------------
2491 :type todo-state-change
2492 :from previous state (keyword as a string), or nil, or a symbol
2493 `todo' or `done', to indicate the general type of state.
2494 :to new state, like in :from")
2496 (defcustom org-enforce-todo-dependencies nil
2497 "Non-nil means undone TODO entries will block switching the parent to DONE.
2498 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2499 be blocked if any prior sibling is not yet done.
2500 Finally, if the parent is blocked because of ordered siblings of its own,
2501 the child will also be blocked."
2502 :set (lambda (var val)
2503 (set var val)
2504 (if val
2505 (add-hook 'org-blocker-hook
2506 'org-block-todo-from-children-or-siblings-or-parent)
2507 (remove-hook 'org-blocker-hook
2508 'org-block-todo-from-children-or-siblings-or-parent)))
2509 :group 'org-todo
2510 :type 'boolean)
2512 (defcustom org-enforce-todo-checkbox-dependencies nil
2513 "Non-nil means unchecked boxes will block switching the parent to DONE.
2514 When this is nil, checkboxes have no influence on switching TODO states.
2515 When non-nil, you first need to check off all check boxes before the TODO
2516 entry can be switched to DONE.
2517 This variable needs to be set before org.el is loaded, and you need to
2518 restart Emacs after a change to make the change effective. The only way
2519 to change is while Emacs is running is through the customize interface."
2520 :set (lambda (var val)
2521 (set var val)
2522 (if val
2523 (add-hook 'org-blocker-hook
2524 'org-block-todo-from-checkboxes)
2525 (remove-hook 'org-blocker-hook
2526 'org-block-todo-from-checkboxes)))
2527 :group 'org-todo
2528 :type 'boolean)
2530 (defcustom org-treat-insert-todo-heading-as-state-change nil
2531 "Non-nil means inserting a TODO heading is treated as state change.
2532 So when the command \\[org-insert-todo-heading] is used, state change
2533 logging will apply if appropriate. When nil, the new TODO item will
2534 be inserted directly, and no logging will take place."
2535 :group 'org-todo
2536 :type 'boolean)
2538 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2539 "Non-nil means switching TODO states with S-cursor counts as state change.
2540 This is the default behavior. However, setting this to nil allows a
2541 convenient way to select a TODO state and bypass any logging associated
2542 with that."
2543 :group 'org-todo
2544 :type 'boolean)
2546 (defcustom org-todo-state-tags-triggers nil
2547 "Tag changes that should be triggered by TODO state changes.
2548 This is a list. Each entry is
2550 (state-change (tag . flag) .......)
2552 State-change can be a string with a state, and empty string to indicate the
2553 state that has no TODO keyword, or it can be one of the symbols `todo'
2554 or `done', meaning any not-done or done state, respectively."
2555 :group 'org-todo
2556 :group 'org-tags
2557 :type '(repeat
2558 (cons (choice :tag "When changing to"
2559 (const :tag "Not-done state" todo)
2560 (const :tag "Done state" done)
2561 (string :tag "State"))
2562 (repeat
2563 (cons :tag "Tag action"
2564 (string :tag "Tag")
2565 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2567 (defcustom org-log-done nil
2568 "Information to record when a task moves to the DONE state.
2570 Possible values are:
2572 nil Don't add anything, just change the keyword
2573 time Add a time stamp to the task
2574 note Prompt for a note and add it with template `org-log-note-headings'
2576 This option can also be set with on a per-file-basis with
2578 #+STARTUP: nologdone
2579 #+STARTUP: logdone
2580 #+STARTUP: lognotedone
2582 You can have local logging settings for a subtree by setting the LOGGING
2583 property to one or more of these keywords."
2584 :group 'org-todo
2585 :group 'org-progress
2586 :type '(choice
2587 (const :tag "No logging" nil)
2588 (const :tag "Record CLOSED timestamp" time)
2589 (const :tag "Record CLOSED timestamp with note." note)))
2591 ;; Normalize old uses of org-log-done.
2592 (cond
2593 ((eq org-log-done t) (setq org-log-done 'time))
2594 ((and (listp org-log-done) (memq 'done org-log-done))
2595 (setq org-log-done 'note)))
2597 (defcustom org-log-reschedule nil
2598 "Information to record when the scheduling date of a tasks is modified.
2600 Possible values are:
2602 nil Don't add anything, just change the date
2603 time Add a time stamp to the task
2604 note Prompt for a note and add it with template `org-log-note-headings'
2606 This option can also be set with on a per-file-basis with
2608 #+STARTUP: nologreschedule
2609 #+STARTUP: logreschedule
2610 #+STARTUP: lognotereschedule"
2611 :group 'org-todo
2612 :group 'org-progress
2613 :type '(choice
2614 (const :tag "No logging" nil)
2615 (const :tag "Record timestamp" time)
2616 (const :tag "Record timestamp with note." note)))
2618 (defcustom org-log-redeadline nil
2619 "Information to record when the deadline date of a tasks is modified.
2621 Possible values are:
2623 nil Don't add anything, just change the date
2624 time Add a time stamp to the task
2625 note Prompt for a note and add it with template `org-log-note-headings'
2627 This option can also be set with on a per-file-basis with
2629 #+STARTUP: nologredeadline
2630 #+STARTUP: logredeadline
2631 #+STARTUP: lognoteredeadline
2633 You can have local logging settings for a subtree by setting the LOGGING
2634 property to one or more of these keywords."
2635 :group 'org-todo
2636 :group 'org-progress
2637 :type '(choice
2638 (const :tag "No logging" nil)
2639 (const :tag "Record timestamp" time)
2640 (const :tag "Record timestamp with note." note)))
2642 (defcustom org-log-note-clock-out nil
2643 "Non-nil means record a note when clocking out of an item.
2644 This can also be configured on a per-file basis by adding one of
2645 the following lines anywhere in the buffer:
2647 #+STARTUP: lognoteclock-out
2648 #+STARTUP: nolognoteclock-out"
2649 :group 'org-todo
2650 :group 'org-progress
2651 :type 'boolean)
2653 (defcustom org-log-done-with-time t
2654 "Non-nil means the CLOSED time stamp will contain date and time.
2655 When nil, only the date will be recorded."
2656 :group 'org-progress
2657 :type 'boolean)
2659 (defcustom org-log-note-headings
2660 '((done . "CLOSING NOTE %t")
2661 (state . "State %-12s from %-12S %t")
2662 (note . "Note taken on %t")
2663 (reschedule . "Rescheduled from %S on %t")
2664 (delschedule . "Not scheduled, was %S on %t")
2665 (redeadline . "New deadline from %S on %t")
2666 (deldeadline . "Removed deadline, was %S on %t")
2667 (refile . "Refiled on %t")
2668 (clock-out . ""))
2669 "Headings for notes added to entries.
2670 The value is an alist, with the car being a symbol indicating the note
2671 context, and the cdr is the heading to be used. The heading may also be the
2672 empty string.
2673 %t in the heading will be replaced by a time stamp.
2674 %T will be an active time stamp instead the default inactive one
2675 %d will be replaced by a short-format time stamp.
2676 %D will be replaced by an active short-format time stamp.
2677 %s will be replaced by the new TODO state, in double quotes.
2678 %S will be replaced by the old TODO state, in double quotes.
2679 %u will be replaced by the user name.
2680 %U will be replaced by the full user name.
2682 In fact, it is not a good idea to change the `state' entry, because
2683 agenda log mode depends on the format of these entries."
2684 :group 'org-todo
2685 :group 'org-progress
2686 :type '(list :greedy t
2687 (cons (const :tag "Heading when closing an item" done) string)
2688 (cons (const :tag
2689 "Heading when changing todo state (todo sequence only)"
2690 state) string)
2691 (cons (const :tag "Heading when just taking a note" note) string)
2692 (cons (const :tag "Heading when rescheduling" reschedule) string)
2693 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2694 (cons (const :tag "Heading when changing deadline" redeadline) string)
2695 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2696 (cons (const :tag "Heading when refiling" refile) string)
2697 (cons (const :tag "Heading when clocking out" clock-out) string)))
2699 (unless (assq 'note org-log-note-headings)
2700 (push '(note . "%t") org-log-note-headings))
2702 (defcustom org-log-into-drawer nil
2703 "Non-nil means insert state change notes and time stamps into a drawer.
2704 When nil, state changes notes will be inserted after the headline and
2705 any scheduling and clock lines, but not inside a drawer.
2707 The value of this variable should be the name of the drawer to use.
2708 LOGBOOK is proposed as the default drawer for this purpose, you can
2709 also set this to a string to define the drawer of your choice.
2711 A value of t is also allowed, representing \"LOGBOOK\".
2713 A value of t or nil can also be set with on a per-file-basis with
2715 #+STARTUP: logdrawer
2716 #+STARTUP: nologdrawer
2718 If this variable is set, `org-log-state-notes-insert-after-drawers'
2719 will be ignored.
2721 You can set the property LOG_INTO_DRAWER to overrule this setting for
2722 a subtree."
2723 :group 'org-todo
2724 :group 'org-progress
2725 :type '(choice
2726 (const :tag "Not into a drawer" nil)
2727 (const :tag "LOGBOOK" t)
2728 (string :tag "Other")))
2730 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2732 (defun org-log-into-drawer ()
2733 "Return the value of `org-log-into-drawer', but let properties overrule.
2734 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2735 used instead of the default value."
2736 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2737 (cond
2738 ((not p) org-log-into-drawer)
2739 ((equal p "nil") nil)
2740 ((equal p "t") "LOGBOOK")
2741 (t p))))
2743 (defcustom org-log-state-notes-insert-after-drawers nil
2744 "Non-nil means insert state change notes after any drawers in entry.
2745 Only the drawers that *immediately* follow the headline and the
2746 deadline/scheduled line are skipped.
2747 When nil, insert notes right after the heading and perhaps the line
2748 with deadline/scheduling if present.
2750 This variable will have no effect if `org-log-into-drawer' is
2751 set."
2752 :group 'org-todo
2753 :group 'org-progress
2754 :type 'boolean)
2756 (defcustom org-log-states-order-reversed t
2757 "Non-nil means the latest state note will be directly after heading.
2758 When nil, the state change notes will be ordered according to time.
2760 This option can also be set with on a per-file-basis with
2762 #+STARTUP: logstatesreversed
2763 #+STARTUP: nologstatesreversed"
2764 :group 'org-todo
2765 :group 'org-progress
2766 :type 'boolean)
2768 (defcustom org-todo-repeat-to-state nil
2769 "The TODO state to which a repeater should return the repeating task.
2770 By default this is the first task in a TODO sequence, or the previous state
2771 in a TODO_TYP set. But you can specify another task here.
2772 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2773 :group 'org-todo
2774 :version "24.1"
2775 :type '(choice (const :tag "Head of sequence" nil)
2776 (string :tag "Specific state")))
2778 (defcustom org-log-repeat 'time
2779 "Non-nil means record moving through the DONE state when triggering repeat.
2780 An auto-repeating task is immediately switched back to TODO when
2781 marked DONE. If you are not logging state changes (by adding \"@\"
2782 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2783 record a closing note, there will be no record of the task moving
2784 through DONE. This variable forces taking a note anyway.
2786 nil Don't force a record
2787 time Record a time stamp
2788 note Prompt for a note and add it with template `org-log-note-headings'
2790 This option can also be set with on a per-file-basis with
2792 #+STARTUP: nologrepeat
2793 #+STARTUP: logrepeat
2794 #+STARTUP: lognoterepeat
2796 You can have local logging settings for a subtree by setting the LOGGING
2797 property to one or more of these keywords."
2798 :group 'org-todo
2799 :group 'org-progress
2800 :type '(choice
2801 (const :tag "Don't force a record" nil)
2802 (const :tag "Force recording the DONE state" time)
2803 (const :tag "Force recording a note with the DONE state" note)))
2806 (defgroup org-priorities nil
2807 "Priorities in Org-mode."
2808 :tag "Org Priorities"
2809 :group 'org-todo)
2811 (defcustom org-enable-priority-commands t
2812 "Non-nil means priority commands are active.
2813 When nil, these commands will be disabled, so that you never accidentally
2814 set a priority."
2815 :group 'org-priorities
2816 :type 'boolean)
2818 (defcustom org-highest-priority ?A
2819 "The highest priority of TODO items. A character like ?A, ?B etc.
2820 Must have a smaller ASCII number than `org-lowest-priority'."
2821 :group 'org-priorities
2822 :type 'character)
2824 (defcustom org-lowest-priority ?C
2825 "The lowest priority of TODO items. A character like ?A, ?B etc.
2826 Must have a larger ASCII number than `org-highest-priority'."
2827 :group 'org-priorities
2828 :type 'character)
2830 (defcustom org-default-priority ?B
2831 "The default priority of TODO items.
2832 This is the priority an item gets if no explicit priority is given.
2833 When starting to cycle on an empty priority the first step in the cycle
2834 depends on `org-priority-start-cycle-with-default'. The resulting first
2835 step priority must not exceed the range from `org-highest-priority' to
2836 `org-lowest-priority' which means that `org-default-priority' has to be
2837 in this range exclusive or inclusive the range boundaries. Else the
2838 first step refuses to set the default and the second will fall back
2839 to (depending on the command used) the highest or lowest priority."
2840 :group 'org-priorities
2841 :type 'character)
2843 (defcustom org-priority-start-cycle-with-default t
2844 "Non-nil means start with default priority when starting to cycle.
2845 When this is nil, the first step in the cycle will be (depending on the
2846 command used) one higher or lower than the default priority.
2847 See also `org-default-priority'."
2848 :group 'org-priorities
2849 :type 'boolean)
2851 (defcustom org-get-priority-function nil
2852 "Function to extract the priority from a string.
2853 The string is normally the headline. If this is nil Org computes the
2854 priority from the priority cookie like [#A] in the headline. It returns
2855 an integer, increasing by 1000 for each priority level.
2856 The user can set a different function here, which should take a string
2857 as an argument and return the numeric priority."
2858 :group 'org-priorities
2859 :version "24.1"
2860 :type '(choice
2861 (const nil)
2862 (function)))
2864 (defgroup org-time nil
2865 "Options concerning time stamps and deadlines in Org-mode."
2866 :tag "Org Time"
2867 :group 'org)
2869 (defcustom org-insert-labeled-timestamps-at-point nil
2870 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2871 When nil, these labeled time stamps are forces into the second line of an
2872 entry, just after the headline. When scheduling from the global TODO list,
2873 the time stamp will always be forced into the second line."
2874 :group 'org-time
2875 :type 'boolean)
2877 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2878 "Formats for `format-time-string' which are used for time stamps.
2879 It is not recommended to change this constant.")
2881 (defcustom org-time-stamp-rounding-minutes '(0 5)
2882 "Number of minutes to round time stamps to.
2883 These are two values, the first applies when first creating a time stamp.
2884 The second applies when changing it with the commands `S-up' and `S-down'.
2885 When changing the time stamp, this means that it will change in steps
2886 of N minutes, as given by the second value.
2888 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2889 numbers should be factors of 60, so for example 5, 10, 15.
2891 When this is larger than 1, you can still force an exact time stamp by using
2892 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2893 and by using a prefix arg to `S-up/down' to specify the exact number
2894 of minutes to shift."
2895 :group 'org-time
2896 :get #'(lambda (var) ; Make sure both elements are there
2897 (if (integerp (default-value var))
2898 (list (default-value var) 5)
2899 (default-value var)))
2900 :type '(list
2901 (integer :tag "when inserting times")
2902 (integer :tag "when modifying times")))
2904 ;; Normalize old customizations of this variable.
2905 (when (integerp org-time-stamp-rounding-minutes)
2906 (setq org-time-stamp-rounding-minutes
2907 (list org-time-stamp-rounding-minutes
2908 org-time-stamp-rounding-minutes)))
2910 (defcustom org-display-custom-times nil
2911 "Non-nil means overlay custom formats over all time stamps.
2912 The formats are defined through the variable `org-time-stamp-custom-formats'.
2913 To turn this on on a per-file basis, insert anywhere in the file:
2914 #+STARTUP: customtime"
2915 :group 'org-time
2916 :set 'set-default
2917 :type 'sexp)
2918 (make-variable-buffer-local 'org-display-custom-times)
2920 (defcustom org-time-stamp-custom-formats
2921 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2922 "Custom formats for time stamps. See `format-time-string' for the syntax.
2923 These are overlaid over the default ISO format if the variable
2924 `org-display-custom-times' is set. Time like %H:%M should be at the
2925 end of the second format. The custom formats are also honored by export
2926 commands, if custom time display is turned on at the time of export."
2927 :group 'org-time
2928 :type 'sexp)
2930 (defun org-time-stamp-format (&optional long inactive)
2931 "Get the right format for a time string."
2932 (let ((f (if long (cdr org-time-stamp-formats)
2933 (car org-time-stamp-formats))))
2934 (if inactive
2935 (concat "[" (substring f 1 -1) "]")
2936 f)))
2938 (defcustom org-time-clocksum-format
2939 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2940 "The format string used when creating CLOCKSUM lines.
2941 This is also used when Org mode generates a time duration.
2943 The value can be a single format string containing two
2944 %-sequences, which will be filled with the number of hours and
2945 minutes in that order.
2947 Alternatively, the value can be a plist associating any of the
2948 keys :years, :months, :weeks, :days, :hours or :minutes with
2949 format strings. The time duration is formatted using only the
2950 time components that are needed and concatenating the results.
2951 If a time unit in absent, it falls back to the next smallest
2952 unit.
2954 The keys :require-years, :require-months, :require-days,
2955 :require-weeks, :require-hours, :require-minutes are also
2956 meaningful. A non-nil value for these keys indicates that the
2957 corresponding time component should always be included, even if
2958 its value is 0.
2961 For example,
2963 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2964 :require-minutes t)
2966 means durations longer than a day will be expressed in days,
2967 hours and minutes, and durations less than a day will always be
2968 expressed in hours and minutes (even for durations less than an
2969 hour).
2971 The value
2973 (:days \"%dd\" :minutes \"%dm\")
2975 means durations longer than a day will be expressed in days and
2976 minutes, and durations less than a day will be expressed entirely
2977 in minutes (even for durations longer than an hour)."
2978 :group 'org-time
2979 :group 'org-clock
2980 :version "24.4"
2981 :package-version '(Org . "8.0")
2982 :type '(choice (string :tag "Format string")
2983 (set :tag "Plist"
2984 (group :inline t (const :tag "Years" :years)
2985 (string :tag "Format string"))
2986 (group :inline t
2987 (const :tag "Always show years" :require-years)
2988 (const t))
2989 (group :inline t (const :tag "Months" :months)
2990 (string :tag "Format string"))
2991 (group :inline t
2992 (const :tag "Always show months" :require-months)
2993 (const t))
2994 (group :inline t (const :tag "Weeks" :weeks)
2995 (string :tag "Format string"))
2996 (group :inline t
2997 (const :tag "Always show weeks" :require-weeks)
2998 (const t))
2999 (group :inline t (const :tag "Days" :days)
3000 (string :tag "Format string"))
3001 (group :inline t
3002 (const :tag "Always show days" :require-days)
3003 (const t))
3004 (group :inline t (const :tag "Hours" :hours)
3005 (string :tag "Format string"))
3006 (group :inline t
3007 (const :tag "Always show hours" :require-hours)
3008 (const t))
3009 (group :inline t (const :tag "Minutes" :minutes)
3010 (string :tag "Format string"))
3011 (group :inline t
3012 (const :tag "Always show minutes" :require-minutes)
3013 (const t)))))
3015 (defcustom org-time-clocksum-use-fractional nil
3016 "When non-nil, \\[org-clock-display] uses fractional times.
3017 See `org-time-clocksum-format' for more on time clock formats."
3018 :group 'org-time
3019 :group 'org-clock
3020 :version "24.3"
3021 :type 'boolean)
3023 (defcustom org-time-clocksum-use-effort-durations nil
3024 "When non-nil, \\[org-clock-display] uses effort durations.
3025 E.g. by default, one day is considered to be a 8 hours effort,
3026 so a task that has been clocked for 16 hours will be displayed
3027 as during 2 days in the clock display or in the clocktable.
3029 See `org-effort-durations' on how to set effort durations
3030 and `org-time-clocksum-format' for more on time clock formats."
3031 :group 'org-time
3032 :group 'org-clock
3033 :version "24.4"
3034 :package-version '(Org . "8.0")
3035 :type 'boolean)
3037 (defcustom org-time-clocksum-fractional-format "%.2f"
3038 "The format string used when creating CLOCKSUM lines,
3039 or when Org mode generates a time duration, if
3040 `org-time-clocksum-use-fractional' is enabled.
3042 The value can be a single format string containing one
3043 %-sequence, which will be filled with the number of hours as
3044 a float.
3046 Alternatively, the value can be a plist associating any of the
3047 keys :years, :months, :weeks, :days, :hours or :minutes with
3048 a format string. The time duration is formatted using the
3049 largest time unit which gives a non-zero integer part. If all
3050 specified formats have zero integer part, the smallest time unit
3051 is used."
3052 :group 'org-time
3053 :type '(choice (string :tag "Format string")
3054 (set (group :inline t (const :tag "Years" :years)
3055 (string :tag "Format string"))
3056 (group :inline t (const :tag "Months" :months)
3057 (string :tag "Format string"))
3058 (group :inline t (const :tag "Weeks" :weeks)
3059 (string :tag "Format string"))
3060 (group :inline t (const :tag "Days" :days)
3061 (string :tag "Format string"))
3062 (group :inline t (const :tag "Hours" :hours)
3063 (string :tag "Format string"))
3064 (group :inline t (const :tag "Minutes" :minutes)
3065 (string :tag "Format string")))))
3067 (defcustom org-deadline-warning-days 14
3068 "Number of days before expiration during which a deadline becomes active.
3069 This variable governs the display in sparse trees and in the agenda.
3070 When 0 or negative, it means use this number (the absolute value of it)
3071 even if a deadline has a different individual lead time specified.
3073 Custom commands can set this variable in the options section."
3074 :group 'org-time
3075 :group 'org-agenda-daily/weekly
3076 :type 'integer)
3078 (defcustom org-scheduled-delay-days 0
3079 "Number of days before a scheduled item becomes active.
3080 This variable governs the display in sparse trees and in the agenda.
3081 The default value (i.e. 0) means: don't delay scheduled item.
3082 When negative, it means use this number (the absolute value of it)
3083 even if a scheduled item has a different individual delay time
3084 specified.
3086 Custom commands can set this variable in the options section."
3087 :group 'org-time
3088 :group 'org-agenda-daily/weekly
3089 :version "24.4"
3090 :package-version '(Org . "8.0")
3091 :type 'integer)
3093 (defcustom org-read-date-prefer-future t
3094 "Non-nil means assume future for incomplete date input from user.
3095 This affects the following situations:
3096 1. The user gives a month but not a year.
3097 For example, if it is April and you enter \"feb 2\", this will be read
3098 as Feb 2, *next* year. \"May 5\", however, will be this year.
3099 2. The user gives a day, but no month.
3100 For example, if today is the 15th, and you enter \"3\", Org-mode will
3101 read this as the third of *next* month. However, if you enter \"17\",
3102 it will be considered as *this* month.
3104 If you set this variable to the symbol `time', then also the following
3105 will work:
3107 3. If the user gives a time.
3108 If the time is before now, it will be interpreted as tomorrow.
3110 Currently none of this works for ISO week specifications.
3112 When this option is nil, the current day, month and year will always be
3113 used as defaults.
3115 See also `org-agenda-jump-prefer-future'."
3116 :group 'org-time
3117 :type '(choice
3118 (const :tag "Never" nil)
3119 (const :tag "Check month and day" t)
3120 (const :tag "Check month, day, and time" time)))
3122 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3123 "Should the agenda jump command prefer the future for incomplete dates?
3124 The default is to do the same as configured in `org-read-date-prefer-future'.
3125 But you can also set a deviating value here.
3126 This may t or nil, or the symbol `org-read-date-prefer-future'."
3127 :group 'org-agenda
3128 :group 'org-time
3129 :version "24.1"
3130 :type '(choice
3131 (const :tag "Use org-read-date-prefer-future"
3132 org-read-date-prefer-future)
3133 (const :tag "Never" nil)
3134 (const :tag "Always" t)))
3136 (defcustom org-read-date-force-compatible-dates t
3137 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3139 Depending on the system Emacs is running on, certain dates cannot
3140 be represented with the type used internally to represent time.
3141 Dates between 1970-1-1 and 2038-1-1 can always be represented
3142 correctly. Some systems allow for earlier dates, some for later,
3143 some for both. One way to find out it to insert any date into an
3144 Org buffer, putting the cursor on the year and hitting S-up and
3145 S-down to test the range.
3147 When this variable is set to t, the date/time prompt will not let
3148 you specify dates outside the 1970-2037 range, so it is certain that
3149 these dates will work in whatever version of Emacs you are
3150 running, and also that you can move a file from one Emacs implementation
3151 to another. WHenever Org is forcing the year for you, it will display
3152 a message and beep.
3154 When this variable is nil, Org will check if the date is
3155 representable in the specific Emacs implementation you are using.
3156 If not, it will force a year, usually the current year, and beep
3157 to remind you. Currently this setting is not recommended because
3158 the likelihood that you will open your Org files in an Emacs that
3159 has limited date range is not negligible.
3161 A workaround for this problem is to use diary sexp dates for time
3162 stamps outside of this range."
3163 :group 'org-time
3164 :version "24.1"
3165 :type 'boolean)
3167 (defcustom org-read-date-display-live t
3168 "Non-nil means display current interpretation of date prompt live.
3169 This display will be in an overlay, in the minibuffer."
3170 :group 'org-time
3171 :type 'boolean)
3173 (defcustom org-read-date-popup-calendar t
3174 "Non-nil means pop up a calendar when prompting for a date.
3175 In the calendar, the date can be selected with mouse-1. However, the
3176 minibuffer will also be active, and you can simply enter the date as well.
3177 When nil, only the minibuffer will be available."
3178 :group 'org-time
3179 :type 'boolean)
3180 (org-defvaralias 'org-popup-calendar-for-date-prompt
3181 'org-read-date-popup-calendar)
3183 (make-obsolete-variable
3184 'org-read-date-minibuffer-setup-hook
3185 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3186 (defcustom org-read-date-minibuffer-setup-hook nil
3187 "Hook to be used to set up keys for the date/time interface.
3188 Add key definitions to `minibuffer-local-map', which will be a
3189 temporary copy.
3191 WARNING: This option is obsolete, you should use
3192 `org-read-date-minibuffer-local-map' to set up keys."
3193 :group 'org-time
3194 :type 'hook)
3196 (defcustom org-extend-today-until 0
3197 "The hour when your day really ends. Must be an integer.
3198 This has influence for the following applications:
3199 - When switching the agenda to \"today\". It it is still earlier than
3200 the time given here, the day recognized as TODAY is actually yesterday.
3201 - When a date is read from the user and it is still before the time given
3202 here, the current date and time will be assumed to be yesterday, 23:59.
3203 Also, timestamps inserted in capture templates follow this rule.
3205 IMPORTANT: This is a feature whose implementation is and likely will
3206 remain incomplete. Really, it is only here because past midnight seems to
3207 be the favorite working time of John Wiegley :-)"
3208 :group 'org-time
3209 :type 'integer)
3211 (defcustom org-use-effective-time nil
3212 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3213 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3214 \"effective time\" of any timestamps between midnight and 8am will be
3215 23:59 of the previous day."
3216 :group 'org-time
3217 :version "24.1"
3218 :type 'boolean)
3220 (defcustom org-use-last-clock-out-time-as-effective-time nil
3221 "When non-nil, use the last clock out time for `org-todo'.
3222 Note that this option has precedence over the combined use of
3223 `org-use-effective-time' and `org-extend-today-until'."
3224 :group 'org-time
3225 :version "24.4"
3226 :package-version '(Org . "8.0")
3227 :type 'boolean)
3229 (defcustom org-edit-timestamp-down-means-later nil
3230 "Non-nil means S-down will increase the time in a time stamp.
3231 When nil, S-up will increase."
3232 :group 'org-time
3233 :type 'boolean)
3235 (defcustom org-calendar-follow-timestamp-change t
3236 "Non-nil means make the calendar window follow timestamp changes.
3237 When a timestamp is modified and the calendar window is visible, it will be
3238 moved to the new date."
3239 :group 'org-time
3240 :type 'boolean)
3242 (defgroup org-tags nil
3243 "Options concerning tags in Org-mode."
3244 :tag "Org Tags"
3245 :group 'org)
3247 (defcustom org-tag-alist nil
3248 "List of tags allowed in Org-mode files.
3249 When this list is nil, Org-mode will base TAG input on what is already in the
3250 buffer.
3251 The value of this variable is an alist, the car of each entry must be a
3252 keyword as a string, the cdr may be a character that is used to select
3253 that tag through the fast-tag-selection interface.
3254 See the manual for details."
3255 :group 'org-tags
3256 :type '(repeat
3257 (choice
3258 (cons (string :tag "Tag name")
3259 (character :tag "Access char"))
3260 (list :tag "Start radio group"
3261 (const :startgroup)
3262 (option (string :tag "Group description")))
3263 (list :tag "Group tags delimiter"
3264 (const :grouptags))
3265 (list :tag "End radio group"
3266 (const :endgroup)
3267 (option (string :tag "Group description")))
3268 (const :tag "New line" (:newline)))))
3270 (defcustom org-tag-persistent-alist nil
3271 "List of tags that will always appear in all Org-mode files.
3272 This is in addition to any in buffer settings or customizations
3273 of `org-tag-alist'.
3274 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3275 The value of this variable is an alist, the car of each entry must be a
3276 keyword as a string, the cdr may be a character that is used to select
3277 that tag through the fast-tag-selection interface.
3278 See the manual for details.
3279 To disable these tags on a per-file basis, insert anywhere in the file:
3280 #+STARTUP: noptag"
3281 :group 'org-tags
3282 :type '(repeat
3283 (choice
3284 (cons (string :tag "Tag name")
3285 (character :tag "Access char"))
3286 (const :tag "Start radio group" (:startgroup))
3287 (const :tag "Group tags delimiter" (:grouptags))
3288 (const :tag "End radio group" (:endgroup))
3289 (const :tag "New line" (:newline)))))
3291 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3292 "If non-nil, always offer completion for all tags of all agenda files.
3293 Instead of customizing this variable directly, you might want to
3294 set it locally for capture buffers, because there no list of
3295 tags in that file can be created dynamically (there are none).
3297 (add-hook \\='org-capture-mode-hook
3298 (lambda ()
3299 (set (make-local-variable
3300 \\='org-complete-tags-always-offer-all-agenda-tags)
3301 t)))"
3302 :group 'org-tags
3303 :version "24.1"
3304 :type 'boolean)
3306 (defvar org-file-tags nil
3307 "List of tags that can be inherited by all entries in the file.
3308 The tags will be inherited if the variable `org-use-tag-inheritance'
3309 says they should be.
3310 This variable is populated from #+FILETAGS lines.")
3312 (defcustom org-use-fast-tag-selection 'auto
3313 "Non-nil means use fast tag selection scheme.
3314 This is a special interface to select and deselect tags with single keys.
3315 When nil, fast selection is never used.
3316 When the symbol `auto', fast selection is used if and only if selection
3317 characters for tags have been configured, either through the variable
3318 `org-tag-alist' or through a #+TAGS line in the buffer.
3319 When t, fast selection is always used and selection keys are assigned
3320 automatically if necessary."
3321 :group 'org-tags
3322 :type '(choice
3323 (const :tag "Always" t)
3324 (const :tag "Never" nil)
3325 (const :tag "When selection characters are configured" auto)))
3327 (defcustom org-fast-tag-selection-single-key nil
3328 "Non-nil means fast tag selection exits after first change.
3329 When nil, you have to press RET to exit it.
3330 During fast tag selection, you can toggle this flag with `C-c'.
3331 This variable can also have the value `expert'. In this case, the window
3332 displaying the tags menu is not even shown, until you press C-c again."
3333 :group 'org-tags
3334 :type '(choice
3335 (const :tag "No" nil)
3336 (const :tag "Yes" t)
3337 (const :tag "Expert" expert)))
3339 (defvar org-fast-tag-selection-include-todo nil
3340 "Non-nil means fast tags selection interface will also offer TODO states.
3341 This is an undocumented feature, you should not rely on it.")
3343 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3344 "The column to which tags should be indented in a headline.
3345 If this number is positive, it specifies the column. If it is negative,
3346 it means that the tags should be flushright to that column. For example,
3347 -80 works well for a normal 80 character screen.
3348 When 0, place tags directly after headline text, with only one space in
3349 between."
3350 :group 'org-tags
3351 :type 'integer)
3353 (defcustom org-auto-align-tags t
3354 "Non-nil keeps tags aligned when modifying headlines.
3355 Some operations (i.e. demoting) change the length of a headline and
3356 therefore shift the tags around. With this option turned on, after
3357 each such operation the tags are again aligned to `org-tags-column'."
3358 :group 'org-tags
3359 :type 'boolean)
3361 (defcustom org-use-tag-inheritance t
3362 "Non-nil means tags in levels apply also for sublevels.
3363 When nil, only the tags directly given in a specific line apply there.
3364 This may also be a list of tags that should be inherited, or a regexp that
3365 matches tags that should be inherited. Additional control is possible
3366 with the variable `org-tags-exclude-from-inheritance' which gives an
3367 explicit list of tags to be excluded from inheritance, even if the value of
3368 `org-use-tag-inheritance' would select it for inheritance.
3370 If this option is t, a match early-on in a tree can lead to a large
3371 number of matches in the subtree when constructing the agenda or creating
3372 a sparse tree. If you only want to see the first match in a tree during
3373 a search, check out the variable `org-tags-match-list-sublevels'."
3374 :group 'org-tags
3375 :type '(choice
3376 (const :tag "Not" nil)
3377 (const :tag "Always" t)
3378 (repeat :tag "Specific tags" (string :tag "Tag"))
3379 (regexp :tag "Tags matched by regexp")))
3381 (defcustom org-tags-exclude-from-inheritance nil
3382 "List of tags that should never be inherited.
3383 This is a way to exclude a few tags from inheritance. For way to do
3384 the opposite, to actively allow inheritance for selected tags,
3385 see the variable `org-use-tag-inheritance'."
3386 :group 'org-tags
3387 :type '(repeat (string :tag "Tag")))
3389 (defun org-tag-inherit-p (tag)
3390 "Check if TAG is one that should be inherited."
3391 (cond
3392 ((member tag org-tags-exclude-from-inheritance) nil)
3393 ((eq org-use-tag-inheritance t) t)
3394 ((not org-use-tag-inheritance) nil)
3395 ((stringp org-use-tag-inheritance)
3396 (string-match org-use-tag-inheritance tag))
3397 ((listp org-use-tag-inheritance)
3398 (member tag org-use-tag-inheritance))
3399 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3401 (defcustom org-tags-match-list-sublevels t
3402 "Non-nil means list also sublevels of headlines matching a search.
3403 This variable applies to tags/property searches, and also to stuck
3404 projects because this search is based on a tags match as well.
3406 When set to the symbol `indented', sublevels are indented with
3407 leading dots.
3409 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3410 the sublevels of a headline matching a tag search often also match
3411 the same search. Listing all of them can create very long lists.
3412 Setting this variable to nil causes subtrees of a match to be skipped.
3414 This variable is semi-obsolete and probably should always be true. It
3415 is better to limit inheritance to certain tags using the variables
3416 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3417 :group 'org-tags
3418 :type '(choice
3419 (const :tag "No, don't list them" nil)
3420 (const :tag "Yes, do list them" t)
3421 (const :tag "List them, indented with leading dots" indented)))
3423 (defcustom org-tags-sort-function nil
3424 "When set, tags are sorted using this function as a comparator."
3425 :group 'org-tags
3426 :type '(choice
3427 (const :tag "No sorting" nil)
3428 (const :tag "Alphabetical" string<)
3429 (const :tag "Reverse alphabetical" string>)
3430 (function :tag "Custom function" nil)))
3432 (defvar org-tags-history nil
3433 "History of minibuffer reads for tags.")
3434 (defvar org-last-tags-completion-table nil
3435 "The last used completion table for tags.")
3436 (defvar org-after-tags-change-hook nil
3437 "Hook that is run after the tags in a line have changed.")
3439 (defgroup org-properties nil
3440 "Options concerning properties in Org-mode."
3441 :tag "Org Properties"
3442 :group 'org)
3444 (defcustom org-property-format "%-10s %s"
3445 "How property key/value pairs should be formatted by `indent-line'.
3446 When `indent-line' hits a property definition, it will format the line
3447 according to this format, mainly to make sure that the values are
3448 lined-up with respect to each other."
3449 :group 'org-properties
3450 :type 'string)
3452 (defcustom org-properties-postprocess-alist nil
3453 "Alist of properties and functions to adjust inserted values.
3454 Elements of this alist must be of the form
3456 ([string] [function])
3458 where [string] must be a property name and [function] must be a
3459 lambda expression: this lambda expression must take one argument,
3460 the value to adjust, and return the new value as a string.
3462 For example, this element will allow the property \"Remaining\"
3463 to be updated wrt the relation between the \"Effort\" property
3464 and the clock summary:
3466 ((\"Remaining\" (lambda(value)
3467 (let ((clocksum (org-clock-sum-current-item))
3468 (effort (org-duration-string-to-minutes
3469 (org-entry-get (point) \"Effort\"))))
3470 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3471 :group 'org-properties
3472 :version "24.1"
3473 :type '(alist :key-type (string :tag "Property")
3474 :value-type (function :tag "Function")))
3476 (defcustom org-use-property-inheritance nil
3477 "Non-nil means properties apply also for sublevels.
3479 This setting is chiefly used during property searches. Turning it on can
3480 cause significant overhead when doing a search, which is why it is not
3481 on by default.
3483 When nil, only the properties directly given in the current entry count.
3484 When t, every property is inherited. The value may also be a list of
3485 properties that should have inheritance, or a regular expression matching
3486 properties that should be inherited.
3488 However, note that some special properties use inheritance under special
3489 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3490 and the properties ending in \"_ALL\" when they are used as descriptor
3491 for valid values of a property.
3493 Note for programmers:
3494 When querying an entry with `org-entry-get', you can control if inheritance
3495 should be used. By default, `org-entry-get' looks only at the local
3496 properties. You can request inheritance by setting the inherit argument
3497 to t (to force inheritance) or to `selective' (to respect the setting
3498 in this variable)."
3499 :group 'org-properties
3500 :type '(choice
3501 (const :tag "Not" nil)
3502 (const :tag "Always" t)
3503 (repeat :tag "Specific properties" (string :tag "Property"))
3504 (regexp :tag "Properties matched by regexp")))
3506 (defun org-property-inherit-p (property)
3507 "Check if PROPERTY is one that should be inherited."
3508 (cond
3509 ((eq org-use-property-inheritance t) t)
3510 ((not org-use-property-inheritance) nil)
3511 ((stringp org-use-property-inheritance)
3512 (string-match org-use-property-inheritance property))
3513 ((listp org-use-property-inheritance)
3514 (member property org-use-property-inheritance))
3515 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3517 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3518 "The default column format, if no other format has been defined.
3519 This variable can be set on the per-file basis by inserting a line
3521 #+COLUMNS: %25ITEM ....."
3522 :group 'org-properties
3523 :type 'string)
3525 (defcustom org-columns-ellipses ".."
3526 "The ellipses to be used when a field in column view is truncated.
3527 When this is the empty string, as many characters as possible are shown,
3528 but then there will be no visual indication that the field has been truncated.
3529 When this is a string of length N, the last N characters of a truncated
3530 field are replaced by this string. If the column is narrower than the
3531 ellipses string, only part of the ellipses string will be shown."
3532 :group 'org-properties
3533 :type 'string)
3535 (defcustom org-columns-modify-value-for-display-function nil
3536 "Function that modifies values for display in column view.
3537 For example, it can be used to cut out a certain part from a time stamp.
3538 The function must take 2 arguments:
3540 column-title The title of the column (*not* the property name)
3541 value The value that should be modified.
3543 The function should return the value that should be displayed,
3544 or nil if the normal value should be used."
3545 :group 'org-properties
3546 :type '(choice (const nil) (function)))
3548 (defcustom org-effort-property "Effort"
3549 "The property that is being used to keep track of effort estimates.
3550 Effort estimates given in this property need to have the format H:MM."
3551 :group 'org-properties
3552 :group 'org-progress
3553 :type '(string :tag "Property"))
3555 (defconst org-global-properties-fixed
3556 '(("VISIBILITY_ALL" . "folded children content all")
3557 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3558 "List of property/value pairs that can be inherited by any entry.
3560 These are fixed values, for the preset properties. The user variable
3561 that can be used to add to this list is `org-global-properties'.
3563 The entries in this list are cons cells where the car is a property
3564 name and cdr is a string with the value. If the value represents
3565 multiple items like an \"_ALL\" property, separate the items by
3566 spaces.")
3568 (defcustom org-global-properties nil
3569 "List of property/value pairs that can be inherited by any entry.
3571 This list will be combined with the constant `org-global-properties-fixed'.
3573 The entries in this list are cons cells where the car is a property
3574 name and cdr is a string with the value.
3576 You can set buffer-local values for the same purpose in the variable
3577 `org-file-properties' this by adding lines like
3579 #+PROPERTY: NAME VALUE"
3580 :group 'org-properties
3581 :type '(repeat
3582 (cons (string :tag "Property")
3583 (string :tag "Value"))))
3585 (defvar org-file-properties nil
3586 "List of property/value pairs that can be inherited by any entry.
3587 Valid for the current buffer.
3588 This variable is populated from #+PROPERTY lines.")
3589 (make-variable-buffer-local 'org-file-properties)
3591 (defgroup org-agenda nil
3592 "Options concerning agenda views in Org-mode."
3593 :tag "Org Agenda"
3594 :group 'org)
3596 (defvar org-category nil
3597 "Variable used by org files to set a category for agenda display.
3598 Such files should use a file variable to set it, for example
3600 # -*- mode: org; org-category: \"ELisp\"
3602 or contain a special line
3604 #+CATEGORY: ELisp
3606 If the file does not specify a category, then file's base name
3607 is used instead.")
3608 (make-variable-buffer-local 'org-category)
3609 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3611 (defcustom org-agenda-files nil
3612 "The files to be used for agenda display.
3613 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3614 \\[org-remove-file]. You can also use customize to edit the list.
3616 If an entry is a directory, all files in that directory that are matched by
3617 `org-agenda-file-regexp' will be part of the file list.
3619 If the value of the variable is not a list but a single file name, then
3620 the list of agenda files is actually stored and maintained in that file, one
3621 agenda file per line. In this file paths can be given relative to
3622 `org-directory'. Tilde expansion and environment variable substitution
3623 are also made."
3624 :group 'org-agenda
3625 :type '(choice
3626 (repeat :tag "List of files and directories" file)
3627 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3629 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3630 "Regular expression to match files for `org-agenda-files'.
3631 If any element in the list in that variable contains a directory instead
3632 of a normal file, all files in that directory that are matched by this
3633 regular expression will be included."
3634 :group 'org-agenda
3635 :type 'regexp)
3637 (defcustom org-agenda-text-search-extra-files nil
3638 "List of extra files to be searched by text search commands.
3639 These files will be searched in addition to the agenda files by the
3640 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3641 Note that these files will only be searched for text search commands,
3642 not for the other agenda views like todo lists, tag searches or the weekly
3643 agenda. This variable is intended to list notes and possibly archive files
3644 that should also be searched by these two commands.
3645 In fact, if the first element in the list is the symbol `agenda-archives',
3646 then all archive files of all agenda files will be added to the search
3647 scope."
3648 :group 'org-agenda
3649 :type '(set :greedy t
3650 (const :tag "Agenda Archives" agenda-archives)
3651 (repeat :inline t (file))))
3653 (org-defvaralias 'org-agenda-multi-occur-extra-files
3654 'org-agenda-text-search-extra-files)
3656 (defcustom org-agenda-skip-unavailable-files nil
3657 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3658 A nil value means to remove them, after a query, from the list."
3659 :group 'org-agenda
3660 :type 'boolean)
3662 (defcustom org-calendar-to-agenda-key [?c]
3663 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3664 The command `org-calendar-goto-agenda' will be bound to this key. The
3665 default is the character `c' because then `c' can be used to switch back and
3666 forth between agenda and calendar."
3667 :group 'org-agenda
3668 :type 'sexp)
3670 (defcustom org-calendar-insert-diary-entry-key [?i]
3671 "The key to be installed in `calendar-mode-map' for adding diary entries.
3672 This option is irrelevant until `org-agenda-diary-file' has been configured
3673 to point to an Org-mode file. When that is the case, the command
3674 `org-agenda-diary-entry' will be bound to the key given here, by default
3675 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3676 if you want to continue doing this, you need to change this to a different
3677 key."
3678 :group 'org-agenda
3679 :type 'sexp)
3681 (defcustom org-agenda-diary-file 'diary-file
3682 "File to which to add new entries with the `i' key in agenda and calendar.
3683 When this is the symbol `diary-file', the functionality in the Emacs
3684 calendar will be used to add entries to the `diary-file'. But when this
3685 points to a file, `org-agenda-diary-entry' will be used instead."
3686 :group 'org-agenda
3687 :type '(choice
3688 (const :tag "The standard Emacs diary file" diary-file)
3689 (file :tag "Special Org file diary entries")))
3691 (eval-after-load "calendar"
3692 '(progn
3693 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3694 'org-calendar-goto-agenda)
3695 (add-hook 'calendar-mode-hook
3696 (lambda ()
3697 (unless (eq org-agenda-diary-file 'diary-file)
3698 (define-key calendar-mode-map
3699 org-calendar-insert-diary-entry-key
3700 'org-agenda-diary-entry))))))
3702 (defgroup org-latex nil
3703 "Options for embedding LaTeX code into Org-mode."
3704 :tag "Org LaTeX"
3705 :group 'org)
3707 (defcustom org-format-latex-options
3708 '(:foreground default :background default :scale 1.0
3709 :html-foreground "Black" :html-background "Transparent"
3710 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3711 "Options for creating images from LaTeX fragments.
3712 This is a property list with the following properties:
3713 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3714 `default' means use the foreground of the default face.
3715 `auto' means use the foreground from the text face.
3716 :background the background color, or \"Transparent\".
3717 `default' means use the background of the default face.
3718 `auto' means use the background from the text face.
3719 :scale a scaling factor for the size of the images, to get more pixels
3720 :html-foreground, :html-background, :html-scale
3721 the same numbers for HTML export.
3722 :matchers a list indicating which matchers should be used to
3723 find LaTeX fragments. Valid members of this list are:
3724 \"begin\" find environments
3725 \"$1\" find single characters surrounded by $.$
3726 \"$\" find math expressions surrounded by $...$
3727 \"$$\" find math expressions surrounded by $$....$$
3728 \"\\(\" find math expressions surrounded by \\(...\\)
3729 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3730 :group 'org-latex
3731 :type 'plist)
3733 (defcustom org-format-latex-signal-error t
3734 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3735 When nil, just push out a message."
3736 :group 'org-latex
3737 :version "24.1"
3738 :type 'boolean)
3740 (defcustom org-latex-to-mathml-jar-file nil
3741 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3742 Use this to specify additional executable file say a jar file.
3744 When using MathToWeb as the converter, specify the full-path to
3745 your mathtoweb.jar file."
3746 :group 'org-latex
3747 :version "24.1"
3748 :type '(choice
3749 (const :tag "None" nil)
3750 (file :tag "JAR file" :must-match t)))
3752 (defcustom org-latex-to-mathml-convert-command nil
3753 "Command to convert LaTeX fragments to MathML.
3754 Replace format-specifiers in the command as noted below and use
3755 `shell-command' to convert LaTeX to MathML.
3756 %j: Executable file in fully expanded form as specified by
3757 `org-latex-to-mathml-jar-file'.
3758 %I: Input LaTeX file in fully expanded form
3759 %o: Output MathML file
3760 This command is used by `org-create-math-formula'.
3762 When using MathToWeb as the converter, set this to
3763 \"java -jar %j -unicode -force -df %o %I\"."
3764 :group 'org-latex
3765 :version "24.1"
3766 :type '(choice
3767 (const :tag "None" nil)
3768 (string :tag "\nShell command")))
3770 (defcustom org-latex-create-formula-image-program 'dvipng
3771 "Program to convert LaTeX fragments with.
3773 dvipng Process the LaTeX fragments to dvi file, then convert
3774 dvi files to png files using dvipng.
3775 This will also include processing of non-math environments.
3776 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3777 to convert pdf files to png files"
3778 :group 'org-latex
3779 :version "24.1"
3780 :type '(choice
3781 (const :tag "dvipng" dvipng)
3782 (const :tag "imagemagick" imagemagick)))
3784 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3785 "Path to store latex preview images.
3786 A relative path here creates many directories relative to the
3787 processed org files paths. An absolute path puts all preview
3788 images at the same place."
3789 :group 'org-latex
3790 :version "24.3"
3791 :type 'string)
3793 (defun org-format-latex-mathml-available-p ()
3794 "Return t if `org-latex-to-mathml-convert-command' is usable."
3795 (save-match-data
3796 (when (and (boundp 'org-latex-to-mathml-convert-command)
3797 org-latex-to-mathml-convert-command)
3798 (let ((executable (car (split-string
3799 org-latex-to-mathml-convert-command))))
3800 (when (executable-find executable)
3801 (if (string-match
3802 "%j" org-latex-to-mathml-convert-command)
3803 (file-readable-p org-latex-to-mathml-jar-file)
3804 t))))))
3806 (defcustom org-format-latex-header "\\documentclass{article}
3807 \\usepackage[usenames]{color}
3808 [PACKAGES]
3809 [DEFAULT-PACKAGES]
3810 \\pagestyle{empty} % do not remove
3811 % The settings below are copied from fullpage.sty
3812 \\setlength{\\textwidth}{\\paperwidth}
3813 \\addtolength{\\textwidth}{-3cm}
3814 \\setlength{\\oddsidemargin}{1.5cm}
3815 \\addtolength{\\oddsidemargin}{-2.54cm}
3816 \\setlength{\\evensidemargin}{\\oddsidemargin}
3817 \\setlength{\\textheight}{\\paperheight}
3818 \\addtolength{\\textheight}{-\\headheight}
3819 \\addtolength{\\textheight}{-\\headsep}
3820 \\addtolength{\\textheight}{-\\footskip}
3821 \\addtolength{\\textheight}{-3cm}
3822 \\setlength{\\topmargin}{1.5cm}
3823 \\addtolength{\\topmargin}{-2.54cm}"
3824 "The document header used for processing LaTeX fragments.
3825 It is imperative that this header make sure that no page number
3826 appears on the page. The package defined in the variables
3827 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3828 will either replace the placeholder \"[PACKAGES]\" in this
3829 header, or they will be appended."
3830 :group 'org-latex
3831 :type 'string)
3833 (defun org-set-packages-alist (var val)
3834 "Set the packages alist and make sure it has 3 elements per entry."
3835 (set var (mapcar (lambda (x)
3836 (if (and (consp x) (= (length x) 2))
3837 (list (car x) (nth 1 x) t)
3839 val)))
3841 (defun org-get-packages-alist (var)
3842 "Get the packages alist and make sure it has 3 elements per entry."
3843 (mapcar (lambda (x)
3844 (if (and (consp x) (= (length x) 2))
3845 (list (car x) (nth 1 x) t)
3847 (default-value var)))
3849 (defcustom org-latex-default-packages-alist
3850 '(("AUTO" "inputenc" t)
3851 ("T1" "fontenc" t)
3852 ("" "fixltx2e" nil)
3853 ("" "graphicx" t)
3854 ("" "longtable" nil)
3855 ("" "float" nil)
3856 ("" "wrapfig" nil)
3857 ("" "rotating" nil)
3858 ("normalem" "ulem" t)
3859 ("" "amsmath" t)
3860 ("" "textcomp" t)
3861 ("" "marvosym" t)
3862 ("" "wasysym" t)
3863 ("" "amssymb" t)
3864 ("" "hyperref" nil)
3865 "\\tolerance=1000")
3866 "Alist of default packages to be inserted in the header.
3868 Change this only if one of the packages here causes an
3869 incompatibility with another package you are using.
3871 The packages in this list are needed by one part or another of
3872 Org mode to function properly:
3874 - inputenc, fontenc: for basic font and character selection
3875 - fixltx2e: Important patches of LaTeX itself
3876 - graphicx: for including images
3877 - longtable: For multipage tables
3878 - float, wrapfig: for figure placement
3879 - rotating: for sideways figures and tables
3880 - ulem: for underline and strike-through
3881 - amsmath: for subscript and superscript and math environments
3882 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3883 for interpreting the entities in `org-entities'. You can skip
3884 some of these packages if you don't use any of their symbols.
3885 - hyperref: for cross references
3887 Therefore you should not modify this variable unless you know
3888 what you are doing. The one reason to change it anyway is that
3889 you might be loading some other package that conflicts with one
3890 of the default packages. Each element is either a cell or
3891 a string.
3893 A cell is of the format:
3895 ( \"options\" \"package\" SNIPPET-FLAG).
3897 If SNIPPET-FLAG is non-nil, the package also needs to be included
3898 when compiling LaTeX snippets into images for inclusion into
3899 non-LaTeX output.
3901 A string will be inserted as-is in the header of the document."
3902 :group 'org-latex
3903 :group 'org-export-latex
3904 :set 'org-set-packages-alist
3905 :get 'org-get-packages-alist
3906 :version "24.1"
3907 :type '(repeat
3908 (choice
3909 (list :tag "options/package pair"
3910 (string :tag "options")
3911 (string :tag "package")
3912 (boolean :tag "Snippet"))
3913 (string :tag "A line of LaTeX"))))
3915 (defcustom org-latex-packages-alist nil
3916 "Alist of packages to be inserted in every LaTeX header.
3918 These will be inserted after `org-latex-default-packages-alist'.
3919 Each element is either a cell or a string.
3921 A cell is of the format:
3923 (\"options\" \"package\" SNIPPET-FLAG)
3925 SNIPPET-FLAG, when non-nil, indicates that this package is also
3926 needed when turning LaTeX snippets into images for inclusion into
3927 non-LaTeX output.
3929 A string will be inserted as-is in the header of the document.
3931 Make sure that you only list packages here which:
3933 - you want in every file;
3934 - do not conflict with the setup in `org-format-latex-header';
3935 - do not conflict with the default packages in
3936 `org-latex-default-packages-alist'."
3937 :group 'org-latex
3938 :group 'org-export-latex
3939 :set 'org-set-packages-alist
3940 :get 'org-get-packages-alist
3941 :type '(repeat
3942 (choice
3943 (list :tag "options/package pair"
3944 (string :tag "options")
3945 (string :tag "package")
3946 (boolean :tag "Snippet"))
3947 (string :tag "A line of LaTeX"))))
3949 (defgroup org-appearance nil
3950 "Settings for Org-mode appearance."
3951 :tag "Org Appearance"
3952 :group 'org)
3954 (defcustom org-level-color-stars-only nil
3955 "Non-nil means fontify only the stars in each headline.
3956 When nil, the entire headline is fontified.
3957 Changing it requires restart of `font-lock-mode' to become effective
3958 also in regions already fontified."
3959 :group 'org-appearance
3960 :type 'boolean)
3962 (defcustom org-hide-leading-stars nil
3963 "Non-nil means hide the first N-1 stars in a headline.
3964 This works by using the face `org-hide' for these stars. This
3965 face is white for a light background, and black for a dark
3966 background. You may have to customize the face `org-hide' to
3967 make this work.
3968 Changing it requires restart of `font-lock-mode' to become effective
3969 also in regions already fontified.
3970 You may also set this on a per-file basis by adding one of the following
3971 lines to the buffer:
3973 #+STARTUP: hidestars
3974 #+STARTUP: showstars"
3975 :group 'org-appearance
3976 :type 'boolean)
3978 (defcustom org-hidden-keywords nil
3979 "List of symbols corresponding to keywords to be hidden the org buffer.
3980 For example, a value \\='(title) for this list will make the document's title
3981 appear in the buffer without the initial #+TITLE: keyword."
3982 :group 'org-appearance
3983 :version "24.1"
3984 :type '(set (const :tag "#+AUTHOR" author)
3985 (const :tag "#+DATE" date)
3986 (const :tag "#+EMAIL" email)
3987 (const :tag "#+TITLE" title)))
3989 (defcustom org-custom-properties nil
3990 "List of properties (as strings) with a special meaning.
3991 The default use of these custom properties is to let the user
3992 hide them with `org-toggle-custom-properties-visibility'."
3993 :group 'org-properties
3994 :group 'org-appearance
3995 :version "24.3"
3996 :type '(repeat (string :tag "Property Name")))
3998 (defcustom org-fontify-done-headline nil
3999 "Non-nil means change the face of a headline if it is marked DONE.
4000 Normally, only the TODO/DONE keyword indicates the state of a headline.
4001 When this is non-nil, the headline after the keyword is set to the
4002 `org-headline-done' as an additional indication."
4003 :group 'org-appearance
4004 :type 'boolean)
4006 (defcustom org-fontify-emphasized-text t
4007 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4008 Changing this variable requires a restart of Emacs to take effect."
4009 :group 'org-appearance
4010 :type 'boolean)
4012 (defcustom org-fontify-whole-heading-line nil
4013 "Non-nil means fontify the whole line for headings.
4014 This is useful when setting a background color for the
4015 org-level-* faces."
4016 :group 'org-appearance
4017 :type 'boolean)
4019 (defcustom org-highlight-latex-and-related nil
4020 "Non-nil means highlight LaTeX related syntax in the buffer.
4021 When non nil, the value should be a list containing any of the
4022 following symbols:
4023 `latex' Highlight LaTeX snippets and environments.
4024 `script' Highlight subscript and superscript.
4025 `entities' Highlight entities."
4026 :group 'org-appearance
4027 :version "24.4"
4028 :package-version '(Org . "8.0")
4029 :type '(choice
4030 (const :tag "No highlighting" nil)
4031 (set :greedy t :tag "Highlight"
4032 (const :tag "LaTeX snippets and environments" latex)
4033 (const :tag "Subscript and superscript" script)
4034 (const :tag "Entities" entities))))
4036 (defcustom org-hide-emphasis-markers nil
4037 "Non-nil mean font-lock should hide the emphasis marker characters."
4038 :group 'org-appearance
4039 :type 'boolean)
4041 (defcustom org-pretty-entities nil
4042 "Non-nil means show entities as UTF8 characters.
4043 When nil, the \\name form remains in the buffer."
4044 :group 'org-appearance
4045 :version "24.1"
4046 :type 'boolean)
4048 (defcustom org-pretty-entities-include-sub-superscripts t
4049 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4050 :group 'org-appearance
4051 :version "24.1"
4052 :type 'boolean)
4054 (defvar org-emph-re nil
4055 "Regular expression for matching emphasis.
4056 After a match, the match groups contain these elements:
4057 0 The match of the full regular expression, including the characters
4058 before and after the proper match
4059 1 The character before the proper match, or empty at beginning of line
4060 2 The proper match, including the leading and trailing markers
4061 3 The leading marker like * or /, indicating the type of highlighting
4062 4 The text between the emphasis markers, not including the markers
4063 5 The character after the match, empty at the end of a line")
4064 (defvar org-verbatim-re nil
4065 "Regular expression for matching verbatim text.")
4066 (defvar org-emphasis-regexp-components) ; defined just below
4067 (defvar org-emphasis-alist) ; defined just below
4068 (defun org-set-emph-re (var val)
4069 "Set variable and compute the emphasis regular expression."
4070 (set var val)
4071 (when (and (boundp 'org-emphasis-alist)
4072 (boundp 'org-emphasis-regexp-components)
4073 org-emphasis-alist org-emphasis-regexp-components)
4074 (let* ((e org-emphasis-regexp-components)
4075 (pre (car e))
4076 (post (nth 1 e))
4077 (border (nth 2 e))
4078 (body (nth 3 e))
4079 (nl (nth 4 e))
4080 (body1 (concat body "*?"))
4081 (markers (mapconcat 'car org-emphasis-alist ""))
4082 (vmarkers (mapconcat
4083 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4084 org-emphasis-alist "")))
4085 ;; make sure special characters appear at the right position in the class
4086 (if (string-match "\\^" markers)
4087 (setq markers (concat (replace-match "" t t markers) "^")))
4088 (if (string-match "-" markers)
4089 (setq markers (concat (replace-match "" t t markers) "-")))
4090 (if (string-match "\\^" vmarkers)
4091 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4092 (if (string-match "-" vmarkers)
4093 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4094 (if (> nl 0)
4095 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4096 (int-to-string nl) "\\}")))
4097 ;; Make the regexp
4098 (setq org-emph-re
4099 (concat "\\([" pre "]\\|^\\)"
4100 "\\("
4101 "\\([" markers "]\\)"
4102 "\\("
4103 "[^" border "]\\|"
4104 "[^" border "]"
4105 body1
4106 "[^" border "]"
4107 "\\)"
4108 "\\3\\)"
4109 "\\([" post "]\\|$\\)"))
4110 (setq org-verbatim-re
4111 (concat "\\([" pre "]\\|^\\)"
4112 "\\("
4113 "\\([" vmarkers "]\\)"
4114 "\\("
4115 "[^" border "]\\|"
4116 "[^" border "]"
4117 body1
4118 "[^" border "]"
4119 "\\)"
4120 "\\3\\)"
4121 "\\([" post "]\\|$\\)")))))
4123 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4124 ;; set this option proved cumbersome. See this message/thread:
4125 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4126 (defvar org-emphasis-regexp-components
4127 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4128 "Components used to build the regular expression for emphasis.
4129 This is a list with five entries. Terminology: In an emphasis string
4130 like \" *strong word* \", we call the initial space PREMATCH, the final
4131 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4132 and \"trong wor\" is the body. The different components in this variable
4133 specify what is allowed/forbidden in each part:
4135 pre Chars allowed as prematch. Beginning of line will be allowed too.
4136 post Chars allowed as postmatch. End of line will be allowed too.
4137 border The chars *forbidden* as border characters.
4138 body-regexp A regexp like \".\" to match a body character. Don't use
4139 non-shy groups here, and don't allow newline here.
4140 newline The maximum number of newlines allowed in an emphasis exp.
4142 You need to reload Org or to restart Emacs after customizing this.")
4144 (defcustom org-emphasis-alist
4145 `(("*" bold)
4146 ("/" italic)
4147 ("_" underline)
4148 ("=" org-verbatim verbatim)
4149 ("~" org-code verbatim)
4150 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4151 "Alist of characters and faces to emphasize text.
4152 Text starting and ending with a special character will be emphasized,
4153 for example *bold*, _underlined_ and /italic/. This variable sets the
4154 marker characters and the face to be used by font-lock for highlighting
4155 in Org-mode Emacs buffers.
4157 You need to reload Org or to restart Emacs after customizing this."
4158 :group 'org-appearance
4159 :set 'org-set-emph-re
4160 :version "24.4"
4161 :package-version '(Org . "8.0")
4162 :type '(repeat
4163 (list
4164 (string :tag "Marker character")
4165 (choice
4166 (face :tag "Font-lock-face")
4167 (plist :tag "Face property list"))
4168 (option (const verbatim)))))
4170 (defvar org-protecting-blocks
4171 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4172 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4173 This is needed for font-lock setup.")
4175 ;;; Miscellaneous options
4177 (defgroup org-completion nil
4178 "Completion in Org-mode."
4179 :tag "Org Completion"
4180 :group 'org)
4182 (defcustom org-completion-use-ido nil
4183 "Non-nil means use ido completion wherever possible.
4184 Note that `ido-mode' must be active for this variable to be relevant.
4185 If you decide to turn this variable on, you might well want to turn off
4186 `org-outline-path-complete-in-steps'.
4187 See also `org-completion-use-iswitchb'."
4188 :group 'org-completion
4189 :type 'boolean)
4191 (defcustom org-completion-use-iswitchb nil
4192 "Non-nil means use iswitchb completion wherever possible.
4193 Note that `iswitchb-mode' must be active for this variable to be relevant.
4194 If you decide to turn this variable on, you might well want to turn off
4195 `org-outline-path-complete-in-steps'.
4196 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4197 :group 'org-completion
4198 :type 'boolean)
4200 (defcustom org-completion-fallback-command 'hippie-expand
4201 "The expansion command called by \\[pcomplete] in normal context.
4202 Normal means, no org-mode-specific context."
4203 :group 'org-completion
4204 :type 'function)
4206 ;;; Functions and variables from their packages
4207 ;; Declared here to avoid compiler warnings
4209 ;; XEmacs only
4210 (defvar outline-mode-menu-heading)
4211 (defvar outline-mode-menu-show)
4212 (defvar outline-mode-menu-hide)
4213 (defvar zmacs-regions) ; XEmacs regions
4215 ;; Emacs only
4216 (defvar mark-active)
4218 ;; Various packages
4219 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4220 (declare-function calendar-forward-day "cal-move" (arg))
4221 (declare-function calendar-goto-date "cal-move" (date))
4222 (declare-function calendar-goto-today "cal-move" ())
4223 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4224 (defvar calc-embedded-close-formula)
4225 (defvar calc-embedded-open-formula)
4226 (declare-function cdlatex-tab "ext:cdlatex" ())
4227 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4228 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4229 (defvar font-lock-unfontify-region-function)
4230 (declare-function iswitchb-read-buffer "iswitchb"
4231 (prompt &optional
4232 default require-match _predicate start matches-set))
4233 (defvar iswitchb-temp-buflist)
4234 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4235 (defvar org-agenda-tags-todo-honor-ignore-options)
4236 (declare-function org-agenda-skip "org-agenda" ())
4237 (declare-function
4238 org-agenda-format-item "org-agenda"
4239 (extra txt &optional level category tags dotime remove-re habitp))
4240 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4241 (declare-function org-agenda-change-all-lines "org-agenda"
4242 (newhead hdmarker &optional fixface just-this))
4243 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4244 (declare-function org-agenda-maybe-redo "org-agenda" ())
4245 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4246 (beg end))
4247 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4248 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4249 "org-agenda" (&optional end))
4250 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4251 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4252 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4253 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4254 (declare-function org-indent-mode "org-indent" (&optional arg))
4255 (declare-function parse-time-string "parse-time" (string))
4256 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4257 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4258 (defvar remember-data-file)
4259 (defvar texmathp-why)
4260 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4261 (declare-function table--at-cell-p "table" (position &optional object at-column))
4263 (defvar org-latex-regexps)
4265 ;;; Autoload and prepare some org modules
4267 ;; Some table stuff that needs to be defined here, because it is used
4268 ;; by the functions setting up org-mode or checking for table context.
4270 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4271 "Detect an org-type or table-type table.")
4272 (defconst org-table-line-regexp "^[ \t]*|"
4273 "Detect an org-type table line.")
4274 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4275 "Detect an org-type table line.")
4276 (defconst org-table-hline-regexp "^[ \t]*|-"
4277 "Detect an org-type table hline.")
4278 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4279 "Detect a table-type table hline.")
4280 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4281 "Detect the first line outside a table when searching from within it.
4282 This works for both table types.")
4284 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4285 "Detect a #+TBLFM line.")
4287 ;;;###autoload
4288 (defun turn-on-orgtbl ()
4289 "Unconditionally turn on `orgtbl-mode'."
4290 (require 'org-table)
4291 (orgtbl-mode 1))
4293 (defun org-at-table-p (&optional table-type)
4294 "Return t if the cursor is inside an org-type table.
4295 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4296 (if org-enable-table-editor
4297 (save-excursion
4298 (beginning-of-line 1)
4299 (looking-at (if table-type org-table-any-line-regexp
4300 org-table-line-regexp)))
4301 nil))
4302 (defsubst org-table-p () (org-at-table-p))
4304 (defun org-at-table.el-p ()
4305 "Return t if and only if we are at a table.el table."
4306 (and (org-at-table-p 'any)
4307 (save-excursion
4308 (goto-char (org-table-begin 'any))
4309 (looking-at org-table1-hline-regexp))))
4311 (defun org-table-recognize-table.el ()
4312 "If there is a table.el table nearby, recognize it and move into it."
4313 (if org-table-tab-recognizes-table.el
4314 (if (org-at-table.el-p)
4315 (progn
4316 (beginning-of-line 1)
4317 (if (looking-at org-table-dataline-regexp)
4319 (if (looking-at org-table1-hline-regexp)
4320 (progn
4321 (beginning-of-line 2)
4322 (if (looking-at org-table-any-border-regexp)
4323 (beginning-of-line -1)))))
4324 (if (re-search-forward "|" (org-table-end t) t)
4325 (progn
4326 (require 'table)
4327 (if (table--at-cell-p (point))
4329 (message "recognizing table.el table...")
4330 (table-recognize-table)
4331 (message "recognizing table.el table...done")))
4332 (error "This should not happen"))
4334 nil)
4335 nil))
4337 (defun org-at-table-hline-p ()
4338 "Return t if the cursor is inside a hline in a table."
4339 (if org-enable-table-editor
4340 (save-excursion
4341 (beginning-of-line 1)
4342 (looking-at org-table-hline-regexp))
4343 nil))
4345 (defun org-table-map-tables (function &optional quietly)
4346 "Apply FUNCTION to the start of all tables in the buffer."
4347 (save-excursion
4348 (save-restriction
4349 (widen)
4350 (goto-char (point-min))
4351 (while (re-search-forward org-table-any-line-regexp nil t)
4352 (unless quietly
4353 (message "Mapping tables: %d%%"
4354 (floor (* 100.0 (point)) (buffer-size))))
4355 (beginning-of-line 1)
4356 (when (and (looking-at org-table-line-regexp)
4357 ;; Exclude tables in src/example/verbatim/clocktable blocks
4358 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4359 (save-excursion (funcall function))
4360 (or (looking-at org-table-line-regexp)
4361 (forward-char 1)))
4362 (re-search-forward org-table-any-border-regexp nil 1))))
4363 (unless quietly (message "Mapping tables: done")))
4365 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4366 (declare-function org-clock-update-mode-line "org-clock" ())
4367 (declare-function org-resolve-clocks "org-clock"
4368 (&optional also-non-dangling-p prompt last-valid))
4370 (defun org-at-TBLFM-p (&optional pos)
4371 "Return t when point (or POS) is in #+TBLFM line."
4372 (save-excursion
4373 (let ((pos pos)))
4374 (goto-char (or pos (point)))
4375 (beginning-of-line 1)
4376 (looking-at org-TBLFM-regexp)))
4378 (defvar org-clock-start-time)
4379 (defvar org-clock-marker (make-marker)
4380 "Marker recording the last clock-in.")
4381 (defvar org-clock-hd-marker (make-marker)
4382 "Marker recording the last clock-in, but the headline position.")
4383 (defvar org-clock-heading ""
4384 "The heading of the current clock entry.")
4385 (defun org-clock-is-active ()
4386 "Return the buffer where the clock is currently running.
4387 Return nil if no clock is running."
4388 (marker-buffer org-clock-marker))
4390 (defun org-check-running-clock ()
4391 "Check if the current buffer contains the running clock.
4392 If yes, offer to stop it and to save the buffer with the changes."
4393 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4394 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4395 (buffer-name))))
4396 (org-clock-out)
4397 (when (y-or-n-p "Save changed buffer?")
4398 (save-buffer))))
4400 (defun org-clocktable-try-shift (dir n)
4401 "Check if this line starts a clock table, if yes, shift the time block."
4402 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4403 (org-clocktable-shift dir n)))
4405 ;;;###autoload
4406 (defun org-clock-persistence-insinuate ()
4407 "Set up hooks for clock persistence."
4408 (require 'org-clock)
4409 (add-hook 'org-mode-hook 'org-clock-load)
4410 (add-hook 'kill-emacs-hook 'org-clock-save))
4412 (defgroup org-archive nil
4413 "Options concerning archiving in Org-mode."
4414 :tag "Org Archive"
4415 :group 'org-structure)
4417 (defcustom org-archive-location "%s_archive::"
4418 "The location where subtrees should be archived.
4420 The value of this variable is a string, consisting of two parts,
4421 separated by a double-colon. The first part is a filename and
4422 the second part is a headline.
4424 When the filename is omitted, archiving happens in the same file.
4425 %s in the filename will be replaced by the current file
4426 name (without the directory part). Archiving to a different file
4427 is useful to keep archived entries from contributing to the
4428 Org-mode Agenda.
4430 The archived entries will be filed as subtrees of the specified
4431 headline. When the headline is omitted, the subtrees are simply
4432 filed away at the end of the file, as top-level entries. Also in
4433 the heading you can use %s to represent the file name, this can be
4434 useful when using the same archive for a number of different files.
4436 Here are a few examples:
4437 \"%s_archive::\"
4438 If the current file is Projects.org, archive in file
4439 Projects.org_archive, as top-level trees. This is the default.
4441 \"::* Archived Tasks\"
4442 Archive in the current file, under the top-level headline
4443 \"* Archived Tasks\".
4445 \"~/org/archive.org::\"
4446 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4448 \"~/org/archive.org::* From %s\"
4449 Archive in file ~/org/archive.org (absolute path), under headlines
4450 \"From FILENAME\" where file name is the current file name.
4452 \"~/org/datetree.org::datetree/* Finished Tasks\"
4453 The \"datetree/\" string is special, signifying to archive
4454 items to the datetree. Items are placed in either the CLOSED
4455 date of the item, or the current date if there is no CLOSED date.
4456 The heading will be a subentry to the current date. There doesn't
4457 need to be a heading, but there always needs to be a slash after
4458 datetree. For example, to store archived items directly in the
4459 datetree, use \"~/org/datetree.org::datetree/\".
4461 \"basement::** Finished Tasks\"
4462 Archive in file ./basement (relative path), as level 3 trees
4463 below the level 2 heading \"** Finished Tasks\".
4465 You may set this option on a per-file basis by adding to the buffer a
4466 line like
4468 #+ARCHIVE: basement::** Finished Tasks
4470 You may also define it locally for a subtree by setting an ARCHIVE property
4471 in the entry. If such a property is found in an entry, or anywhere up
4472 the hierarchy, it will be used."
4473 :group 'org-archive
4474 :type 'string)
4476 (defcustom org-archive-tag "ARCHIVE"
4477 "The tag that marks a subtree as archived.
4478 An archived subtree does not open during visibility cycling, and does
4479 not contribute to the agenda listings.
4480 After changing this, font-lock must be restarted in the relevant buffers to
4481 get the proper fontification."
4482 :group 'org-archive
4483 :group 'org-keywords
4484 :type 'string)
4486 (defcustom org-agenda-skip-archived-trees t
4487 "Non-nil means the agenda will skip any items located in archived trees.
4488 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4489 variable is no longer recommended, you should leave it at the value t.
4490 Instead, use the key `v' to cycle the archives-mode in the agenda."
4491 :group 'org-archive
4492 :group 'org-agenda-skip
4493 :type 'boolean)
4495 (defcustom org-columns-skip-archived-trees t
4496 "Non-nil means ignore archived trees when creating column view."
4497 :group 'org-archive
4498 :group 'org-properties
4499 :type 'boolean)
4501 (defcustom org-cycle-open-archived-trees nil
4502 "Non-nil means `org-cycle' will open archived trees.
4503 An archived tree is a tree marked with the tag ARCHIVE.
4504 When nil, archived trees will stay folded. You can still open them with
4505 normal outline commands like `show-all', but not with the cycling commands."
4506 :group 'org-archive
4507 :group 'org-cycle
4508 :type 'boolean)
4510 (defcustom org-sparse-tree-open-archived-trees nil
4511 "Non-nil means sparse tree construction shows matches in archived trees.
4512 When nil, matches in these trees are highlighted, but the trees are kept in
4513 collapsed state."
4514 :group 'org-archive
4515 :group 'org-sparse-trees
4516 :type 'boolean)
4518 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4519 "The default date type when building a sparse tree.
4520 When this is nil, a date is a scheduled or a deadline timestamp.
4521 Otherwise, these types are allowed:
4523 all: all timestamps
4524 active: only active timestamps (<...>)
4525 inactive: only inactive timestamps (<...)
4526 scheduled: only scheduled timestamps
4527 deadline: only deadline timestamps"
4528 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4529 (const :tag "All timestamps" all)
4530 (const :tag "Only active timestamps" active)
4531 (const :tag "Only inactive timestamps" inactive)
4532 (const :tag "Only scheduled timestamps" scheduled)
4533 (const :tag "Only deadline timestamps" deadline)
4534 (const :tag "Only closed timestamps" closed))
4535 :version "24.3"
4536 :group 'org-sparse-trees)
4538 (defun org-cycle-hide-archived-subtrees (state)
4539 "Re-hide all archived subtrees after a visibility state change."
4540 (when (and (not org-cycle-open-archived-trees)
4541 (not (memq state '(overview folded))))
4542 (save-excursion
4543 (let* ((globalp (memq state '(contents all)))
4544 (beg (if globalp (point-min) (point)))
4545 (end (if globalp (point-max) (org-end-of-subtree t))))
4546 (org-hide-archived-subtrees beg end)
4547 (goto-char beg)
4548 (if (looking-at (concat ".*:" org-archive-tag ":"))
4549 (message "%s" (substitute-command-keys
4550 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4552 (defun org-force-cycle-archived ()
4553 "Cycle subtree even if it is archived."
4554 (interactive)
4555 (setq this-command 'org-cycle)
4556 (let ((org-cycle-open-archived-trees t))
4557 (call-interactively 'org-cycle)))
4559 (defun org-hide-archived-subtrees (beg end)
4560 "Re-hide all archived subtrees after a visibility state change."
4561 (save-excursion
4562 (let* ((re (concat ":" org-archive-tag ":")))
4563 (goto-char beg)
4564 (while (re-search-forward re end t)
4565 (when (org-at-heading-p)
4566 (org-flag-subtree t)
4567 (org-end-of-subtree t))))))
4569 (declare-function outline-end-of-heading "outline" ())
4570 (declare-function outline-flag-region "outline" (from to flag))
4571 (defun org-flag-subtree (flag)
4572 (save-excursion
4573 (org-back-to-heading t)
4574 (outline-end-of-heading)
4575 (outline-flag-region (point)
4576 (progn (org-end-of-subtree t) (point))
4577 flag)))
4579 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4581 ;; Declare Column View Code
4583 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4584 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4585 (declare-function org-columns-compute "org-colview" (property))
4587 ;; Declare ID code
4589 (declare-function org-id-store-link "org-id")
4590 (declare-function org-id-locations-load "org-id")
4591 (declare-function org-id-locations-save "org-id")
4592 (defvar org-id-track-globally)
4594 ;;; Variables for pre-computed regular expressions, all buffer local
4596 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4597 "Matches first line of a hidden block.")
4598 (make-variable-buffer-local 'org-drawer-regexp)
4599 (defvar org-todo-regexp nil
4600 "Matches any of the TODO state keywords.")
4601 (make-variable-buffer-local 'org-todo-regexp)
4602 (defvar org-not-done-regexp nil
4603 "Matches any of the TODO state keywords except the last one.")
4604 (make-variable-buffer-local 'org-not-done-regexp)
4605 (defvar org-not-done-heading-regexp nil
4606 "Matches a TODO headline that is not done.")
4607 (make-variable-buffer-local 'org-not-done-regexp)
4608 (defvar org-todo-line-regexp nil
4609 "Matches a headline and puts TODO state into group 2 if present.")
4610 (make-variable-buffer-local 'org-todo-line-regexp)
4611 (defvar org-complex-heading-regexp nil
4612 "Matches a headline and puts everything into groups:
4613 group 1: the stars
4614 group 2: The todo keyword, maybe
4615 group 3: Priority cookie
4616 group 4: True headline
4617 group 5: Tags")
4618 (make-variable-buffer-local 'org-complex-heading-regexp)
4619 (defvar org-complex-heading-regexp-format nil
4620 "Printf format to make regexp to match an exact headline.
4621 This regexp will match the headline of any node which has the
4622 exact headline text that is put into the format, but may have any
4623 TODO state, priority and tags.")
4624 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4625 (defvar org-todo-line-tags-regexp nil
4626 "Matches a headline and puts TODO state into group 2 if present.
4627 Also put tags into group 4 if tags are present.")
4628 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4629 (defvar org-ds-keyword-length 12
4630 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4631 (make-variable-buffer-local 'org-ds-keyword-length)
4632 (defvar org-deadline-regexp nil
4633 "Matches the DEADLINE keyword.")
4634 (make-variable-buffer-local 'org-deadline-regexp)
4635 (defvar org-deadline-time-regexp nil
4636 "Matches the DEADLINE keyword together with a time stamp.")
4637 (make-variable-buffer-local 'org-deadline-time-regexp)
4638 (defvar org-deadline-time-hour-regexp nil
4639 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4640 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4641 (defvar org-deadline-line-regexp nil
4642 "Matches the DEADLINE keyword and the rest of the line.")
4643 (make-variable-buffer-local 'org-deadline-line-regexp)
4644 (defvar org-scheduled-regexp nil
4645 "Matches the SCHEDULED keyword.")
4646 (make-variable-buffer-local 'org-scheduled-regexp)
4647 (defvar org-scheduled-time-regexp nil
4648 "Matches the SCHEDULED keyword together with a time stamp.")
4649 (make-variable-buffer-local 'org-scheduled-time-regexp)
4650 (defvar org-scheduled-time-hour-regexp nil
4651 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4652 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4653 (defvar org-closed-time-regexp nil
4654 "Matches the CLOSED keyword together with a time stamp.")
4655 (make-variable-buffer-local 'org-closed-time-regexp)
4657 (defvar org-keyword-time-regexp nil
4658 "Matches any of the 4 keywords, together with the time stamp.")
4659 (make-variable-buffer-local 'org-keyword-time-regexp)
4660 (defvar org-keyword-time-not-clock-regexp nil
4661 "Matches any of the 3 keywords, together with the time stamp.")
4662 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4663 (defvar org-maybe-keyword-time-regexp nil
4664 "Matches a timestamp, possibly preceded by a keyword.")
4665 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4666 (defvar org-all-time-keywords nil
4667 "List of time keywords.")
4668 (make-variable-buffer-local 'org-all-time-keywords)
4670 (defconst org-plain-time-of-day-regexp
4671 (concat
4672 "\\(\\<[012]?[0-9]"
4673 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4674 "\\(--?"
4675 "\\(\\<[012]?[0-9]"
4676 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4677 "\\)?")
4678 "Regular expression to match a plain time or time range.
4679 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4680 groups carry important information:
4681 0 the full match
4682 1 the first time, range or not
4683 8 the second time, if it is a range.")
4685 (defconst org-plain-time-extension-regexp
4686 (concat
4687 "\\(\\<[012]?[0-9]"
4688 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4689 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4690 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4691 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4692 groups carry important information:
4693 0 the full match
4694 7 hours of duration
4695 9 minutes of duration")
4697 (defconst org-stamp-time-of-day-regexp
4698 (concat
4699 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4700 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4701 "\\(--?"
4702 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4703 "Regular expression to match a timestamp time or time range.
4704 After a match, the following groups carry important information:
4705 0 the full match
4706 1 date plus weekday, for back referencing to make sure both times are on the same day
4707 2 the first time, range or not
4708 4 the second time, if it is a range.")
4710 (defconst org-startup-options
4711 '(("fold" org-startup-folded t)
4712 ("overview" org-startup-folded t)
4713 ("nofold" org-startup-folded nil)
4714 ("showall" org-startup-folded nil)
4715 ("showeverything" org-startup-folded showeverything)
4716 ("content" org-startup-folded content)
4717 ("indent" org-startup-indented t)
4718 ("noindent" org-startup-indented nil)
4719 ("hidestars" org-hide-leading-stars t)
4720 ("showstars" org-hide-leading-stars nil)
4721 ("odd" org-odd-levels-only t)
4722 ("oddeven" org-odd-levels-only nil)
4723 ("align" org-startup-align-all-tables t)
4724 ("noalign" org-startup-align-all-tables nil)
4725 ("inlineimages" org-startup-with-inline-images t)
4726 ("noinlineimages" org-startup-with-inline-images nil)
4727 ("latexpreview" org-startup-with-latex-preview t)
4728 ("nolatexpreview" org-startup-with-latex-preview nil)
4729 ("customtime" org-display-custom-times t)
4730 ("logdone" org-log-done time)
4731 ("lognotedone" org-log-done note)
4732 ("nologdone" org-log-done nil)
4733 ("lognoteclock-out" org-log-note-clock-out t)
4734 ("nolognoteclock-out" org-log-note-clock-out nil)
4735 ("logrepeat" org-log-repeat state)
4736 ("lognoterepeat" org-log-repeat note)
4737 ("logdrawer" org-log-into-drawer t)
4738 ("nologdrawer" org-log-into-drawer nil)
4739 ("logstatesreversed" org-log-states-order-reversed t)
4740 ("nologstatesreversed" org-log-states-order-reversed nil)
4741 ("nologrepeat" org-log-repeat nil)
4742 ("logreschedule" org-log-reschedule time)
4743 ("lognotereschedule" org-log-reschedule note)
4744 ("nologreschedule" org-log-reschedule nil)
4745 ("logredeadline" org-log-redeadline time)
4746 ("lognoteredeadline" org-log-redeadline note)
4747 ("nologredeadline" org-log-redeadline nil)
4748 ("logrefile" org-log-refile time)
4749 ("lognoterefile" org-log-refile note)
4750 ("nologrefile" org-log-refile nil)
4751 ("fninline" org-footnote-define-inline t)
4752 ("nofninline" org-footnote-define-inline nil)
4753 ("fnlocal" org-footnote-section nil)
4754 ("fnauto" org-footnote-auto-label t)
4755 ("fnprompt" org-footnote-auto-label nil)
4756 ("fnconfirm" org-footnote-auto-label confirm)
4757 ("fnplain" org-footnote-auto-label plain)
4758 ("fnadjust" org-footnote-auto-adjust t)
4759 ("nofnadjust" org-footnote-auto-adjust nil)
4760 ("constcgs" constants-unit-system cgs)
4761 ("constSI" constants-unit-system SI)
4762 ("noptag" org-tag-persistent-alist nil)
4763 ("hideblocks" org-hide-block-startup t)
4764 ("nohideblocks" org-hide-block-startup nil)
4765 ("beamer" org-startup-with-beamer-mode t)
4766 ("entitiespretty" org-pretty-entities t)
4767 ("entitiesplain" org-pretty-entities nil))
4768 "Variable associated with STARTUP options for org-mode.
4769 Each element is a list of three items: the startup options (as written
4770 in the #+STARTUP line), the corresponding variable, and the value to set
4771 this variable to if the option is found. An optional forth element PUSH
4772 means to push this value onto the list in the variable.")
4774 (defun org-update-property-plist (key val props)
4775 "Update PROPS with KEY and VAL."
4776 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4777 (key (if appending (substring key 0 (- (length key) 1)) key))
4778 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4779 (previous (cdr (assoc key props))))
4780 (if appending
4781 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4782 (cons (cons key val) remainder))))
4784 (defconst org-block-regexp
4785 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4786 "Regular expression for hiding blocks.")
4787 (defconst org-heading-keyword-regexp-format
4788 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4789 "Printf format for a regexp matching a headline with some keyword.
4790 This regexp will match the headline of any node which has the
4791 exact keyword that is put into the format. The keyword isn't in
4792 any group by default, but the stars and the body are.")
4793 (defconst org-heading-keyword-maybe-regexp-format
4794 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4795 "Printf format for a regexp matching a headline, possibly with some keyword.
4796 This regexp can match any headline with the specified keyword, or
4797 without a keyword. The keyword isn't in any group by default,
4798 but the stars and the body are.")
4800 (defcustom org-group-tags t
4801 "When non-nil (the default), use group tags.
4802 This can be turned on/off through `org-toggle-tags-groups'."
4803 :group 'org-tags
4804 :group 'org-startup
4805 :type 'boolean)
4807 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4809 (defun org-toggle-tags-groups ()
4810 "Toggle support for group tags.
4811 Support for group tags is controlled by the option
4812 `org-group-tags', which is non-nil by default."
4813 (interactive)
4814 (setq org-group-tags (not org-group-tags))
4815 (cond ((and (derived-mode-p 'org-agenda-mode)
4816 org-group-tags)
4817 (org-agenda-redo))
4818 ((derived-mode-p 'org-mode)
4819 (let ((org-inhibit-startup t)) (org-mode))))
4820 (message "Groups tags support has been turned %s"
4821 (if org-group-tags "on" "off")))
4823 (defun org-set-regexps-and-options-for-tags ()
4824 "Precompute variables used for tags."
4825 (when (derived-mode-p 'org-mode)
4826 (org-set-local 'org-file-tags nil)
4827 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4828 (splitre "[ \t]+")
4829 (start 0)
4830 tags ftags key value)
4831 (save-excursion
4832 (save-restriction
4833 (widen)
4834 (goto-char (point-min))
4835 (while (re-search-forward re nil t)
4836 (setq key (upcase (org-match-string-no-properties 1))
4837 value (org-match-string-no-properties 2))
4838 (if (stringp value) (setq value (org-trim value)))
4839 (cond
4840 ((equal key "TAGS")
4841 (setq tags (append tags (if tags '("\\n") nil)
4842 (org-split-string value splitre))))
4843 ((equal key "FILETAGS")
4844 (when (string-match "\\S-" value)
4845 (setq ftags
4846 (append
4847 ftags
4848 (apply 'append
4849 (mapcar (lambda (x) (org-split-string x ":"))
4850 (org-split-string value)))))))))))
4851 ;; Process the file tags.
4852 (and ftags (org-set-local 'org-file-tags
4853 (mapcar 'org-add-prop-inherited ftags)))
4854 (org-set-local 'org-tag-groups-alist nil)
4855 ;; Process the tags.
4856 (when (and (not tags) org-tag-alist)
4857 (setq tags
4858 (mapcar
4859 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4860 ((eq (car tg) :endgroup) "}")
4861 ((eq (car tg) :grouptags) ":")
4862 ((eq (car tg) :newline) "\n")
4863 (t (concat (car tg)
4864 (if (characterp (cdr tg))
4865 (format "(%s)" (char-to-string (cdr tg))) "")))))
4866 org-tag-alist)))
4867 (let (tgs g)
4868 (dolist (e tags)
4869 (cond
4870 ((equal e "{")
4871 (progn (push '(:startgroup) tgs)
4872 (when (equal (nth 1 tags) ":")
4873 (push (list (replace-regexp-in-string
4874 "(.+)$" "" (nth 0 tags)))
4875 org-tag-groups-alist)
4876 (setq g 0))))
4877 ((equal e ":") (push '(:grouptags) tgs))
4878 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4879 ((equal e "\\n") (push '(:newline) tgs))
4880 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4881 (push (cons (match-string 1 e)
4882 (string-to-char (match-string 2 e)))
4883 tgs)
4884 (if (and g (> g 0))
4885 (setcar org-tag-groups-alist
4886 (append (car org-tag-groups-alist)
4887 (list (match-string 1 e)))))
4888 (if g (setq g (1+ g))))
4889 (t (push (list e) tgs)
4890 (if (and g (> g 0))
4891 (setcar org-tag-groups-alist
4892 (append (car org-tag-groups-alist) (list e))))
4893 (if g (setq g (1+ g))))))
4894 (org-set-local 'org-tag-alist nil)
4895 (dolist (e tgs)
4896 (or (and (stringp (car e))
4897 (assoc (car e) org-tag-alist))
4898 (push e org-tag-alist)))
4899 ;; Return a list with tag variables
4900 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4902 (defvar org-ota nil)
4903 (defun org-set-regexps-and-options ()
4904 "Precompute regular expressions used in the current buffer."
4905 (when (derived-mode-p 'org-mode)
4906 (org-set-local 'org-todo-kwd-alist nil)
4907 (org-set-local 'org-todo-key-alist nil)
4908 (org-set-local 'org-todo-key-trigger nil)
4909 (org-set-local 'org-todo-keywords-1 nil)
4910 (org-set-local 'org-done-keywords nil)
4911 (org-set-local 'org-todo-heads nil)
4912 (org-set-local 'org-todo-sets nil)
4913 (org-set-local 'org-todo-log-states nil)
4914 (org-set-local 'org-file-properties nil)
4915 (let ((re (org-make-options-regexp
4916 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4917 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4918 "SETUPFILE" "OPTIONS")
4919 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4920 (splitre "[ \t]+")
4921 (scripts org-use-sub-superscripts)
4922 kwds kws0 kwsa key log value cat arch const links hw dws
4923 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4924 (start 0))
4925 (save-excursion
4926 (save-restriction
4927 (widen)
4928 (goto-char (point-min))
4929 (while
4930 (or (and
4931 ext-setup-or-nil
4932 (not org-ota)
4933 (let (ret)
4934 (with-temp-buffer
4935 (insert ext-setup-or-nil)
4936 (let ((major-mode 'org-mode) org-ota)
4937 (setq ret (save-match-data
4938 (org-set-regexps-and-options-for-tags)))))
4939 ;; Append setupfile tags to existing tags
4940 (setq org-ota t)
4941 (setq org-file-tags
4942 (delq nil (append org-file-tags (nth 0 ret)))
4943 org-tag-alist
4944 (delq nil (append org-tag-alist (nth 1 ret)))
4945 org-tag-groups-alist
4946 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4947 (and ext-setup-or-nil
4948 (string-match re ext-setup-or-nil start)
4949 (setq start (match-end 0)))
4950 (and (setq ext-setup-or-nil nil start 0)
4951 (re-search-forward re nil t)))
4952 (setq key (upcase (match-string 1 ext-setup-or-nil))
4953 value (org-match-string-no-properties 2 ext-setup-or-nil))
4954 (if (stringp value) (setq value (org-trim value)))
4955 (cond
4956 ((equal key "CATEGORY")
4957 (setq cat value))
4958 ((member key '("SEQ_TODO" "TODO"))
4959 (push (cons 'sequence (org-split-string value splitre)) kwds))
4960 ((equal key "TYP_TODO")
4961 (push (cons 'type (org-split-string value splitre)) kwds))
4962 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4963 ;; general TODO-like setup
4964 (push (cons (intern (downcase (match-string 1 key)))
4965 (org-split-string value splitre))
4966 kwds))
4967 ((equal key "COLUMNS")
4968 (org-set-local 'org-columns-default-format value))
4969 ((equal key "LINK")
4970 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4971 (push (cons (match-string 1 value)
4972 (org-trim (match-string 2 value)))
4973 links)))
4974 ((equal key "PRIORITIES")
4975 (setq prio (org-split-string value " +")))
4976 ((equal key "PROPERTY")
4977 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4978 (setq props (org-update-property-plist (match-string 1 value)
4979 (match-string 2 value)
4980 props))))
4981 ((equal key "DRAWERS")
4982 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4983 ((equal key "CONSTANTS")
4984 (org-table-set-constants))
4985 ((equal key "STARTUP")
4986 (let ((opts (org-split-string value splitre))
4987 var val)
4988 (dolist (l opts)
4989 (when (setq l (assoc l org-startup-options))
4990 (setq var (nth 1 l) val (nth 2 l))
4991 (if (not (nth 3 l))
4992 (set (make-local-variable var) val)
4993 (if (not (listp (symbol-value var)))
4994 (set (make-local-variable var) nil))
4995 (set (make-local-variable var) (symbol-value var))
4996 (add-to-list var val))))))
4997 ((equal key "ARCHIVE")
4998 (setq arch value)
4999 (remove-text-properties 0 (length arch)
5000 '(face t fontified t) arch))
5001 ((equal key "OPTIONS")
5002 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5003 (setq scripts (read (match-string 2 value)))))
5004 ((and (equal key "SETUPFILE")
5005 ;; Prevent checking in Gnus messages
5006 (not buffer-read-only))
5007 (setq setup-contents (org-file-contents
5008 (expand-file-name
5009 (org-remove-double-quotes value))
5010 'noerror))
5011 (if (not ext-setup-or-nil)
5012 (setq ext-setup-or-nil setup-contents start 0)
5013 (setq ext-setup-or-nil
5014 (concat (substring ext-setup-or-nil 0 start)
5015 "\n" setup-contents "\n"
5016 (substring ext-setup-or-nil start)))))))
5017 ;; search for property blocks
5018 (goto-char (point-min))
5019 (while (re-search-forward org-block-regexp nil t)
5020 (when (equal "PROPERTY" (upcase (match-string 1)))
5021 (setq value (replace-regexp-in-string
5022 "[\n\r]" " " (match-string 4)))
5023 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5024 (setq props (org-update-property-plist (match-string 1 value)
5025 (match-string 2 value)
5026 props)))))))
5027 (org-set-local 'org-use-sub-superscripts scripts)
5028 (when cat
5029 (org-set-local 'org-category (intern cat))
5030 (push (cons "CATEGORY" cat) props))
5031 (when prio
5032 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5033 (setq prio (mapcar 'string-to-char prio))
5034 (org-set-local 'org-highest-priority (nth 0 prio))
5035 (org-set-local 'org-lowest-priority (nth 1 prio))
5036 (org-set-local 'org-default-priority (nth 2 prio)))
5037 (and props (org-set-local 'org-file-properties (nreverse props)))
5038 (and drawers (org-set-local 'org-drawers drawers))
5039 (and arch (org-set-local 'org-archive-location arch))
5040 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5041 ;; Process the TODO keywords
5042 (unless kwds
5043 ;; Use the global values as if they had been given locally.
5044 (setq kwds (default-value 'org-todo-keywords))
5045 (if (stringp (car kwds))
5046 (setq kwds (list (cons org-todo-interpretation
5047 (default-value 'org-todo-keywords)))))
5048 (setq kwds (reverse kwds)))
5049 (setq kwds (nreverse kwds))
5050 (let (inter kw)
5051 (dolist (kws kwds)
5052 (let ((kws (or
5053 (run-hook-with-args-until-success
5054 'org-todo-setup-filter-hook kws)
5055 kws)))
5056 (setq inter (pop kws) sep (member "|" kws)
5057 kws0 (delete "|" (copy-sequence kws))
5058 kwsa nil
5059 kws1 (mapcar
5060 (lambda (x)
5061 ;; 1 2
5062 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5063 (progn
5064 (setq kw (match-string 1 x)
5065 key (and (match-end 2) (match-string 2 x))
5066 log (org-extract-log-state-settings x))
5067 (push (cons kw (and key (string-to-char key))) kwsa)
5068 (and log (push log org-todo-log-states))
5070 (error "Invalid TODO keyword %s" x)))
5071 kws0)
5072 kwsa (if kwsa (append '((:startgroup))
5073 (nreverse kwsa)
5074 '((:endgroup))))
5075 hw (car kws1)
5076 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5077 tail (list inter hw (car dws) (org-last dws))))
5078 (add-to-list 'org-todo-heads hw 'append)
5079 (push kws1 org-todo-sets)
5080 (setq org-done-keywords (append org-done-keywords dws nil))
5081 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5082 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5083 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5084 (setq org-todo-sets (nreverse org-todo-sets)
5085 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5086 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5087 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5088 ;; Compute the regular expressions and other local variables.
5089 ;; Using `org-outline-regexp-bol' would complicate them much,
5090 ;; because of the fixed white space at the end of that string.
5091 (if (not org-done-keywords)
5092 (setq org-done-keywords (and org-todo-keywords-1
5093 (list (org-last org-todo-keywords-1)))))
5094 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5095 (length org-scheduled-string)
5096 (length org-clock-string)
5097 (length org-closed-string)))
5098 org-drawer-regexp
5099 (concat "^[ \t]*:\\("
5100 (mapconcat 'regexp-quote org-drawers "\\|")
5101 "\\):[ \t]*$")
5102 org-not-done-keywords
5103 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5104 org-todo-regexp
5105 (concat "\\("
5106 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5107 "\\)")
5108 org-not-done-regexp
5109 (concat "\\("
5110 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5111 "\\)")
5112 org-not-done-heading-regexp
5113 (format org-heading-keyword-regexp-format org-not-done-regexp)
5114 org-todo-line-regexp
5115 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5116 org-complex-heading-regexp
5117 (concat "^\\(\\*+\\)"
5118 "\\(?: +" org-todo-regexp "\\)?"
5119 "\\(?: +\\(\\[#.\\]\\)\\)?"
5120 "\\(?: +\\(.*?\\)\\)??"
5121 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5122 "[ \t]*$")
5123 org-complex-heading-regexp-format
5124 (concat "^\\(\\*+\\)"
5125 "\\(?: +" org-todo-regexp "\\)?"
5126 "\\(?: +\\(\\[#.\\]\\)\\)?"
5127 "\\(?: +"
5128 ;; Stats cookies can be stuck to body.
5129 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5130 "\\(%s\\)"
5131 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5132 "\\)"
5133 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5134 "[ \t]*$")
5135 org-todo-line-tags-regexp
5136 (concat "^\\(\\*+\\)"
5137 "\\(?: +" org-todo-regexp "\\)?"
5138 "\\(?: +\\(.*?\\)\\)??"
5139 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5140 "[ \t]*$")
5141 org-deadline-regexp (concat "\\<" org-deadline-string)
5142 org-deadline-time-regexp
5143 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5144 org-deadline-time-hour-regexp
5145 (concat "\\<" org-deadline-string
5146 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5147 org-deadline-line-regexp
5148 (concat "\\<\\(" org-deadline-string "\\).*")
5149 org-scheduled-regexp
5150 (concat "\\<" org-scheduled-string)
5151 org-scheduled-time-regexp
5152 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5153 org-scheduled-time-hour-regexp
5154 (concat "\\<" org-scheduled-string
5155 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5156 org-closed-time-regexp
5157 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5158 org-keyword-time-regexp
5159 (concat "\\<\\(" org-scheduled-string
5160 "\\|" org-deadline-string
5161 "\\|" org-closed-string
5162 "\\|" org-clock-string "\\)"
5163 " *[[<]\\([^]>]+\\)[]>]")
5164 org-keyword-time-not-clock-regexp
5165 (concat "\\<\\(" org-scheduled-string
5166 "\\|" org-deadline-string
5167 "\\|" org-closed-string
5168 "\\)"
5169 " *[[<]\\([^]>]+\\)[]>]")
5170 org-maybe-keyword-time-regexp
5171 (concat "\\(\\<\\(" org-scheduled-string
5172 "\\|" org-deadline-string
5173 "\\|" org-closed-string
5174 "\\|" org-clock-string "\\)\\)?"
5175 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5176 org-all-time-keywords
5177 (mapcar (lambda (w) (substring w 0 -1))
5178 (list org-scheduled-string org-deadline-string
5179 org-clock-string org-closed-string)))
5180 (setq org-ota nil)
5181 (org-compute-latex-and-related-regexp))))
5183 (defun org-file-contents (file &optional noerror)
5184 "Return the contents of FILE, as a string."
5185 (if (or (not file) (not (file-readable-p file)))
5186 (if (not noerror)
5187 (error "Cannot read file \"%s\"" file)
5188 (message "Cannot read file \"%s\"" file)
5190 (with-temp-buffer
5191 (insert-file-contents file)
5192 (buffer-string))))
5194 (defun org-extract-log-state-settings (x)
5195 "Extract the log state setting from a TODO keyword string.
5196 This will extract info from a string like \"WAIT(w@/!)\"."
5197 (let (kw key log1 log2)
5198 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5199 (setq kw (match-string 1 x)
5200 key (and (match-end 2) (match-string 2 x))
5201 log1 (and (match-end 3) (match-string 3 x))
5202 log2 (and (match-end 4) (match-string 4 x)))
5203 (and (or log1 log2)
5204 (list kw
5205 (and log1 (if (equal log1 "!") 'time 'note))
5206 (and log2 (if (equal log2 "!") 'time 'note)))))))
5208 (defun org-remove-keyword-keys (list)
5209 "Remove a pair of parenthesis at the end of each string in LIST."
5210 (mapcar (lambda (x)
5211 (if (string-match "(.*)$" x)
5212 (substring x 0 (match-beginning 0))
5214 list))
5216 (defun org-assign-fast-keys (alist)
5217 "Assign fast keys to a keyword-key alist.
5218 Respect keys that are already there."
5219 (let (new (alt ?0))
5220 (dolist (e alist)
5221 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5222 (cdr e)) ;; Key already assigned.
5223 (push e new)
5224 (let ((clist (string-to-list (downcase (car e))))
5225 (used (append new alist)))
5226 (when (= (car clist) ?@)
5227 (pop clist))
5228 (while (and clist (rassoc (car clist) used))
5229 (pop clist))
5230 (unless clist
5231 (while (rassoc alt used)
5232 (incf alt)))
5233 (push (cons (car e) (or (car clist) alt)) new))))
5234 (nreverse new)))
5236 ;;; Some variables used in various places
5238 (defvar org-window-configuration nil
5239 "Used in various places to store a window configuration.")
5240 (defvar org-selected-window nil
5241 "Used in various places to store a window configuration.")
5242 (defvar org-finish-function nil
5243 "Function to be called when `C-c C-c' is used.
5244 This is for getting out of special buffers like capture.")
5247 ;; FIXME: Occasionally check by commenting these, to make sure
5248 ;; no other functions uses these, forgetting to let-bind them.
5249 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5250 (defvar org-last-state)
5251 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5253 ;; Defined somewhere in this file, but used before definition.
5254 (defvar org-entities) ;; defined in org-entities.el
5255 (defvar org-struct-menu)
5256 (defvar org-org-menu)
5257 (defvar org-tbl-menu)
5259 ;;;; Define the Org-mode
5261 ;; We use a before-change function to check if a table might need
5262 ;; an update.
5263 (defvar org-table-may-need-update t
5264 "Indicates that a table might need an update.
5265 This variable is set by `org-before-change-function'.
5266 `org-table-align' sets it back to nil.")
5267 (defun org-before-change-function (beg end)
5268 "Every change indicates that a table might need an update."
5269 (setq org-table-may-need-update t))
5270 (defvar org-mode-map)
5271 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5272 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5273 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5274 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5275 (defvar org-table-buffer-is-an nil)
5277 (defvar bidi-paragraph-direction)
5278 (defvar buffer-face-mode-face)
5280 (require 'outline)
5281 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5282 (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"))
5283 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5285 ;; Other stuff we need.
5286 (require 'time-date)
5287 (require 'easymenu)
5288 (require 'overlay)
5290 ;; (require 'org-macs) moved higher up in the file before it is first used
5291 (require 'org-entities)
5292 ;; (require 'org-compat) moved higher up in the file before it is first used
5293 (require 'org-faces)
5294 (require 'org-list)
5295 (require 'org-pcomplete)
5296 (require 'org-src)
5297 (require 'org-footnote)
5298 (require 'org-macro)
5300 ;; babel
5301 (require 'ob)
5303 ;;;###autoload
5304 (define-derived-mode org-mode outline-mode "Org"
5305 "Outline-based notes management and organizer, alias
5306 \"Carsten's outline-mode for keeping track of everything.\"
5308 Org-mode develops organizational tasks around a NOTES file which
5309 contains information about projects as plain text. Org-mode is
5310 implemented on top of outline-mode, which is ideal to keep the content
5311 of large files well structured. It supports ToDo items, deadlines and
5312 time stamps, which magically appear in the diary listing of the Emacs
5313 calendar. Tables are easily created with a built-in table editor.
5314 Plain text URL-like links connect to websites, emails (VM), Usenet
5315 messages (Gnus), BBDB entries, and any files related to the project.
5316 For printing and sharing of notes, an Org-mode file (or a part of it)
5317 can be exported as a structured ASCII or HTML file.
5319 The following commands are available:
5321 \\{org-mode-map}"
5323 ;; Get rid of Outline menus, they are not needed
5324 ;; Need to do this here because define-derived-mode sets up
5325 ;; the keymap so late. Still, it is a waste to call this each time
5326 ;; we switch another buffer into org-mode.
5327 (if (featurep 'xemacs)
5328 (when (boundp 'outline-mode-menu-heading)
5329 ;; Assume this is Greg's port, it uses easymenu
5330 (easy-menu-remove outline-mode-menu-heading)
5331 (easy-menu-remove outline-mode-menu-show)
5332 (easy-menu-remove outline-mode-menu-hide))
5333 (define-key org-mode-map [menu-bar headings] 'undefined)
5334 (define-key org-mode-map [menu-bar hide] 'undefined)
5335 (define-key org-mode-map [menu-bar show] 'undefined))
5337 (org-load-modules-maybe)
5338 (when (featurep 'xemacs)
5339 (easy-menu-add org-org-menu)
5340 (easy-menu-add org-tbl-menu))
5341 (org-install-agenda-files-menu)
5342 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5343 (add-to-invisibility-spec '(org-cwidth))
5344 (add-to-invisibility-spec '(org-hide-block . t))
5345 (when (featurep 'xemacs)
5346 (org-set-local 'line-move-ignore-invisible t))
5347 (org-set-local 'outline-regexp org-outline-regexp)
5348 (org-set-local 'outline-level 'org-outline-level)
5349 (setq bidi-paragraph-direction 'left-to-right)
5350 (when (and org-ellipsis
5351 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5352 (fboundp 'make-glyph-code))
5353 (unless org-display-table
5354 (setq org-display-table (make-display-table)))
5355 (set-display-table-slot
5356 org-display-table 4
5357 (vconcat (mapcar
5358 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5359 org-ellipsis)))
5360 (if (stringp org-ellipsis) org-ellipsis "..."))))
5361 (setq buffer-display-table org-display-table))
5362 (org-set-regexps-and-options-for-tags)
5363 (org-set-regexps-and-options)
5364 (org-set-font-lock-defaults)
5365 (when (and org-tag-faces (not org-tags-special-faces-re))
5366 ;; tag faces set outside customize.... force initialization.
5367 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5368 ;; Calc embedded
5369 (org-set-local 'calc-embedded-open-mode "# ")
5370 ;; Modify a few syntax entries
5371 (modify-syntax-entry ?@ "w")
5372 (modify-syntax-entry ?\" "\"")
5373 (modify-syntax-entry ?\\ "_")
5374 (modify-syntax-entry ?~ "_")
5375 (if org-startup-truncated (setq truncate-lines t))
5376 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5377 (org-set-local 'font-lock-unfontify-region-function
5378 'org-unfontify-region)
5379 ;; Activate before-change-function
5380 (org-set-local 'org-table-may-need-update t)
5381 (org-add-hook 'before-change-functions 'org-before-change-function nil
5382 'local)
5383 ;; Check for running clock before killing a buffer
5384 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5385 ;; Initialize macros templates.
5386 (org-macro-initialize-templates)
5387 ;; Initialize radio targets.
5388 (org-update-radio-target-regexp)
5389 ;; Indentation.
5390 (org-set-local 'indent-line-function 'org-indent-line)
5391 (org-set-local 'indent-region-function 'org-indent-region)
5392 ;; Filling and auto-filling.
5393 (org-setup-filling)
5394 ;; Comments.
5395 (org-setup-comments-handling)
5396 ;; Beginning/end of defun
5397 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5398 (org-set-local 'end-of-defun-function
5399 (lambda ()
5400 (if (not (org-at-heading-p))
5401 (org-forward-element)
5402 (org-forward-element)
5403 (forward-char -1))))
5404 ;; Next error for sparse trees
5405 (org-set-local 'next-error-function 'org-occur-next-match)
5406 ;; Make sure dependence stuff works reliably, even for users who set it
5407 ;; too late :-(
5408 (if org-enforce-todo-dependencies
5409 (add-hook 'org-blocker-hook
5410 'org-block-todo-from-children-or-siblings-or-parent)
5411 (remove-hook 'org-blocker-hook
5412 'org-block-todo-from-children-or-siblings-or-parent))
5413 (if org-enforce-todo-checkbox-dependencies
5414 (add-hook 'org-blocker-hook
5415 'org-block-todo-from-checkboxes)
5416 (remove-hook 'org-blocker-hook
5417 'org-block-todo-from-checkboxes))
5419 ;; Align options lines
5420 (org-set-local
5421 'align-mode-rules-list
5422 '((org-in-buffer-settings
5423 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5424 (modes . '(org-mode)))))
5426 ;; Imenu
5427 (org-set-local 'imenu-create-index-function
5428 'org-imenu-get-tree)
5430 ;; Make isearch reveal context
5431 (if (or (featurep 'xemacs)
5432 (not (boundp 'outline-isearch-open-invisible-function)))
5433 ;; Emacs 21 and XEmacs make use of the hook
5434 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5435 ;; Emacs 22 deals with this through a special variable
5436 (org-set-local 'outline-isearch-open-invisible-function
5437 (lambda (&rest ignore) (org-show-context 'isearch))))
5439 ;; Setup the pcomplete hooks
5440 (set (make-local-variable 'pcomplete-command-completion-function)
5441 'org-pcomplete-initial)
5442 (set (make-local-variable 'pcomplete-command-name-function)
5443 'org-command-at-point)
5444 (set (make-local-variable 'pcomplete-default-completion-function)
5445 'ignore)
5446 (set (make-local-variable 'pcomplete-parse-arguments-function)
5447 'org-parse-arguments)
5448 (set (make-local-variable 'pcomplete-termination-string) "")
5449 (when (>= emacs-major-version 23)
5450 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5452 ;; If empty file that did not turn on org-mode automatically, make it to.
5453 (if (and org-insert-mode-line-in-empty-file
5454 (org-called-interactively-p 'any)
5455 (= (point-min) (point-max)))
5456 (insert "# -*- mode: org -*-\n\n"))
5457 (unless org-inhibit-startup
5458 (org-unmodified
5459 (and org-startup-with-beamer-mode (org-beamer-mode))
5460 (when org-startup-align-all-tables
5461 (org-table-map-tables 'org-table-align 'quietly))
5462 (when org-startup-with-inline-images
5463 (org-display-inline-images))
5464 (when org-startup-with-latex-preview
5465 (org-preview-latex-fragment))
5466 (unless org-inhibit-startup-visibility-stuff
5467 (org-set-startup-visibility))))
5468 ;; Try to set org-hide correctly
5469 (let ((foreground (org-find-invisible-foreground)))
5470 (if foreground
5471 (set-face-foreground 'org-hide foreground))))
5473 ;; Update `customize-package-emacs-version-alist'
5474 (add-to-list 'customize-package-emacs-version-alist
5475 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5476 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5477 ("8.2.6" . "24.4")))
5479 (defvar org-mode-transpose-word-syntax-table
5480 (let ((st (make-syntax-table)))
5481 (mapc (lambda(c) (modify-syntax-entry
5482 (string-to-char (car c)) "w p" st))
5483 org-emphasis-alist)
5484 st))
5486 (when (fboundp 'abbrev-table-put)
5487 (abbrev-table-put org-mode-abbrev-table
5488 :parents (list text-mode-abbrev-table)))
5490 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5492 (defun org-find-invisible-foreground ()
5493 (let ((candidates (remove
5494 "unspecified-bg"
5495 (nconc
5496 (list (face-background 'default)
5497 (face-background 'org-default))
5498 (mapcar
5499 (lambda (alist)
5500 (when (boundp alist)
5501 (cdr (assoc 'background-color (symbol-value alist)))))
5502 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5503 (list (face-foreground 'org-hide))))))
5504 (car (remove nil candidates))))
5506 (defun org-current-time (&optional rounding-minutes past)
5507 "Current time, possibly rounded to ROUNDING-MINUTES.
5508 When ROUNDING-MINUTES is not an integer, fall back on the car of
5509 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5510 the rounding returns a past time."
5511 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5512 (car org-time-stamp-rounding-minutes)))
5513 (time (decode-time)) res)
5514 (if (< r 1)
5515 (current-time)
5516 (setq res
5517 (apply 'encode-time
5518 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5519 (nthcdr 2 time))))
5520 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5521 (seconds-to-time (- (float-time res) (* r 60)))
5522 res))))
5524 (defun org-today ()
5525 "Return today date, considering `org-extend-today-until'."
5526 (time-to-days
5527 (time-subtract (current-time)
5528 (list 0 (* 3600 org-extend-today-until) 0))))
5530 ;;;; Font-Lock stuff, including the activators
5532 (defvar org-mouse-map (make-sparse-keymap))
5533 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5534 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5535 (when org-mouse-1-follows-link
5536 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5537 (when org-tab-follows-link
5538 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5539 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5541 (require 'font-lock)
5543 (defconst org-non-link-chars "]\t\n\r<>")
5544 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5545 "shell" "elisp" "doi" "message"))
5546 (defvar org-link-types-re nil
5547 "Matches a link that has a url-like prefix like \"http:\"")
5548 (defvar org-link-re-with-space nil
5549 "Matches a link with spaces, optional angular brackets around it.")
5550 (defvar org-link-re-with-space2 nil
5551 "Matches a link with spaces, optional angular brackets around it.")
5552 (defvar org-link-re-with-space3 nil
5553 "Matches a link with spaces, only for internal part in bracket links.")
5554 (defvar org-angle-link-re nil
5555 "Matches link with angular brackets, spaces are allowed.")
5556 (defvar org-plain-link-re nil
5557 "Matches plain link, without spaces.")
5558 (defvar org-bracket-link-regexp nil
5559 "Matches a link in double brackets.")
5560 (defvar org-bracket-link-analytic-regexp nil
5561 "Regular expression used to analyze links.
5562 Here is what the match groups contain after a match:
5563 1: http:
5564 2: http
5565 3: path
5566 4: [desc]
5567 5: desc")
5568 (defvar org-bracket-link-analytic-regexp++ nil
5569 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5570 (defvar org-any-link-re nil
5571 "Regular expression matching any link.")
5573 (defconst org-match-sexp-depth 3
5574 "Number of stacked braces for sub/superscript matching.")
5576 (defun org-create-multibrace-regexp (left right n)
5577 "Create a regular expression which will match a balanced sexp.
5578 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5579 as single character strings.
5580 The regexp returned will match the entire expression including the
5581 delimiters. It will also define a single group which contains the
5582 match except for the outermost delimiters. The maximum depth of
5583 stacked delimiters is N. Escaping delimiters is not possible."
5584 (let* ((nothing (concat "[^" left right "]*?"))
5585 (or "\\|")
5586 (re nothing)
5587 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5588 (while (> n 1)
5589 (setq n (1- n)
5590 re (concat re or next)
5591 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5592 (concat left "\\(" re "\\)" right)))
5594 (defvar org-match-substring-regexp
5595 (concat
5596 "\\(\\S-\\)\\([_^]\\)\\("
5597 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5598 "\\|"
5599 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5600 "\\|"
5601 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5602 "The regular expression matching a sub- or superscript.")
5604 (defvar org-match-substring-with-braces-regexp
5605 (concat
5606 "\\(\\S-\\)\\([_^]\\)\\("
5607 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5608 "\\)")
5609 "The regular expression matching a sub- or superscript, forcing braces.")
5611 (defun org-make-link-regexps ()
5612 "Update the link regular expressions.
5613 This should be called after the variable `org-link-types' has changed."
5614 (let ((types-re (regexp-opt org-link-types t)))
5615 (setq org-link-types-re
5616 (concat "\\`" types-re ":")
5617 org-link-re-with-space
5618 (concat "<?" types-re ":"
5619 "\\([^" org-non-link-chars " ]"
5620 "[^" org-non-link-chars "]*"
5621 "[^" org-non-link-chars " ]\\)>?")
5622 org-link-re-with-space2
5623 (concat "<?" types-re ":"
5624 "\\([^" org-non-link-chars " ]"
5625 "[^\t\n\r]*"
5626 "[^" org-non-link-chars " ]\\)>?")
5627 org-link-re-with-space3
5628 (concat "<?" types-re ":"
5629 "\\([^" org-non-link-chars " ]"
5630 "[^\t\n\r]*\\)")
5631 org-angle-link-re
5632 (concat "<" types-re ":"
5633 "\\([^" org-non-link-chars " ]"
5634 "[^" org-non-link-chars "]*"
5635 "\\)>")
5636 org-plain-link-re
5637 (concat
5638 "\\<" types-re ":"
5639 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5640 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5641 org-bracket-link-regexp
5642 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5643 org-bracket-link-analytic-regexp
5644 (concat
5645 "\\[\\["
5646 "\\(" types-re ":\\)?"
5647 "\\([^]]+\\)"
5648 "\\]"
5649 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5650 "\\]")
5651 org-bracket-link-analytic-regexp++
5652 (concat
5653 "\\[\\["
5654 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5655 "\\([^]]+\\)"
5656 "\\]"
5657 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5658 "\\]")
5659 org-any-link-re
5660 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5661 org-angle-link-re "\\)\\|\\("
5662 org-plain-link-re "\\)"))))
5664 (org-make-link-regexps)
5666 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5667 "Regular expression for fast time stamp matching.")
5668 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5669 "Regular expression for fast time stamp matching.")
5670 (defconst org-ts-regexp0
5671 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5672 "Regular expression matching time strings for analysis.
5673 This one does not require the space after the date, so it can be used
5674 on a string that terminates immediately after the date.")
5675 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5676 "Regular expression matching time strings for analysis.")
5677 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5678 "Regular expression matching time stamps, with groups.")
5679 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5680 "Regular expression matching time stamps (also [..]), with groups.")
5681 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5682 "Regular expression matching a time stamp range.")
5683 (defconst org-tr-regexp-both
5684 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5685 "Regular expression matching a time stamp range.")
5686 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5687 org-ts-regexp "\\)?")
5688 "Regular expression matching a time stamp or time stamp range.")
5689 (defconst org-tsr-regexp-both
5690 (concat org-ts-regexp-both "\\(--?-?"
5691 org-ts-regexp-both "\\)?")
5692 "Regular expression matching a time stamp or time stamp range.
5693 The time stamps may be either active or inactive.")
5695 (defvar org-emph-face nil)
5697 (defun org-do-emphasis-faces (limit)
5698 "Run through the buffer and add overlays to emphasized strings."
5699 (let (rtn a)
5700 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5701 (let* ((border (char-after (match-beginning 3)))
5702 (bre (regexp-quote (char-to-string border))))
5703 (if (and (not (= border (char-after (match-beginning 4))))
5704 (not (save-match-data
5705 (string-match (concat bre ".*" bre)
5706 (replace-regexp-in-string
5707 "\n" " "
5708 (substring (match-string 2) 1 -1))))))
5709 (progn
5710 (setq rtn t)
5711 (setq a (assoc (match-string 3) org-emphasis-alist))
5712 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5713 'face
5714 (nth 1 a))
5715 (and (nth 2 a)
5716 (org-remove-flyspell-overlays-in
5717 (match-beginning 0) (match-end 0)))
5718 (add-text-properties (match-beginning 2) (match-end 2)
5719 '(font-lock-multiline t org-emphasis t))
5720 (when org-hide-emphasis-markers
5721 (add-text-properties (match-end 4) (match-beginning 5)
5722 '(invisible org-link))
5723 (add-text-properties (match-beginning 3) (match-end 3)
5724 '(invisible org-link))))))
5725 (goto-char (1+ (match-beginning 0))))
5726 rtn))
5728 (defun org-emphasize (&optional char)
5729 "Insert or change an emphasis, i.e. a font like bold or italic.
5730 If there is an active region, change that region to a new emphasis.
5731 If there is no region, just insert the marker characters and position
5732 the cursor between them.
5733 CHAR should be the marker character. If it is a space, it means to
5734 remove the emphasis of the selected region.
5735 If CHAR is not given (for example in an interactive call) it will be
5736 prompted for."
5737 (interactive)
5738 (let ((erc org-emphasis-regexp-components)
5739 (prompt "")
5740 (string "") beg end move c s)
5741 (if (org-region-active-p)
5742 (setq beg (region-beginning) end (region-end)
5743 string (buffer-substring beg end))
5744 (setq move t))
5746 (unless char
5747 (message "Emphasis marker or tag: [%s]"
5748 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5749 (setq char (read-char-exclusive)))
5750 (if (equal char ?\ )
5751 (setq s "" move nil)
5752 (unless (assoc (char-to-string char) org-emphasis-alist)
5753 (user-error "No such emphasis marker: \"%c\"" char))
5754 (setq s (char-to-string char)))
5755 (while (and (> (length string) 1)
5756 (equal (substring string 0 1) (substring string -1))
5757 (assoc (substring string 0 1) org-emphasis-alist))
5758 (setq string (substring string 1 -1)))
5759 (setq string (concat s string s))
5760 (if beg (delete-region beg end))
5761 (unless (or (bolp)
5762 (string-match (concat "[" (nth 0 erc) "\n]")
5763 (char-to-string (char-before (point)))))
5764 (insert " "))
5765 (unless (or (eobp)
5766 (string-match (concat "[" (nth 1 erc) "\n]")
5767 (char-to-string (char-after (point)))))
5768 (insert " ") (backward-char 1))
5769 (insert string)
5770 (and move (backward-char 1))))
5772 (defconst org-nonsticky-props
5773 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5775 (defsubst org-rear-nonsticky-at (pos)
5776 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5778 (defun org-activate-plain-links (limit)
5779 "Run through the buffer and add overlays to links."
5780 (let (f hl)
5781 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5782 (not (org-in-src-block-p)))
5783 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5784 (setq f (get-text-property (match-beginning 0) 'face))
5785 (setq hl (org-match-string-no-properties 0))
5786 (if (or (eq f 'org-tag)
5787 (and (listp f) (memq 'org-tag f)))
5789 (add-text-properties (match-beginning 0) (match-end 0)
5790 (list 'mouse-face 'highlight
5791 'face 'org-link
5792 'htmlize-link `(:uri ,hl)
5793 'keymap org-mouse-map))
5794 (org-rear-nonsticky-at (match-end 0)))
5795 t)))
5797 (defun org-activate-code (limit)
5798 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5799 (progn
5800 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5801 (remove-text-properties (match-beginning 0) (match-end 0)
5802 '(display t invisible t intangible t))
5803 t)))
5805 (defcustom org-src-fontify-natively nil
5806 "When non-nil, fontify code in code blocks."
5807 :type 'boolean
5808 :version "24.1"
5809 :group 'org-appearance
5810 :group 'org-babel)
5812 (defcustom org-allow-promoting-top-level-subtree nil
5813 "When non-nil, allow promoting a top level subtree.
5814 The leading star of the top level headline will be replaced
5815 by a #."
5816 :type 'boolean
5817 :version "24.1"
5818 :group 'org-appearance)
5820 (defun org-fontify-meta-lines-and-blocks (limit)
5821 (condition-case nil
5822 (org-fontify-meta-lines-and-blocks-1 limit)
5823 (error (message "org-mode fontification error"))))
5825 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5826 "Fontify #+ lines and blocks."
5827 (let ((case-fold-search t))
5828 (if (re-search-forward
5829 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5830 limit t)
5831 (let ((beg (match-beginning 0))
5832 (block-start (match-end 0))
5833 (block-end nil)
5834 (lang (match-string 7))
5835 (beg1 (line-beginning-position 2))
5836 (dc1 (downcase (match-string 2)))
5837 (dc3 (downcase (match-string 3)))
5838 end end1 quoting block-type ovl)
5839 (cond
5840 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5841 ;; a single line of backend-specific content
5842 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5843 (remove-text-properties (match-beginning 0) (match-end 0)
5844 '(display t invisible t intangible t))
5845 (add-text-properties (match-beginning 1) (match-end 3)
5846 '(font-lock-fontified t face org-meta-line))
5847 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5848 '(font-lock-fontified t face org-block))
5849 ; for backend-specific code
5851 ((and (match-end 4) (equal dc3 "+begin"))
5852 ;; Truly a block
5853 (setq block-type (downcase (match-string 5))
5854 quoting (member block-type org-protecting-blocks))
5855 (when (re-search-forward
5856 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5857 nil t) ;; on purpose, we look further than LIMIT
5858 (setq end (min (point-max) (match-end 0))
5859 end1 (min (point-max) (1- (match-beginning 0))))
5860 (setq block-end (match-beginning 0))
5861 (when quoting
5862 (remove-text-properties beg end
5863 '(display t invisible t intangible t)))
5864 (add-text-properties
5865 beg end
5866 '(font-lock-fontified t font-lock-multiline t))
5867 (add-text-properties beg beg1 '(face org-meta-line))
5868 (add-text-properties end1 (min (point-max) (1+ end))
5869 '(face org-meta-line)) ; for end_src
5870 (cond
5871 ((and lang (not (string= lang "")) org-src-fontify-natively)
5872 (org-src-font-lock-fontify-block lang block-start block-end)
5873 ;; remove old background overlays
5874 (mapc (lambda (ov)
5875 (if (eq (overlay-get ov 'face) 'org-block-background)
5876 (delete-overlay ov)))
5877 (overlays-at (/ (+ beg1 block-end) 2)))
5878 ;; add a background overlay
5879 (setq ovl (make-overlay beg1 block-end))
5880 (overlay-put ovl 'face 'org-block-background)
5881 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5882 (quoting
5883 (add-text-properties beg1 (min (point-max) (1+ end1))
5884 '(face org-block))) ; end of source block
5885 ((not org-fontify-quote-and-verse-blocks))
5886 ((string= block-type "quote")
5887 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5888 ((string= block-type "verse")
5889 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5890 (add-text-properties beg beg1 '(face org-block-begin-line))
5891 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5892 '(face org-block-end-line))
5894 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5895 (add-text-properties
5896 beg (match-end 3)
5897 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5898 '(font-lock-fontified t invisible t)
5899 '(font-lock-fontified t face org-document-info-keyword)))
5900 (add-text-properties
5901 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5902 (if (string-equal dc1 "+title:")
5903 '(font-lock-fontified t face org-document-title)
5904 '(font-lock-fontified t face org-document-info))))
5905 ((or (equal dc1 "+results")
5906 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5907 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5908 "+call:" "+header:" "+headers:" "+name:"))
5909 (and (match-end 4) (equal dc3 "+attr")))
5910 (add-text-properties
5911 beg (match-end 0)
5912 '(font-lock-fontified t face org-meta-line))
5914 ((member dc3 '(" " ""))
5915 (add-text-properties
5916 beg (match-end 0)
5917 '(font-lock-fontified t face font-lock-comment-face)))
5918 ((not (member (char-after beg) '(?\ ?\t)))
5919 ;; just any other in-buffer setting, but not indented
5920 (add-text-properties
5921 beg (match-end 0)
5922 '(font-lock-fontified t face org-meta-line))
5924 (t nil))))))
5926 (defun org-activate-angle-links (limit)
5927 "Run through the buffer and add overlays to links."
5928 (if (and (re-search-forward org-angle-link-re limit t)
5929 (not (org-in-src-block-p)))
5930 (progn
5931 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5932 (add-text-properties (match-beginning 0) (match-end 0)
5933 (list 'mouse-face 'highlight
5934 'keymap org-mouse-map))
5935 (org-rear-nonsticky-at (match-end 0))
5936 t)))
5938 (defun org-activate-footnote-links (limit)
5939 "Run through the buffer and add overlays to footnotes."
5940 (let ((fn (org-footnote-next-reference-or-definition limit)))
5941 (when fn
5942 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5943 (org-remove-flyspell-overlays-in beg end)
5944 (add-text-properties beg end
5945 (list 'mouse-face 'highlight
5946 'keymap org-mouse-map
5947 'help-echo
5948 (if (= (point-at-bol) beg)
5949 "Footnote definition"
5950 "Footnote reference")
5951 'font-lock-fontified t
5952 'font-lock-multiline t
5953 'face 'org-footnote))))))
5955 (defun org-activate-bracket-links (limit)
5956 "Run through the buffer and add overlays to bracketed links."
5957 (if (and (re-search-forward org-bracket-link-regexp limit t)
5958 (not (org-in-src-block-p)))
5959 (let* ((hl (org-match-string-no-properties 1))
5960 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5961 (ip (org-maybe-intangible
5962 (list 'invisible 'org-link
5963 'keymap org-mouse-map 'mouse-face 'highlight
5964 'font-lock-multiline t 'help-echo help
5965 'htmlize-link `(:uri ,hl))))
5966 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5967 'font-lock-multiline t 'help-echo help
5968 'htmlize-link `(:uri ,hl))))
5969 ;; We need to remove the invisible property here. Table narrowing
5970 ;; may have made some of this invisible.
5971 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5972 (remove-text-properties (match-beginning 0) (match-end 0)
5973 '(invisible nil))
5974 (if (match-end 3)
5975 (progn
5976 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5977 (org-rear-nonsticky-at (match-beginning 3))
5978 (add-text-properties (match-beginning 3) (match-end 3) vp)
5979 (org-rear-nonsticky-at (match-end 3))
5980 (add-text-properties (match-end 3) (match-end 0) ip)
5981 (org-rear-nonsticky-at (match-end 0)))
5982 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5983 (org-rear-nonsticky-at (match-beginning 1))
5984 (add-text-properties (match-beginning 1) (match-end 1) vp)
5985 (org-rear-nonsticky-at (match-end 1))
5986 (add-text-properties (match-end 1) (match-end 0) ip)
5987 (org-rear-nonsticky-at (match-end 0)))
5988 t)))
5990 (defun org-activate-dates (limit)
5991 "Run through the buffer and add overlays to dates."
5992 (if (and (re-search-forward org-tsr-regexp-both limit t)
5993 (not (equal (char-before (match-beginning 0)) 91)))
5994 (progn
5995 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5996 (add-text-properties (match-beginning 0) (match-end 0)
5997 (list 'mouse-face 'highlight
5998 'keymap org-mouse-map))
5999 (org-rear-nonsticky-at (match-end 0))
6000 (when org-display-custom-times
6001 (if (match-end 3)
6002 (org-display-custom-time (match-beginning 3) (match-end 3)))
6003 (org-display-custom-time (match-beginning 1) (match-end 1)))
6004 t)))
6006 (defvar org-target-link-regexp nil
6007 "Regular expression matching radio targets in plain text.")
6008 (make-variable-buffer-local 'org-target-link-regexp)
6009 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6010 "Regular expression matching a link target.")
6011 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6012 "Regular expression matching a radio target.")
6013 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6014 "Regular expression matching any target.")
6016 (defun org-activate-target-links (limit)
6017 "Run through the buffer and add overlays to target matches."
6018 (when org-target-link-regexp
6019 (let ((case-fold-search t))
6020 (if (re-search-forward org-target-link-regexp limit t)
6021 (progn
6022 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6023 (add-text-properties (match-beginning 0) (match-end 0)
6024 (list 'mouse-face 'highlight
6025 'keymap org-mouse-map
6026 'help-echo "Radio target link"
6027 'org-linked-text t))
6028 (org-rear-nonsticky-at (match-end 0))
6029 t)))))
6031 (defun org-update-radio-target-regexp ()
6032 "Find all radio targets in this file and update the regular expression."
6033 (interactive)
6034 (when (memq 'radio org-activate-links)
6035 (setq org-target-link-regexp
6036 (org-make-target-link-regexp (org-all-targets 'radio)))
6037 (org-restart-font-lock)))
6039 (defun org-hide-wide-columns (limit)
6040 (let (s e)
6041 (setq s (text-property-any (point) (or limit (point-max))
6042 'org-cwidth t))
6043 (when s
6044 (setq e (next-single-property-change s 'org-cwidth))
6045 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6046 (goto-char e)
6047 t)))
6049 (defvar org-latex-and-related-regexp nil
6050 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6051 (defvar org-match-substring-regexp)
6052 (defvar org-match-substring-with-braces-regexp)
6054 (defun org-compute-latex-and-related-regexp ()
6055 "Compute regular expression for LaTeX, entities and sub/superscript.
6056 Result depends on variable `org-highlight-latex-and-related'."
6057 (org-set-local
6058 'org-latex-and-related-regexp
6059 (let* ((re-sub
6060 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6061 ((eq org-use-sub-superscripts '{})
6062 (list org-match-substring-with-braces-regexp))
6063 (org-use-sub-superscripts (list org-match-substring-regexp))))
6064 (re-latex
6065 (when (memq 'latex org-highlight-latex-and-related)
6066 (let ((matchers (plist-get org-format-latex-options :matchers)))
6067 (delq nil
6068 (mapcar (lambda (x)
6069 (and (member (car x) matchers) (nth 1 x)))
6070 org-latex-regexps)))))
6071 (re-entities
6072 (when (memq 'entities org-highlight-latex-and-related)
6073 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6074 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6076 (defun org-do-latex-and-related (limit)
6077 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6078 LIMIT bounds the search for syntax to highlight. Stop at first
6079 highlighted object, if any. Return t if some highlighting was
6080 done, nil otherwise."
6081 (when (org-string-nw-p org-latex-and-related-regexp)
6082 (catch 'found
6083 (while (re-search-forward org-latex-and-related-regexp limit t)
6084 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6085 'face))
6086 '(org-code org-verbatim underline))
6087 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6088 '(?_ ?^))
6090 0)))
6091 (font-lock-prepend-text-property
6092 (+ offset (match-beginning 0)) (match-end 0)
6093 'face 'org-latex-and-related)
6094 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6095 '(font-lock-multiline t)))
6096 (throw 'found t)))
6097 nil)))
6099 (defun org-restart-font-lock ()
6100 "Restart `font-lock-mode', to force refontification."
6101 (when (and (boundp 'font-lock-mode) font-lock-mode)
6102 (font-lock-mode -1)
6103 (font-lock-mode 1)))
6105 (defun org-all-targets (&optional radio)
6106 "Return a list of all targets in this file.
6107 When optional argument RADIO is non-nil, only find radio
6108 targets."
6109 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6110 (save-excursion
6111 (goto-char (point-min))
6112 (while (re-search-forward re nil t)
6113 ;; Make sure point is really within the object.
6114 (backward-char)
6115 (let ((obj (org-element-context)))
6116 (when (memq (org-element-type obj) '(radio-target target))
6117 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6118 rtn)))
6120 (defun org-make-target-link-regexp (targets)
6121 "Make regular expression matching all strings in TARGETS.
6122 The regular expression finds the targets also if there is a line break
6123 between words."
6124 (and targets
6125 (concat
6126 "\\_<\\("
6127 (mapconcat
6128 (lambda (x)
6129 (setq x (regexp-quote x))
6130 (while (string-match " +" x)
6131 (setq x (replace-match "\\s-+" t t x)))
6133 targets
6134 "\\|")
6135 "\\)\\_>")))
6137 (defun org-activate-tags (limit)
6138 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6139 (progn
6140 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6141 (add-text-properties (match-beginning 1) (match-end 1)
6142 (list 'mouse-face 'highlight
6143 'keymap org-mouse-map))
6144 (org-rear-nonsticky-at (match-end 1))
6145 t)))
6147 (defun org-outline-level ()
6148 "Compute the outline level of the heading at point.
6149 If this is called at a normal headline, the level is the number of stars.
6150 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6151 (save-excursion
6152 (if (not (condition-case nil
6153 (org-back-to-heading t)
6154 (error nil)))
6156 (looking-at org-outline-regexp)
6157 (1- (- (match-end 0) (match-beginning 0))))))
6159 (defvar org-font-lock-keywords nil)
6161 (defsubst org-re-property (property &optional literal allow-null)
6162 "Return a regexp matching a PROPERTY line.
6164 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6165 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6166 non-nil, match properties even without a value.
6168 Match group 3 is set to the value when it exists. If there is no
6169 value and ALLOW-NULL is non-nil, it is set to the empty string."
6170 (concat
6171 "^\\(?4:[ \t]*\\)"
6172 (format "\\(?1::\\(?2:%s\\):\\)"
6173 (if literal property (regexp-quote property)))
6174 (if allow-null
6175 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$"
6176 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$")))
6178 (defconst org-property-re
6179 (org-re-property ".*?" 'literal t)
6180 "Regular expression matching a property line.
6181 There are four matching groups:
6182 1: :PROPKEY: including the leading and trailing colon,
6183 2: PROPKEY without the leading and trailing colon,
6184 3: PROPVAL without leading or trailing spaces,
6185 4: the indentation of the current line,
6186 5: trailing whitespace.")
6188 (defvar org-font-lock-hook nil
6189 "Functions to be called for special font lock stuff.")
6191 (defvar org-font-lock-set-keywords-hook nil
6192 "Functions that can manipulate `org-font-lock-extra-keywords'.
6193 This is called after `org-font-lock-extra-keywords' is defined, but before
6194 it is installed to be used by font lock. This can be useful if something
6195 needs to be inserted at a specific position in the font-lock sequence.")
6197 (defun org-font-lock-hook (limit)
6198 "Run `org-font-lock-hook' within LIMIT."
6199 (run-hook-with-args 'org-font-lock-hook limit))
6201 (defun org-set-font-lock-defaults ()
6202 "Set font lock defaults for the current buffer."
6203 (let* ((em org-fontify-emphasized-text)
6204 (lk org-activate-links)
6205 (org-font-lock-extra-keywords
6206 (list
6207 ;; Call the hook
6208 '(org-font-lock-hook)
6209 ;; Headlines
6210 `(,(if org-fontify-whole-heading-line
6211 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6212 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6213 (1 (org-get-level-face 1))
6214 (2 (org-get-level-face 2))
6215 (3 (org-get-level-face 3)))
6216 ;; Table lines
6217 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6218 (1 'org-table t))
6219 ;; Table internals
6220 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6221 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6222 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6223 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6224 ;; Drawers
6225 (list org-drawer-regexp '(0 'org-special-keyword t))
6226 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6227 ;; Properties
6228 (list org-property-re
6229 '(1 'org-special-keyword t)
6230 '(3 'org-property-value t))
6231 ;; Links
6232 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6233 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6234 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6235 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6236 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6237 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6238 (if (memq 'footnote lk) '(org-activate-footnote-links))
6239 ;; Targets.
6240 (list org-any-target-regexp '(0 'org-target t))
6241 ;; Diary sexps.
6242 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6243 ;; Macro
6244 '("{{{.+}}}" (0 'org-macro t))
6245 '(org-hide-wide-columns (0 nil append))
6246 ;; TODO keyword
6247 (list (format org-heading-keyword-regexp-format
6248 org-todo-regexp)
6249 '(2 (org-get-todo-face 2) t))
6250 ;; DONE
6251 (if org-fontify-done-headline
6252 (list (format org-heading-keyword-regexp-format
6253 (concat
6254 "\\(?:"
6255 (mapconcat 'regexp-quote org-done-keywords "\\|")
6256 "\\)"))
6257 '(2 'org-headline-done t))
6258 nil)
6259 ;; Priorities
6260 '(org-font-lock-add-priority-faces)
6261 ;; Tags
6262 '(org-font-lock-add-tag-faces)
6263 ;; Tags groups
6264 (if (and org-group-tags org-tag-groups-alist)
6265 (list (concat org-outline-regexp-bol ".+\\(:"
6266 (regexp-opt (mapcar 'car org-tag-groups-alist))
6267 ":\\).*$")
6268 '(1 'org-tag-group prepend)))
6269 ;; Special keywords
6270 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6271 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6272 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6273 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6274 ;; Emphasis
6275 (if em
6276 (if (featurep 'xemacs)
6277 '(org-do-emphasis-faces (0 nil append))
6278 '(org-do-emphasis-faces)))
6279 ;; Checkboxes
6280 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6281 1 'org-checkbox prepend)
6282 (if (cdr (assq 'checkbox org-list-automatic-rules))
6283 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6284 (0 (org-get-checkbox-statistics-face) t)))
6285 ;; Description list items
6286 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6287 1 'org-list-dt prepend)
6288 ;; ARCHIVEd headings
6289 (list (concat
6290 org-outline-regexp-bol
6291 "\\(.*:" org-archive-tag ":.*\\)")
6292 '(1 'org-archived prepend))
6293 ;; Specials
6294 '(org-do-latex-and-related)
6295 '(org-fontify-entities)
6296 '(org-raise-scripts)
6297 ;; Code
6298 '(org-activate-code (1 'org-code t))
6299 ;; COMMENT
6300 (list (format org-heading-keyword-regexp-format
6301 (concat "\\("
6302 org-comment-string "\\|" org-quote-string
6303 "\\)"))
6304 '(2 'org-special-keyword t))
6305 ;; Blocks and meta lines
6306 '(org-fontify-meta-lines-and-blocks))))
6307 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6308 (run-hooks 'org-font-lock-set-keywords-hook)
6309 ;; Now set the full font-lock-keywords
6310 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6311 (org-set-local 'font-lock-defaults
6312 '(org-font-lock-keywords t nil nil backward-paragraph))
6313 (kill-local-variable 'font-lock-keywords) nil))
6315 (defun org-toggle-pretty-entities ()
6316 "Toggle the composition display of entities as UTF8 characters."
6317 (interactive)
6318 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6319 (org-restart-font-lock)
6320 (if org-pretty-entities
6321 (message "Entities are now displayed as UTF8 characters")
6322 (save-restriction
6323 (widen)
6324 (org-decompose-region (point-min) (point-max))
6325 (message "Entities are now displayed as plain text"))))
6327 (defvar org-custom-properties-overlays nil
6328 "List of overlays used for custom properties.")
6329 (make-variable-buffer-local 'org-custom-properties-overlays)
6331 (defun org-toggle-custom-properties-visibility ()
6332 "Display or hide properties in `org-custom-properties'."
6333 (interactive)
6334 (if org-custom-properties-overlays
6335 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6336 (setq org-custom-properties-overlays nil))
6337 (unless (not org-custom-properties)
6338 (save-excursion
6339 (save-restriction
6340 (widen)
6341 (goto-char (point-min))
6342 (while (re-search-forward org-property-re nil t)
6343 (mapc (lambda(p)
6344 (when (equal p (substring (match-string 1) 1 -1))
6345 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6346 (overlay-put o 'invisible t)
6347 (overlay-put o 'org-custom-property t)
6348 (push o org-custom-properties-overlays))))
6349 org-custom-properties)))))))
6351 (defun org-fontify-entities (limit)
6352 "Find an entity to fontify."
6353 (let (ee)
6354 (when org-pretty-entities
6355 (catch 'match
6356 (while (re-search-forward
6357 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6358 limit t)
6359 (if (and (not (org-in-indented-comment-line))
6360 (setq ee (org-entity-get (match-string 1)))
6361 (= (length (nth 6 ee)) 1))
6362 (let*
6363 ((end (if (equal (match-string 2) "{}")
6364 (match-end 2)
6365 (match-end 1))))
6366 (add-text-properties
6367 (match-beginning 0) end
6368 (list 'font-lock-fontified t))
6369 (compose-region (match-beginning 0) end
6370 (nth 6 ee) nil)
6371 (backward-char 1)
6372 (throw 'match t))))
6373 nil))))
6375 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6376 "Fontify string S like in Org-mode."
6377 (with-temp-buffer
6378 (insert s)
6379 (let ((org-odd-levels-only odd-levels))
6380 (org-mode)
6381 (org-font-lock-ensure)
6382 (buffer-string))))
6384 (defvar org-m nil)
6385 (defvar org-l nil)
6386 (defvar org-f nil)
6387 (defun org-get-level-face (n)
6388 "Get the right face for match N in font-lock matching of headlines."
6389 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6390 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6391 (if org-cycle-level-faces
6392 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6393 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6394 (cond
6395 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6396 ((eq n 2) org-f)
6397 (t (if org-level-color-stars-only nil org-f))))
6400 (defun org-get-todo-face (kwd)
6401 "Get the right face for a TODO keyword KWD.
6402 If KWD is a number, get the corresponding match group."
6403 (if (numberp kwd) (setq kwd (match-string kwd)))
6404 (or (org-face-from-face-or-color
6405 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6406 (and (member kwd org-done-keywords) 'org-done)
6407 'org-todo))
6409 (defun org-face-from-face-or-color (context inherit face-or-color)
6410 "Create a face list that inherits INHERIT, but sets the foreground color.
6411 When FACE-OR-COLOR is not a string, just return it."
6412 (if (stringp face-or-color)
6413 (list :inherit inherit
6414 (cdr (assoc context org-faces-easy-properties))
6415 face-or-color)
6416 face-or-color))
6418 (defun org-font-lock-add-tag-faces (limit)
6419 "Add the special tag faces."
6420 (when (and org-tag-faces org-tags-special-faces-re)
6421 (while (re-search-forward org-tags-special-faces-re limit t)
6422 (add-text-properties (match-beginning 1) (match-end 1)
6423 (list 'face (org-get-tag-face 1)
6424 'font-lock-fontified t))
6425 (backward-char 1))))
6427 (defun org-font-lock-add-priority-faces (limit)
6428 "Add the special priority faces."
6429 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6430 (when (save-match-data (org-at-heading-p))
6431 (add-text-properties
6432 (match-beginning 0) (match-end 0)
6433 (list 'face (or (org-face-from-face-or-color
6434 'priority 'org-priority
6435 (cdr (assoc (char-after (match-beginning 1))
6436 org-priority-faces)))
6437 'org-priority)
6438 'font-lock-fontified t)))))
6440 (defun org-get-tag-face (kwd)
6441 "Get the right face for a TODO keyword KWD.
6442 If KWD is a number, get the corresponding match group."
6443 (if (numberp kwd) (setq kwd (match-string kwd)))
6444 (or (org-face-from-face-or-color
6445 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6446 'org-tag))
6448 (defun org-unfontify-region (beg end &optional maybe_loudly)
6449 "Remove fontification and activation overlays from links."
6450 (font-lock-default-unfontify-region beg end)
6451 (let* ((buffer-undo-list t)
6452 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6453 (inhibit-modification-hooks t)
6454 deactivate-mark buffer-file-name buffer-file-truename)
6455 (org-decompose-region beg end)
6456 (remove-text-properties beg end
6457 '(mouse-face t keymap t org-linked-text t
6458 invisible t intangible t
6459 org-no-flyspell t org-emphasis t))
6460 (org-remove-font-lock-display-properties beg end)))
6462 (defconst org-script-display '(((raise -0.3) (height 0.7))
6463 ((raise 0.3) (height 0.7))
6464 ((raise -0.5))
6465 ((raise 0.5)))
6466 "Display properties for showing superscripts and subscripts.")
6468 (defun org-remove-font-lock-display-properties (beg end)
6469 "Remove specific display properties that have been added by font lock.
6470 The will remove the raise properties that are used to show superscripts
6471 and subscripts."
6472 (let (next prop)
6473 (while (< beg end)
6474 (setq next (next-single-property-change beg 'display nil end)
6475 prop (get-text-property beg 'display))
6476 (if (member prop org-script-display)
6477 (put-text-property beg next 'display nil))
6478 (setq beg next))))
6480 (defun org-raise-scripts (limit)
6481 "Add raise properties to sub/superscripts."
6482 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6483 (if (re-search-forward
6484 (if (eq org-use-sub-superscripts t)
6485 org-match-substring-regexp
6486 org-match-substring-with-braces-regexp)
6487 limit t)
6488 (let* ((pos (point)) table-p comment-p
6489 (mpos (match-beginning 3))
6490 (emph-p (get-text-property mpos 'org-emphasis))
6491 (link-p (get-text-property mpos 'mouse-face))
6492 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6493 (goto-char (point-at-bol))
6494 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6495 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6496 (goto-char pos)
6497 ;; Handle a_b^c
6498 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6499 (if (or comment-p emph-p link-p keyw-p)
6501 (put-text-property (match-beginning 3) (match-end 0)
6502 'display
6503 (if (equal (char-after (match-beginning 2)) ?^)
6504 (nth (if table-p 3 1) org-script-display)
6505 (nth (if table-p 2 0) org-script-display)))
6506 (add-text-properties (match-beginning 2) (match-end 2)
6507 (list 'invisible t
6508 'org-dwidth t 'org-dwidth-n 1))
6509 (if (and (eq (char-after (match-beginning 3)) ?{)
6510 (eq (char-before (match-end 3)) ?}))
6511 (progn
6512 (add-text-properties
6513 (match-beginning 3) (1+ (match-beginning 3))
6514 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6515 (add-text-properties
6516 (1- (match-end 3)) (match-end 3)
6517 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6518 t)))))
6520 ;;;; Visibility cycling, including org-goto and indirect buffer
6522 ;;; Cycling
6524 (defvar org-cycle-global-status nil)
6525 (make-variable-buffer-local 'org-cycle-global-status)
6526 (put 'org-cycle-global-status 'org-state t)
6527 (defvar org-cycle-subtree-status nil)
6528 (make-variable-buffer-local 'org-cycle-subtree-status)
6529 (put 'org-cycle-subtree-status 'org-state t)
6531 (defvar org-inlinetask-min-level)
6533 (defun org-unlogged-message (&rest args)
6534 "Display a message, but avoid logging it in the *Messages* buffer."
6535 (let ((message-log-max nil))
6536 (apply 'message args)))
6538 ;;;###autoload
6539 (defun org-cycle (&optional arg)
6540 "TAB-action and visibility cycling for Org-mode.
6542 This is the command invoked in Org-mode by the TAB key. Its main purpose
6543 is outline visibility cycling, but it also invokes other actions
6544 in special contexts.
6546 - When this function is called with a prefix argument, rotate the entire
6547 buffer through 3 states (global cycling)
6548 1. OVERVIEW: Show only top-level headlines.
6549 2. CONTENTS: Show all headlines of all levels, but no body text.
6550 3. SHOW ALL: Show everything.
6551 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6552 determined by the variable `org-startup-folded', and by any VISIBILITY
6553 properties in the buffer.
6554 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6555 including any drawers.
6557 - When inside a table, re-align the table and move to the next field.
6559 - When point is at the beginning of a headline, rotate the subtree started
6560 by this line through 3 different states (local cycling)
6561 1. FOLDED: Only the main headline is shown.
6562 2. CHILDREN: The main headline and the direct children are shown.
6563 From this state, you can move to one of the children
6564 and zoom in further.
6565 3. SUBTREE: Show the entire subtree, including body text.
6566 If there is no subtree, switch directly from CHILDREN to FOLDED.
6568 - When point is at the beginning of an empty headline and the variable
6569 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6570 of the headline by demoting and promoting it to likely levels. This
6571 speeds up creation document structure by pressing TAB once or several
6572 times right after creating a new headline.
6574 - When there is a numeric prefix, go up to a heading with level ARG, do
6575 a `show-subtree' and return to the previous cursor position. If ARG
6576 is negative, go up that many levels.
6578 - When point is not at the beginning of a headline, execute the global
6579 binding for TAB, which is re-indenting the line. See the option
6580 `org-cycle-emulate-tab' for details.
6582 - Special case: if point is at the beginning of the buffer and there is
6583 no headline in line 1, this function will act as if called with prefix arg
6584 (C-u TAB, same as S-TAB) also when called without prefix arg.
6585 But only if also the variable `org-cycle-global-at-bob' is t."
6586 (interactive "P")
6587 (org-load-modules-maybe)
6588 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6589 (and org-cycle-level-after-item/entry-creation
6590 (or (org-cycle-level)
6591 (org-cycle-item-indentation))))
6592 (let* ((limit-level
6593 (or org-cycle-max-level
6594 (and (boundp 'org-inlinetask-min-level)
6595 org-inlinetask-min-level
6596 (1- org-inlinetask-min-level))))
6597 (nstars (and limit-level
6598 (if org-odd-levels-only
6599 (and limit-level (1- (* limit-level 2)))
6600 limit-level)))
6601 (org-outline-regexp
6602 (if (not (derived-mode-p 'org-mode))
6603 outline-regexp
6604 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6605 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6606 (not (looking-at org-outline-regexp))))
6607 (org-cycle-hook
6608 (if bob-special
6609 (delq 'org-optimize-window-after-visibility-change
6610 (copy-sequence org-cycle-hook))
6611 org-cycle-hook))
6612 (pos (point)))
6614 (if (or bob-special (equal arg '(4)))
6615 ;; special case: use global cycling
6616 (setq arg t))
6618 (cond
6620 ((equal arg '(16))
6621 (setq last-command 'dummy)
6622 (org-set-startup-visibility)
6623 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6625 ((equal arg '(64))
6626 (show-all)
6627 (org-unlogged-message "Entire buffer visible, including drawers"))
6629 ;; Try cdlatex TAB completion
6630 ((org-try-cdlatex-tab))
6632 ;; Table: enter it or move to the next field.
6633 ((org-at-table-p 'any)
6634 (if (org-at-table.el-p)
6635 (message "%s" "Use C-c ' to edit table.el tables")
6636 (if arg (org-table-edit-field t)
6637 (org-table-justify-field-maybe)
6638 (call-interactively 'org-table-next-field))))
6640 ((run-hook-with-args-until-success
6641 'org-tab-after-check-for-table-hook))
6643 ;; Global cycling: delegate to `org-cycle-internal-global'.
6644 ((eq arg t) (org-cycle-internal-global))
6646 ;; Drawers: delegate to `org-flag-drawer'.
6647 ((and org-drawers org-drawer-regexp
6648 (save-excursion
6649 (beginning-of-line 1)
6650 (looking-at org-drawer-regexp)))
6651 (org-flag-drawer ; toggle block visibility
6652 (not (get-char-property (match-end 0) 'invisible))))
6654 ;; Show-subtree, ARG levels up from here.
6655 ((integerp arg)
6656 (save-excursion
6657 (org-back-to-heading)
6658 (outline-up-heading (if (< arg 0) (- arg)
6659 (- (funcall outline-level) arg)))
6660 (org-show-subtree)))
6662 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6663 ((and (featurep 'org-inlinetask)
6664 (org-inlinetask-at-task-p)
6665 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6666 (org-inlinetask-toggle-visibility))
6668 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6669 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6670 (save-excursion (beginning-of-line 1)
6671 (looking-at org-outline-regexp)))
6672 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6673 (org-cycle-internal-local))
6675 ;; From there: TAB emulation and template completion.
6676 (buffer-read-only (org-back-to-heading))
6678 ((run-hook-with-args-until-success
6679 'org-tab-after-check-for-cycling-hook))
6681 ((org-try-structure-completion))
6683 ((run-hook-with-args-until-success
6684 'org-tab-before-tab-emulation-hook))
6686 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6687 (or (not (bolp))
6688 (not (looking-at org-outline-regexp))))
6689 (call-interactively (global-key-binding "\t")))
6691 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6692 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6693 (or (and (eq org-cycle-emulate-tab 'white)
6694 (= (match-end 0) (point-at-eol)))
6695 (and (eq org-cycle-emulate-tab 'whitestart)
6696 (>= (match-end 0) pos))))
6698 (eq org-cycle-emulate-tab t))
6699 (call-interactively (global-key-binding "\t")))
6701 (t (save-excursion
6702 (org-back-to-heading)
6703 (org-cycle)))))))
6705 (defun org-cycle-internal-global ()
6706 "Do the global cycling action."
6707 ;; Hack to avoid display of messages for .org attachments in Gnus
6708 (let ((ga (string-match "\\*fontification" (buffer-name))))
6709 (cond
6710 ((and (eq last-command this-command)
6711 (eq org-cycle-global-status 'overview))
6712 ;; We just created the overview - now do table of contents
6713 ;; This can be slow in very large buffers, so indicate action
6714 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6715 (unless ga (org-unlogged-message "CONTENTS..."))
6716 (org-content)
6717 (unless ga (org-unlogged-message "CONTENTS...done"))
6718 (setq org-cycle-global-status 'contents)
6719 (run-hook-with-args 'org-cycle-hook 'contents))
6721 ((and (eq last-command this-command)
6722 (eq org-cycle-global-status 'contents))
6723 ;; We just showed the table of contents - now show everything
6724 (run-hook-with-args 'org-pre-cycle-hook 'all)
6725 (show-all)
6726 (unless ga (org-unlogged-message "SHOW ALL"))
6727 (setq org-cycle-global-status 'all)
6728 (run-hook-with-args 'org-cycle-hook 'all))
6731 ;; Default action: go to overview
6732 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6733 (org-overview)
6734 (unless ga (org-unlogged-message "OVERVIEW"))
6735 (setq org-cycle-global-status 'overview)
6736 (run-hook-with-args 'org-cycle-hook 'overview)))))
6738 (defvar org-called-with-limited-levels nil
6739 "Non-nil when `org-with-limited-levels' is currently active.")
6741 (defun org-cycle-internal-local ()
6742 "Do the local cycling action."
6743 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6744 ;; First, determine end of headline (EOH), end of subtree or item
6745 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6746 (save-excursion
6747 (if (org-at-item-p)
6748 (progn
6749 (beginning-of-line)
6750 (setq struct (org-list-struct))
6751 (setq eoh (point-at-eol))
6752 (setq eos (org-list-get-item-end-before-blank (point) struct))
6753 (setq has-children (org-list-has-child-p (point) struct)))
6754 (org-back-to-heading)
6755 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6756 (setq eos (save-excursion (org-end-of-subtree t t)
6757 (when (bolp) (backward-char)) (point)))
6758 (setq has-children
6759 (or (save-excursion
6760 (let ((level (funcall outline-level)))
6761 (outline-next-heading)
6762 (and (org-at-heading-p t)
6763 (> (funcall outline-level) level))))
6764 (save-excursion
6765 (org-list-search-forward (org-item-beginning-re) eos t)))))
6766 ;; Determine end invisible part of buffer (EOL)
6767 (beginning-of-line 2)
6768 ;; XEmacs doesn't have `next-single-char-property-change'
6769 (if (featurep 'xemacs)
6770 (while (and (not (eobp)) ;; this is like `next-line'
6771 (get-char-property (1- (point)) 'invisible))
6772 (beginning-of-line 2))
6773 (while (and (not (eobp)) ;; this is like `next-line'
6774 (get-char-property (1- (point)) 'invisible))
6775 (goto-char (next-single-char-property-change (point) 'invisible))
6776 (and (eolp) (beginning-of-line 2))))
6777 (setq eol (point)))
6778 ;; Find out what to do next and set `this-command'
6779 (cond
6780 ((= eos eoh)
6781 ;; Nothing is hidden behind this heading
6782 (unless (org-before-first-heading-p)
6783 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6784 (org-unlogged-message "EMPTY ENTRY")
6785 (setq org-cycle-subtree-status nil)
6786 (save-excursion
6787 (goto-char eos)
6788 (outline-next-heading)
6789 (if (outline-invisible-p) (org-flag-heading nil))))
6790 ((and (or (>= eol eos)
6791 (not (string-match "\\S-" (buffer-substring eol eos))))
6792 (or has-children
6793 (not (setq children-skipped
6794 org-cycle-skip-children-state-if-no-children))))
6795 ;; Entire subtree is hidden in one line: children view
6796 (unless (org-before-first-heading-p)
6797 (run-hook-with-args 'org-pre-cycle-hook 'children))
6798 (if (org-at-item-p)
6799 (org-list-set-item-visibility (point-at-bol) struct 'children)
6800 (org-show-entry)
6801 (org-with-limited-levels (show-children))
6802 ;; FIXME: This slows down the func way too much.
6803 ;; How keep drawers hidden in subtree anyway?
6804 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6805 ;; (org-cycle-hide-drawers 'subtree))
6807 ;; Fold every list in subtree to top-level items.
6808 (when (eq org-cycle-include-plain-lists 'integrate)
6809 (save-excursion
6810 (org-back-to-heading)
6811 (while (org-list-search-forward (org-item-beginning-re) eos t)
6812 (beginning-of-line 1)
6813 (let* ((struct (org-list-struct))
6814 (prevs (org-list-prevs-alist struct))
6815 (end (org-list-get-bottom-point struct)))
6816 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6817 (org-list-get-all-items (point) struct prevs))
6818 (goto-char (if (< end eos) end eos)))))))
6819 (org-unlogged-message "CHILDREN")
6820 (save-excursion
6821 (goto-char eos)
6822 (outline-next-heading)
6823 (if (outline-invisible-p) (org-flag-heading nil)))
6824 (setq org-cycle-subtree-status 'children)
6825 (unless (org-before-first-heading-p)
6826 (run-hook-with-args 'org-cycle-hook 'children)))
6827 ((or children-skipped
6828 (and (eq last-command this-command)
6829 (eq org-cycle-subtree-status 'children)))
6830 ;; We just showed the children, or no children are there,
6831 ;; now show everything.
6832 (unless (org-before-first-heading-p)
6833 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6834 (outline-flag-region eoh eos nil)
6835 (org-unlogged-message
6836 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6837 (setq org-cycle-subtree-status 'subtree)
6838 (unless (org-before-first-heading-p)
6839 (run-hook-with-args 'org-cycle-hook 'subtree)))
6841 ;; Default action: hide the subtree.
6842 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6843 (outline-flag-region eoh eos t)
6844 (org-unlogged-message "FOLDED")
6845 (setq org-cycle-subtree-status 'folded)
6846 (unless (org-before-first-heading-p)
6847 (run-hook-with-args 'org-cycle-hook 'folded))))))
6849 ;;;###autoload
6850 (defun org-global-cycle (&optional arg)
6851 "Cycle the global visibility. For details see `org-cycle'.
6852 With \\[universal-argument] prefix arg, switch to startup visibility.
6853 With a numeric prefix, show all headlines up to that level."
6854 (interactive "P")
6855 (let ((org-cycle-include-plain-lists
6856 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6857 (cond
6858 ((integerp arg)
6859 (show-all)
6860 (hide-sublevels arg)
6861 (setq org-cycle-global-status 'contents))
6862 ((equal arg '(4))
6863 (org-set-startup-visibility)
6864 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6866 (org-cycle '(4))))))
6868 (defun org-set-startup-visibility ()
6869 "Set the visibility required by startup options and properties."
6870 (cond
6871 ((eq org-startup-folded t)
6872 (org-overview))
6873 ((eq org-startup-folded 'content)
6874 (org-content))
6875 ((or (eq org-startup-folded 'showeverything)
6876 (eq org-startup-folded nil))
6877 (show-all)))
6878 (unless (eq org-startup-folded 'showeverything)
6879 (if org-hide-block-startup (org-hide-block-all))
6880 (org-set-visibility-according-to-property 'no-cleanup)
6881 (org-cycle-hide-archived-subtrees 'all)
6882 (org-cycle-hide-drawers 'all)
6883 (org-cycle-show-empty-lines t)))
6885 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6886 "Switch subtree visibilities according to :VISIBILITY: property."
6887 (interactive)
6888 (let (org-show-entry-below state)
6889 (save-excursion
6890 (goto-char (point-min))
6891 (while (re-search-forward
6892 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6893 nil t)
6894 (setq state (match-string 1))
6895 (save-excursion
6896 (org-back-to-heading t)
6897 (hide-subtree)
6898 (org-reveal)
6899 (cond
6900 ((equal state '("fold" "folded"))
6901 (hide-subtree))
6902 ((equal state "children")
6903 (org-show-hidden-entry)
6904 (show-children))
6905 ((equal state "content")
6906 (save-excursion
6907 (save-restriction
6908 (org-narrow-to-subtree)
6909 (org-content))))
6910 ((member state '("all" "showall"))
6911 (show-subtree)))))
6912 (unless no-cleanup
6913 (org-cycle-hide-archived-subtrees 'all)
6914 (org-cycle-hide-drawers 'all)
6915 (org-cycle-show-empty-lines 'all)))))
6917 ;; This function uses outline-regexp instead of the more fundamental
6918 ;; org-outline-regexp so that org-cycle-global works outside of Org
6919 ;; buffers, where outline-regexp is needed.
6920 (defun org-overview ()
6921 "Switch to overview mode, showing only top-level headlines.
6922 This shows all headlines with a level equal or greater than the level
6923 of the first headline in the buffer. This is important, because if the
6924 first headline is not level one, then (hide-sublevels 1) gives confusing
6925 results."
6926 (interactive)
6927 (save-excursion
6928 (let ((level
6929 (save-excursion
6930 (goto-char (point-min))
6931 (if (re-search-forward (concat "^" outline-regexp) nil t)
6932 (progn
6933 (goto-char (match-beginning 0))
6934 (funcall outline-level))))))
6935 (and level (hide-sublevels level)))))
6937 (defun org-content (&optional arg)
6938 "Show all headlines in the buffer, like a table of contents.
6939 With numerical argument N, show content up to level N."
6940 (interactive "P")
6941 (org-overview)
6942 (save-excursion
6943 ;; Visit all headings and show their offspring
6944 (and (integerp arg) (org-overview))
6945 (goto-char (point-max))
6946 (catch 'exit
6947 (while (and (progn (condition-case nil
6948 (outline-previous-visible-heading 1)
6949 (error (goto-char (point-min))))
6951 (looking-at org-outline-regexp))
6952 (if (integerp arg)
6953 (show-children (1- arg))
6954 (show-branches))
6955 (if (bobp) (throw 'exit nil))))))
6957 (defun org-optimize-window-after-visibility-change (state)
6958 "Adjust the window after a change in outline visibility.
6959 This function is the default value of the hook `org-cycle-hook'."
6960 (when (get-buffer-window (current-buffer))
6961 (cond
6962 ((eq state 'content) nil)
6963 ((eq state 'all) nil)
6964 ((eq state 'folded) nil)
6965 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6966 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6968 (defun org-remove-empty-overlays-at (pos)
6969 "Remove outline overlays that do not contain non-white stuff."
6970 (mapc
6971 (lambda (o)
6972 (and (eq 'outline (overlay-get o 'invisible))
6973 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6974 (overlay-end o))))
6975 (delete-overlay o)))
6976 (overlays-at pos)))
6978 (defun org-clean-visibility-after-subtree-move ()
6979 "Fix visibility issues after moving a subtree."
6980 ;; First, find a reasonable region to look at:
6981 ;; Start two siblings above, end three below
6982 (let* ((beg (save-excursion
6983 (and (org-get-last-sibling)
6984 (org-get-last-sibling))
6985 (point)))
6986 (end (save-excursion
6987 (and (org-get-next-sibling)
6988 (org-get-next-sibling)
6989 (org-get-next-sibling))
6990 (if (org-at-heading-p)
6991 (point-at-eol)
6992 (point))))
6993 (level (looking-at "\\*+"))
6994 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6995 (save-excursion
6996 (save-restriction
6997 (narrow-to-region beg end)
6998 (when re
6999 ;; Properly fold already folded siblings
7000 (goto-char (point-min))
7001 (while (re-search-forward re nil t)
7002 (if (and (not (outline-invisible-p))
7003 (save-excursion
7004 (goto-char (point-at-eol)) (outline-invisible-p)))
7005 (hide-entry))))
7006 (org-cycle-show-empty-lines 'overview)
7007 (org-cycle-hide-drawers 'overview)))))
7009 (defun org-cycle-show-empty-lines (state)
7010 "Show empty lines above all visible headlines.
7011 The region to be covered depends on STATE when called through
7012 `org-cycle-hook'. Lisp program can use t for STATE to get the
7013 entire buffer covered. Note that an empty line is only shown if there
7014 are at least `org-cycle-separator-lines' empty lines before the headline."
7015 (when (not (= org-cycle-separator-lines 0))
7016 (save-excursion
7017 (let* ((n (abs org-cycle-separator-lines))
7018 (re (cond
7019 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7020 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7021 (t (let ((ns (number-to-string (- n 2))))
7022 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7023 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7024 beg end b e)
7025 (cond
7026 ((memq state '(overview contents t))
7027 (setq beg (point-min) end (point-max)))
7028 ((memq state '(children folded))
7029 (setq beg (point) end (progn (org-end-of-subtree t t)
7030 (beginning-of-line 2)
7031 (point)))))
7032 (when beg
7033 (goto-char beg)
7034 (while (re-search-forward re end t)
7035 (unless (get-char-property (match-end 1) 'invisible)
7036 (setq e (match-end 1))
7037 (if (< org-cycle-separator-lines 0)
7038 (setq b (save-excursion
7039 (goto-char (match-beginning 0))
7040 (org-back-over-empty-lines)
7041 (if (save-excursion
7042 (goto-char (max (point-min) (1- (point))))
7043 (org-at-heading-p))
7044 (1- (point))
7045 (point))))
7046 (setq b (match-beginning 1)))
7047 (outline-flag-region b e nil)))))))
7048 ;; Never hide empty lines at the end of the file.
7049 (save-excursion
7050 (goto-char (point-max))
7051 (outline-previous-heading)
7052 (outline-end-of-heading)
7053 (if (and (looking-at "[ \t\n]+")
7054 (= (match-end 0) (point-max)))
7055 (outline-flag-region (point) (match-end 0) nil))))
7057 (defun org-show-empty-lines-in-parent ()
7058 "Move to the parent and re-show empty lines before visible headlines."
7059 (save-excursion
7060 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7061 (org-cycle-show-empty-lines context))))
7063 (defun org-files-list ()
7064 "Return `org-agenda-files' list, plus all open org-mode files.
7065 This is useful for operations that need to scan all of a user's
7066 open and agenda-wise Org files."
7067 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7068 (dolist (buf (buffer-list))
7069 (with-current-buffer buf
7070 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7071 (let ((file (expand-file-name (buffer-file-name))))
7072 (unless (member file files)
7073 (push file files))))))
7074 files))
7076 (defsubst org-entry-beginning-position ()
7077 "Return the beginning position of the current entry."
7078 (save-excursion (outline-back-to-heading t) (point)))
7080 (defsubst org-entry-end-position ()
7081 "Return the end position of the current entry."
7082 (save-excursion (outline-next-heading) (point)))
7084 (defun org-cycle-hide-drawers (state)
7085 "Re-hide all drawers after a visibility state change."
7086 (when (and (derived-mode-p 'org-mode)
7087 (not (memq state '(overview folded contents))))
7088 (save-excursion
7089 (let* ((globalp (memq state '(contents all)))
7090 (beg (if globalp (point-min) (point)))
7091 (end (if globalp (point-max)
7092 (if (eq state 'children)
7093 (save-excursion (outline-next-heading) (point))
7094 (org-end-of-subtree t)))))
7095 (goto-char beg)
7096 (while (re-search-forward org-drawer-regexp end t)
7097 (org-flag-drawer t))))))
7099 (defun org-cycle-hide-inline-tasks (state)
7100 "Re-hide inline tasks when switching to `contents' or `children'
7101 visibility state."
7102 (case state
7103 (contents
7104 (when (org-bound-and-true-p org-inlinetask-min-level)
7105 (hide-sublevels (1- org-inlinetask-min-level))))
7106 (children
7107 (when (featurep 'org-inlinetask)
7108 (save-excursion
7109 (while (and (outline-next-heading)
7110 (org-inlinetask-at-task-p))
7111 (org-inlinetask-toggle-visibility)
7112 (org-inlinetask-goto-end)))))))
7114 (defun org-flag-drawer (flag)
7115 "When FLAG is non-nil, hide the drawer we are within.
7116 Otherwise make it visible."
7117 (save-excursion
7118 (beginning-of-line 1)
7119 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7120 (let ((b (match-end 0)))
7121 (if (re-search-forward
7122 "^[ \t]*:END:"
7123 (save-excursion (outline-next-heading) (point)) t)
7124 (outline-flag-region b (point-at-eol) flag)
7125 (user-error ":END: line missing at position %s" b))))))
7127 (defun org-subtree-end-visible-p ()
7128 "Is the end of the current subtree visible?"
7129 (pos-visible-in-window-p
7130 (save-excursion (org-end-of-subtree t) (point))))
7132 (defun org-first-headline-recenter ()
7133 "Move cursor to the first headline and recenter the headline."
7134 (goto-char (point-min))
7135 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7136 (set-window-start (selected-window) (point-at-bol))))
7138 ;;; Saving and restoring visibility
7140 (defun org-outline-overlay-data (&optional use-markers)
7141 "Return a list of the locations of all outline overlays.
7142 These are overlays with the `invisible' property value `outline'.
7143 The return value is a list of cons cells, with start and stop
7144 positions for each overlay.
7145 If USE-MARKERS is set, return the positions as markers."
7146 (let (beg end)
7147 (save-excursion
7148 (save-restriction
7149 (widen)
7150 (delq nil
7151 (mapcar (lambda (o)
7152 (when (eq (overlay-get o 'invisible) 'outline)
7153 (setq beg (overlay-start o)
7154 end (overlay-end o))
7155 (and beg end (> end beg)
7156 (if use-markers
7157 (cons (move-marker (make-marker) beg)
7158 (move-marker (make-marker) end))
7159 (cons beg end)))))
7160 (overlays-in (point-min) (point-max))))))))
7162 (defun org-set-outline-overlay-data (data)
7163 "Create visibility overlays for all positions in DATA.
7164 DATA should have been made by `org-outline-overlay-data'."
7165 (let (o)
7166 (save-excursion
7167 (save-restriction
7168 (widen)
7169 (show-all)
7170 (mapc (lambda (c)
7171 (outline-flag-region (car c) (cdr c) t))
7172 data)))))
7174 ;;; Folding of blocks
7176 (defvar org-hide-block-overlays nil
7177 "Overlays hiding blocks.")
7178 (make-variable-buffer-local 'org-hide-block-overlays)
7180 (defun org-block-map (function &optional start end)
7181 "Call FUNCTION at the head of all source blocks in the current buffer.
7182 Optional arguments START and END can be used to limit the range."
7183 (let ((start (or start (point-min)))
7184 (end (or end (point-max))))
7185 (save-excursion
7186 (goto-char start)
7187 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7188 (save-excursion
7189 (save-match-data
7190 (goto-char (match-beginning 0))
7191 (funcall function)))))))
7193 (defun org-hide-block-toggle-all ()
7194 "Toggle the visibility of all blocks in the current buffer."
7195 (org-block-map #'org-hide-block-toggle))
7197 (defun org-hide-block-all ()
7198 "Fold all blocks in the current buffer."
7199 (interactive)
7200 (org-show-block-all)
7201 (org-block-map #'org-hide-block-toggle-maybe))
7203 (defun org-show-block-all ()
7204 "Unfold all blocks in the current buffer."
7205 (interactive)
7206 (mapc 'delete-overlay org-hide-block-overlays)
7207 (setq org-hide-block-overlays nil))
7209 (defun org-hide-block-toggle-maybe ()
7210 "Toggle visibility of block at point."
7211 (interactive)
7212 (let ((case-fold-search t))
7213 (if (save-excursion
7214 (beginning-of-line 1)
7215 (looking-at org-block-regexp))
7216 (progn (org-hide-block-toggle)
7217 t) ;; to signal that we took action
7218 nil))) ;; to signal that we did not
7220 (defun org-hide-block-toggle (&optional force)
7221 "Toggle the visibility of the current block."
7222 (interactive)
7223 (save-excursion
7224 (beginning-of-line)
7225 (if (re-search-forward org-block-regexp nil t)
7226 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7227 (end (match-end 0)) ;; end of entire body
7229 (if (memq t (mapcar (lambda (overlay)
7230 (eq (overlay-get overlay 'invisible)
7231 'org-hide-block))
7232 (overlays-at start)))
7233 (if (or (not force) (eq force 'off))
7234 (mapc (lambda (ov)
7235 (when (member ov org-hide-block-overlays)
7236 (setq org-hide-block-overlays
7237 (delq ov org-hide-block-overlays)))
7238 (when (eq (overlay-get ov 'invisible)
7239 'org-hide-block)
7240 (delete-overlay ov)))
7241 (overlays-at start)))
7242 (setq ov (make-overlay start end))
7243 (overlay-put ov 'invisible 'org-hide-block)
7244 ;; make the block accessible to isearch
7245 (overlay-put
7246 ov 'isearch-open-invisible
7247 (lambda (ov)
7248 (when (member ov org-hide-block-overlays)
7249 (setq org-hide-block-overlays
7250 (delq ov org-hide-block-overlays)))
7251 (when (eq (overlay-get ov 'invisible)
7252 'org-hide-block)
7253 (delete-overlay ov))))
7254 (push ov org-hide-block-overlays)))
7255 (user-error "Not looking at a source block"))))
7257 ;; org-tab-after-check-for-cycling-hook
7258 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7259 ;; Remove overlays when changing major mode
7260 (add-hook 'org-mode-hook
7261 (lambda () (org-add-hook 'change-major-mode-hook
7262 'org-show-block-all 'append 'local)))
7264 ;;; Org-goto
7266 (defvar org-goto-window-configuration nil)
7267 (defvar org-goto-marker nil)
7268 (defvar org-goto-map)
7269 (defun org-goto-map ()
7270 "Set the keymap `org-goto'."
7271 (setq org-goto-map
7272 (let ((map (make-sparse-keymap)))
7273 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7274 mouse-drag-region universal-argument org-occur)))
7275 (dolist (cmd cmds)
7276 (substitute-key-definition cmd cmd map global-map)))
7277 (suppress-keymap map)
7278 (org-defkey map "\C-m" 'org-goto-ret)
7279 (org-defkey map [(return)] 'org-goto-ret)
7280 (org-defkey map [(left)] 'org-goto-left)
7281 (org-defkey map [(right)] 'org-goto-right)
7282 (org-defkey map [(control ?g)] 'org-goto-quit)
7283 (org-defkey map "\C-i" 'org-cycle)
7284 (org-defkey map [(tab)] 'org-cycle)
7285 (org-defkey map [(down)] 'outline-next-visible-heading)
7286 (org-defkey map [(up)] 'outline-previous-visible-heading)
7287 (if org-goto-auto-isearch
7288 (if (fboundp 'define-key-after)
7289 (define-key-after map [t] 'org-goto-local-auto-isearch)
7290 nil)
7291 (org-defkey map "q" 'org-goto-quit)
7292 (org-defkey map "n" 'outline-next-visible-heading)
7293 (org-defkey map "p" 'outline-previous-visible-heading)
7294 (org-defkey map "f" 'outline-forward-same-level)
7295 (org-defkey map "b" 'outline-backward-same-level)
7296 (org-defkey map "u" 'outline-up-heading))
7297 (org-defkey map "/" 'org-occur)
7298 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7299 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7300 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7301 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7302 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7303 map)))
7305 (defconst org-goto-help
7306 "Browse buffer copy, to find location or copy text.%s
7307 RET=jump to location C-g=quit and return to previous location
7308 [Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7310 (defvar org-goto-start-pos) ; dynamically scoped parameter
7312 (defun org-goto (&optional alternative-interface)
7313 "Look up a different location in the current file, keeping current visibility.
7315 When you want look-up or go to a different location in a
7316 document, the fastest way is often to fold the entire buffer and
7317 then dive into the tree. This method has the disadvantage, that
7318 the previous location will be folded, which may not be what you
7319 want.
7321 This command works around this by showing a copy of the current
7322 buffer in an indirect buffer, in overview mode. You can dive
7323 into the tree in that copy, use org-occur and incremental search
7324 to find a location. When pressing RET or `Q', the command
7325 returns to the original buffer in which the visibility is still
7326 unchanged. After RET it will also jump to the location selected
7327 in the indirect buffer and expose the headline hierarchy above.
7329 With a prefix argument, use the alternative interface: e.g., if
7330 `org-goto-interface' is `outline' use `outline-path-completion'."
7331 (interactive "P")
7332 (org-goto-map)
7333 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7334 (org-refile-use-outline-path t)
7335 (org-refile-target-verify-function nil)
7336 (interface
7337 (if (not alternative-interface)
7338 org-goto-interface
7339 (if (eq org-goto-interface 'outline)
7340 'outline-path-completion
7341 'outline)))
7342 (org-goto-start-pos (point))
7343 (selected-point
7344 (if (eq interface 'outline)
7345 (car (org-get-location (current-buffer) org-goto-help))
7346 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7347 (org-refile-check-position pa)
7348 (nth 3 pa)))))
7349 (if selected-point
7350 (progn
7351 (org-mark-ring-push org-goto-start-pos)
7352 (goto-char selected-point)
7353 (if (or (outline-invisible-p) (org-invisible-p2))
7354 (org-show-context 'org-goto)))
7355 (message "Quit"))))
7357 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7358 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7359 (defvar org-goto-local-auto-isearch-map) ; defined below
7361 (defun org-get-location (buf help)
7362 "Let the user select a location in the Org-mode buffer BUF.
7363 This function uses a recursive edit. It returns the selected position
7364 or nil."
7365 (org-no-popups
7366 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7367 (isearch-hide-immediately nil)
7368 (isearch-search-fun-function
7369 (lambda () 'org-goto-local-search-headings))
7370 (org-goto-selected-point org-goto-exit-command))
7371 (save-excursion
7372 (save-window-excursion
7373 (delete-other-windows)
7374 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7375 (org-pop-to-buffer-same-window
7376 (condition-case nil
7377 (make-indirect-buffer (current-buffer) "*org-goto*")
7378 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7379 (with-output-to-temp-buffer "*Org Help*"
7380 (princ (format help (if org-goto-auto-isearch
7381 " Just type for auto-isearch."
7382 " n/p/f/b/u to navigate, q to quit."))))
7383 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7384 (setq buffer-read-only nil)
7385 (let ((org-startup-truncated t)
7386 (org-startup-folded nil)
7387 (org-startup-align-all-tables nil))
7388 (org-mode)
7389 (org-overview))
7390 (setq buffer-read-only t)
7391 (if (and (boundp 'org-goto-start-pos)
7392 (integer-or-marker-p org-goto-start-pos))
7393 (let ((org-show-hierarchy-above t)
7394 (org-show-siblings t)
7395 (org-show-following-heading t))
7396 (goto-char org-goto-start-pos)
7397 (and (outline-invisible-p) (org-show-context)))
7398 (goto-char (point-min)))
7399 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7400 (message "Select location and press RET")
7401 (use-local-map org-goto-map)
7402 (recursive-edit)))
7403 (kill-buffer "*org-goto*")
7404 (cons org-goto-selected-point org-goto-exit-command))))
7406 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7407 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7408 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7409 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7411 (defun org-goto-local-search-headings (string bound noerror)
7412 "Search and make sure that any matches are in headlines."
7413 (catch 'return
7414 (while (if isearch-forward
7415 (search-forward string bound noerror)
7416 (search-backward string bound noerror))
7417 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7418 (and (member :headline context)
7419 (not (member :tags context))))
7420 (throw 'return (point))))))
7422 (defun org-goto-local-auto-isearch ()
7423 "Start isearch."
7424 (interactive)
7425 (goto-char (point-min))
7426 (let ((keys (this-command-keys)))
7427 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7428 (isearch-mode t)
7429 (isearch-process-search-char (string-to-char keys)))))
7431 (defun org-goto-ret (&optional arg)
7432 "Finish `org-goto' by going to the new location."
7433 (interactive "P")
7434 (setq org-goto-selected-point (point)
7435 org-goto-exit-command 'return)
7436 (throw 'exit nil))
7438 (defun org-goto-left ()
7439 "Finish `org-goto' by going to the new location."
7440 (interactive)
7441 (if (org-at-heading-p)
7442 (progn
7443 (beginning-of-line 1)
7444 (setq org-goto-selected-point (point)
7445 org-goto-exit-command 'left)
7446 (throw 'exit nil))
7447 (user-error "Not on a heading")))
7449 (defun org-goto-right ()
7450 "Finish `org-goto' by going to the new location."
7451 (interactive)
7452 (if (org-at-heading-p)
7453 (progn
7454 (setq org-goto-selected-point (point)
7455 org-goto-exit-command 'right)
7456 (throw 'exit nil))
7457 (user-error "Not on a heading")))
7459 (defun org-goto-quit ()
7460 "Finish `org-goto' without cursor motion."
7461 (interactive)
7462 (setq org-goto-selected-point nil)
7463 (setq org-goto-exit-command 'quit)
7464 (throw 'exit nil))
7466 ;;; Indirect buffer display of subtrees
7468 (defvar org-indirect-dedicated-frame nil
7469 "This is the frame being used for indirect tree display.")
7470 (defvar org-last-indirect-buffer nil)
7472 (defun org-tree-to-indirect-buffer (&optional arg)
7473 "Create indirect buffer and narrow it to current subtree.
7474 With a numerical prefix ARG, go up to this level and then take that tree.
7475 If ARG is negative, go up that many levels.
7477 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7478 indirect buffer previously made with this command, to avoid proliferation of
7479 indirect buffers. However, when you call the command with a \
7480 \\[universal-argument] prefix, or
7481 when `org-indirect-buffer-display' is `new-frame', the last buffer
7482 is kept so that you can work with several indirect buffers at the same time.
7483 If `org-indirect-buffer-display' is `dedicated-frame', the \
7484 \\[universal-argument] prefix also
7485 requests that a new frame be made for the new buffer, so that the dedicated
7486 frame is not changed."
7487 (interactive "P")
7488 (let ((cbuf (current-buffer))
7489 (cwin (selected-window))
7490 (pos (point))
7491 beg end level heading ibuf)
7492 (save-excursion
7493 (org-back-to-heading t)
7494 (when (numberp arg)
7495 (setq level (org-outline-level))
7496 (if (< arg 0) (setq arg (+ level arg)))
7497 (while (> (setq level (org-outline-level)) arg)
7498 (org-up-heading-safe)))
7499 (setq beg (point)
7500 heading (org-get-heading))
7501 (org-end-of-subtree t t)
7502 (if (org-at-heading-p) (backward-char 1))
7503 (setq end (point)))
7504 (if (and (buffer-live-p org-last-indirect-buffer)
7505 (not (eq org-indirect-buffer-display 'new-frame))
7506 (not arg))
7507 (kill-buffer org-last-indirect-buffer))
7508 (setq ibuf (org-get-indirect-buffer cbuf)
7509 org-last-indirect-buffer ibuf)
7510 (cond
7511 ((or (eq org-indirect-buffer-display 'new-frame)
7512 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7513 (select-frame (make-frame))
7514 (delete-other-windows)
7515 (org-pop-to-buffer-same-window ibuf)
7516 (org-set-frame-title heading))
7517 ((eq org-indirect-buffer-display 'dedicated-frame)
7518 (raise-frame
7519 (select-frame (or (and org-indirect-dedicated-frame
7520 (frame-live-p org-indirect-dedicated-frame)
7521 org-indirect-dedicated-frame)
7522 (setq org-indirect-dedicated-frame (make-frame)))))
7523 (delete-other-windows)
7524 (org-pop-to-buffer-same-window ibuf)
7525 (org-set-frame-title (concat "Indirect: " heading)))
7526 ((eq org-indirect-buffer-display 'current-window)
7527 (org-pop-to-buffer-same-window ibuf))
7528 ((eq org-indirect-buffer-display 'other-window)
7529 (pop-to-buffer ibuf))
7530 (t (error "Invalid value")))
7531 (if (featurep 'xemacs)
7532 (save-excursion (org-mode) (turn-on-font-lock)))
7533 (narrow-to-region beg end)
7534 (show-all)
7535 (goto-char pos)
7536 (run-hook-with-args 'org-cycle-hook 'all)
7537 (and (window-live-p cwin) (select-window cwin))))
7539 (defun org-get-indirect-buffer (&optional buffer)
7540 (setq buffer (or buffer (current-buffer)))
7541 (let ((n 1) (base (buffer-name buffer)) bname)
7542 (while (buffer-live-p
7543 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7544 (setq n (1+ n)))
7545 (condition-case nil
7546 (make-indirect-buffer buffer bname 'clone)
7547 (error (make-indirect-buffer buffer bname)))))
7549 (defun org-set-frame-title (title)
7550 "Set the title of the current frame to the string TITLE."
7551 ;; FIXME: how to name a single frame in XEmacs???
7552 (unless (featurep 'xemacs)
7553 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7555 ;;;; Structure editing
7557 ;;; Inserting headlines
7559 (defun org-previous-line-empty-p (&optional next)
7560 "Is the previous line a blank line?
7561 When NEXT is non-nil, check the next line instead."
7562 (save-excursion
7563 (and (not (bobp))
7564 (or (beginning-of-line (if next 2 0)) t)
7565 (save-match-data
7566 (looking-at "[ \t]*$")))))
7568 (defun org-insert-heading (&optional arg invisible-ok)
7569 "Insert a new heading or an item with the same depth at point.
7571 If point is at the beginning of a heading or a list item, insert
7572 a new heading or a new item above the current one. If point is
7573 at the beginning of a normal line, turn the line into a heading.
7575 If point is in the middle of a headline or a list item, split the
7576 headline or the item and create a new headline/item with the text
7577 in the current line after point \(see `org-M-RET-may-split-line'
7578 on how to modify this behavior).
7580 With one universal prefix argument, set the user option
7581 `org-insert-heading-respect-content' to t for the duration of
7582 the command. This modifies the behavior described above in this
7583 ways: on list items and at the beginning of normal lines, force
7584 the insertion of a heading after the current subtree.
7586 With two universal prefix arguments, insert the heading at the
7587 end of the grandparent subtree. For example, if point is within
7588 a 2nd-level heading, then it will insert a 2nd-level heading at
7589 the end of the 1st-level parent heading.
7591 When INVISIBLE-OK is set, stop at invisible headlines when going
7592 back. This is important for non-interactive uses of the
7593 command."
7594 (interactive "P")
7595 (if (org-called-interactively-p 'any) (org-reveal))
7596 (let ((itemp (org-in-item-p))
7597 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7598 (respect-content (or org-insert-heading-respect-content
7599 (equal arg '(4))))
7600 (initial-content "")
7601 (adjust-empty-lines t))
7603 (cond
7605 ((or (= (buffer-size) 0)
7606 (and (not (save-excursion
7607 (and (ignore-errors (org-back-to-heading invisible-ok))
7608 (org-at-heading-p))))
7609 (or arg (not itemp))))
7610 ;; At beginning of buffer or so high up that only a heading
7611 ;; makes sense.
7612 (cond ((and (bolp) (not respect-content)) (insert "* "))
7613 ((not respect-content)
7614 (unless may-split (end-of-line))
7615 (insert "\n* "))
7616 ((re-search-forward org-outline-regexp-bol nil t)
7617 (beginning-of-line)
7618 (insert "* \n")
7619 (backward-char))
7620 (t (goto-char (point-max))
7621 (insert "\n* ")))
7622 (run-hooks 'org-insert-heading-hook))
7624 ((and itemp (not (member arg '((4) (16)))))
7625 ;; Insert an item
7626 (org-insert-item))
7629 ;; Maybe move at the end of the subtree
7630 (when (equal arg '(16))
7631 (org-up-heading-safe)
7632 (org-end-of-subtree t))
7633 ;; Insert a heading
7634 (save-restriction
7635 (widen)
7636 (let* ((level nil)
7637 (on-heading (org-at-heading-p))
7638 (empty-line-p (if on-heading
7639 (org-previous-line-empty-p)
7640 ;; We will decide later
7641 nil))
7642 ;; Get a level string to fall back on
7643 (fix-level
7644 (if (org-before-first-heading-p) "*"
7645 (save-excursion
7646 (org-back-to-heading t)
7647 (if (org-previous-line-empty-p) (setq empty-line-p t))
7648 (looking-at org-outline-regexp)
7649 (make-string (1- (length (match-string 0))) ?*))))
7650 (stars
7651 (save-excursion
7652 (condition-case nil
7653 (progn
7654 (org-back-to-heading invisible-ok)
7655 (when (and (not on-heading)
7656 (featurep 'org-inlinetask)
7657 (integerp org-inlinetask-min-level)
7658 (>= (length (match-string 0))
7659 org-inlinetask-min-level))
7660 ;; Find a heading level before the inline task
7661 (while (and (setq level (org-up-heading-safe))
7662 (>= level org-inlinetask-min-level)))
7663 (if (org-at-heading-p)
7664 (org-back-to-heading invisible-ok)
7665 (error "This should not happen")))
7666 (unless (and (save-excursion
7667 (save-match-data
7668 (org-backward-heading-same-level
7669 1 invisible-ok))
7670 (= (point) (match-beginning 0)))
7671 (not (org-previous-line-empty-p t)))
7672 (setq empty-line-p (or empty-line-p
7673 (org-previous-line-empty-p))))
7674 (match-string 0))
7675 (error (or fix-level "* ")))))
7676 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7677 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7678 pos hide-previous previous-pos)
7680 ;; If we insert after content, move there and clean up whitespace
7681 (when (and respect-content
7682 (not (org-looking-at-p org-outline-regexp-bol)))
7683 (if (not (org-before-first-heading-p))
7684 (org-end-of-subtree nil t)
7685 (re-search-forward org-outline-regexp-bol)
7686 (beginning-of-line 0))
7687 (skip-chars-backward " \r\n")
7688 (and (not (looking-back "^\\*+" (line-beginning-position)))
7689 (looking-at "[ \t]+") (replace-match ""))
7690 (unless (eobp) (forward-char 1))
7691 (when (looking-at "^\\*")
7692 (unless (bobp) (backward-char 1))
7693 (insert "\n")))
7695 ;; If we are splitting, grab the text that should be moved to the new headline
7696 (when may-split
7697 (if (org-on-heading-p)
7698 ;; This is a heading, we split intelligently (keeping tags)
7699 (let ((pos (point)))
7700 (goto-char (point-at-bol))
7701 (unless (looking-at org-complex-heading-regexp)
7702 (error "This should not happen"))
7703 (when (and (match-beginning 4)
7704 (> pos (match-beginning 4))
7705 (< pos (match-end 4)))
7706 (setq initial-content (buffer-substring pos (match-end 4)))
7707 (goto-char pos)
7708 (delete-region (point) (match-end 4))
7709 (if (looking-at "[ \t]*$")
7710 (replace-match "")
7711 (insert (make-string (length initial-content) ?\ )))
7712 (setq initial-content (org-trim initial-content)))
7713 (goto-char pos))
7714 ;; a normal line
7715 (setq initial-content
7716 (org-trim (buffer-substring (point) (point-at-eol))))
7717 (delete-region (point) (point-at-eol))))
7719 ;; If we are at the beginning of the line, insert before it. Else after
7720 (cond
7721 ((and (bolp) (looking-at "[ \t]*$")))
7722 ((and (bolp) (not (looking-at "[ \t]*$")))
7723 (open-line 1))
7725 (goto-char (point-at-eol))
7726 (insert "\n")))
7728 ;; Insert the new heading
7729 (insert stars)
7730 (just-one-space)
7731 (insert initial-content)
7732 (when adjust-empty-lines
7733 (if (or (not blank)
7734 (and blank (not (org-previous-line-empty-p))))
7735 (org-N-empty-lines-before-current (if blank 1 0))))
7736 (run-hooks 'org-insert-heading-hook)))))))
7738 (defun org-N-empty-lines-before-current (N)
7739 "Make the number of empty lines before current exactly N.
7740 So this will delete or add empty lines."
7741 (save-excursion
7742 (beginning-of-line)
7743 (let ((p (point)))
7744 (skip-chars-backward " \r\t\n")
7745 (unless (bolp) (forward-line))
7746 (delete-region (point) p))
7747 (when (> N 0) (insert (make-string N ?\n)))))
7749 (defun org-get-heading (&optional no-tags no-todo)
7750 "Return the heading of the current entry, without the stars.
7751 When NO-TAGS is non-nil, don't include tags.
7752 When NO-TODO is non-nil, don't include TODO keywords."
7753 (save-excursion
7754 (org-back-to-heading t)
7755 (cond
7756 ((and no-tags no-todo)
7757 (looking-at org-complex-heading-regexp)
7758 (match-string 4))
7759 (no-tags
7760 (looking-at (concat org-outline-regexp
7761 "\\(.*?\\)"
7762 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7763 (match-string 1))
7764 (no-todo
7765 (looking-at org-todo-line-regexp)
7766 (match-string 3))
7767 (t (looking-at org-heading-regexp)
7768 (match-string 2)))))
7770 (defvar orgstruct-mode) ; defined below
7772 (defun org-heading-components ()
7773 "Return the components of the current heading.
7774 This is a list with the following elements:
7775 - the level as an integer
7776 - the reduced level, different if `org-odd-levels-only' is set.
7777 - the TODO keyword, or nil
7778 - the priority character, like ?A, or nil if no priority is given
7779 - the headline text itself, or the tags string if no headline text
7780 - the tags string, or nil."
7781 (save-excursion
7782 (org-back-to-heading t)
7783 (if (let (case-fold-search)
7784 (looking-at
7785 (if orgstruct-mode
7786 org-heading-regexp
7787 org-complex-heading-regexp)))
7788 (if orgstruct-mode
7789 (list (length (match-string 1))
7790 (org-reduced-level (length (match-string 1)))
7793 (match-string 2)
7794 nil)
7795 (list (length (match-string 1))
7796 (org-reduced-level (length (match-string 1)))
7797 (org-match-string-no-properties 2)
7798 (and (match-end 3) (aref (match-string 3) 2))
7799 (org-match-string-no-properties 4)
7800 (org-match-string-no-properties 5))))))
7802 (defun org-get-entry ()
7803 "Get the entry text, after heading, entire subtree."
7804 (save-excursion
7805 (org-back-to-heading t)
7806 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7808 (defun org-insert-heading-after-current ()
7809 "Insert a new heading with same level as current, after current subtree."
7810 (interactive)
7811 (org-back-to-heading)
7812 (org-insert-heading)
7813 (org-move-subtree-down)
7814 (end-of-line 1))
7816 (defun org-insert-heading-respect-content (&optional invisible-ok)
7817 "Insert heading with `org-insert-heading-respect-content' set to t."
7818 (interactive)
7819 (org-insert-heading '(4) invisible-ok))
7821 (defun org-insert-todo-heading-respect-content (&optional force-state)
7822 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7823 (interactive)
7824 (org-insert-todo-heading force-state '(4)))
7826 (defun org-insert-todo-heading (arg &optional force-heading)
7827 "Insert a new heading with the same level and TODO state as current heading.
7828 If the heading has no TODO state, or if the state is DONE, use the first
7829 state (TODO by default). Also with one prefix arg, force first state. With
7830 two prefix args, force inserting at the end of the parent subtree."
7831 (interactive "P")
7832 (when (or force-heading (not (org-insert-item 'checkbox)))
7833 (org-insert-heading (or (and (equal arg '(16)) '(16))
7834 force-heading))
7835 (save-excursion
7836 (org-back-to-heading)
7837 (outline-previous-heading)
7838 (looking-at org-todo-line-regexp))
7839 (let*
7840 ((new-mark-x
7841 (if (or (equal arg '(4))
7842 (not (match-beginning 2))
7843 (member (match-string 2) org-done-keywords))
7844 (car org-todo-keywords-1)
7845 (match-string 2)))
7846 (new-mark
7848 (run-hook-with-args-until-success
7849 'org-todo-get-default-hook new-mark-x nil)
7850 new-mark-x)))
7851 (beginning-of-line 1)
7852 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7853 (if org-treat-insert-todo-heading-as-state-change
7854 (org-todo new-mark)
7855 (insert new-mark " "))))
7856 (when org-provide-todo-statistics
7857 (org-update-parent-todo-statistics))))
7859 (defun org-insert-subheading (arg)
7860 "Insert a new subheading and demote it.
7861 Works for outline headings and for plain lists alike."
7862 (interactive "P")
7863 (org-insert-heading arg)
7864 (cond
7865 ((org-at-heading-p) (org-do-demote))
7866 ((org-at-item-p) (org-indent-item))))
7868 (defun org-insert-todo-subheading (arg)
7869 "Insert a new subheading with TODO keyword or checkbox and demote it.
7870 Works for outline headings and for plain lists alike."
7871 (interactive "P")
7872 (org-insert-todo-heading arg)
7873 (cond
7874 ((org-at-heading-p) (org-do-demote))
7875 ((org-at-item-p) (org-indent-item))))
7877 ;;; Promotion and Demotion
7879 (defvar org-after-demote-entry-hook nil
7880 "Hook run after an entry has been demoted.
7881 The cursor will be at the beginning of the entry.
7882 When a subtree is being demoted, the hook will be called for each node.")
7884 (defvar org-after-promote-entry-hook nil
7885 "Hook run after an entry has been promoted.
7886 The cursor will be at the beginning of the entry.
7887 When a subtree is being promoted, the hook will be called for each node.")
7889 (defun org-promote-subtree ()
7890 "Promote the entire subtree.
7891 See also `org-promote'."
7892 (interactive)
7893 (save-excursion
7894 (org-with-limited-levels (org-map-tree 'org-promote)))
7895 (org-fix-position-after-promote))
7897 (defun org-demote-subtree ()
7898 "Demote the entire subtree. See `org-demote'.
7899 See also `org-promote'."
7900 (interactive)
7901 (save-excursion
7902 (org-with-limited-levels (org-map-tree 'org-demote)))
7903 (org-fix-position-after-promote))
7906 (defun org-do-promote ()
7907 "Promote the current heading higher up the tree.
7908 If the region is active in `transient-mark-mode', promote all headings
7909 in the region."
7910 (interactive)
7911 (save-excursion
7912 (if (org-region-active-p)
7913 (org-map-region 'org-promote (region-beginning) (region-end))
7914 (org-promote)))
7915 (org-fix-position-after-promote))
7917 (defun org-do-demote ()
7918 "Demote the current heading lower down the tree.
7919 If the region is active in `transient-mark-mode', demote all headings
7920 in the region."
7921 (interactive)
7922 (save-excursion
7923 (if (org-region-active-p)
7924 (org-map-region 'org-demote (region-beginning) (region-end))
7925 (org-demote)))
7926 (org-fix-position-after-promote))
7928 (defun org-fix-position-after-promote ()
7929 "Make sure that after pro/demotion cursor position is right."
7930 (let ((pos (point)))
7931 (when (save-excursion
7932 (beginning-of-line 1)
7933 (looking-at org-todo-line-regexp)
7934 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7935 (cond ((eobp) (insert " "))
7936 ((eolp) (insert " "))
7937 ((equal (char-after) ?\ ) (forward-char 1))))))
7939 (defun org-current-level ()
7940 "Return the level of the current entry, or nil if before the first headline.
7941 The level is the number of stars at the beginning of the headline."
7942 (save-excursion
7943 (org-with-limited-levels
7944 (if (ignore-errors (org-back-to-heading t))
7945 (funcall outline-level)))))
7947 (defun org-get-previous-line-level ()
7948 "Return the outline depth of the last headline before the current line.
7949 Returns 0 for the first headline in the buffer, and nil if before the
7950 first headline."
7951 (and (org-current-level)
7952 (or (and (/= (line-beginning-position) (point-min))
7953 (save-excursion (beginning-of-line 0) (org-current-level)))
7954 0)))
7956 (defun org-reduced-level (l)
7957 "Compute the effective level of a heading.
7958 This takes into account the setting of `org-odd-levels-only'."
7959 (cond
7960 ((zerop l) 0)
7961 (org-odd-levels-only (1+ (floor (/ l 2))))
7962 (t l)))
7964 (defun org-level-increment ()
7965 "Return the number of stars that will be added or removed at a
7966 time to headlines when structure editing, based on the value of
7967 `org-odd-levels-only'."
7968 (if org-odd-levels-only 2 1))
7970 (defun org-get-valid-level (level &optional change)
7971 "Rectify a level change under the influence of `org-odd-levels-only'
7972 LEVEL is a current level, CHANGE is by how much the level should be
7973 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7974 even level numbers will become the next higher odd number."
7975 (if org-odd-levels-only
7976 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7977 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7978 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7979 (max 1 (+ level (or change 0)))))
7981 (if (boundp 'define-obsolete-function-alias)
7982 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7983 (define-obsolete-function-alias 'org-get-legal-level
7984 'org-get-valid-level)
7985 (define-obsolete-function-alias 'org-get-legal-level
7986 'org-get-valid-level "23.1")))
7988 (defun org-promote ()
7989 "Promote the current heading higher up the tree.
7990 If the region is active in `transient-mark-mode', promote all headings
7991 in the region."
7992 (org-back-to-heading t)
7993 (let* ((level (save-match-data (funcall outline-level)))
7994 (after-change-functions (remove 'flyspell-after-change-function
7995 after-change-functions))
7996 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7997 (diff (abs (- level (length up-head) -1))))
7998 (cond ((and (= level 1) org-called-with-limited-levels
7999 org-allow-promoting-top-level-subtree)
8000 (replace-match "# " nil t))
8001 ((= level 1)
8002 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8003 (t (replace-match up-head nil t)))
8004 ;; Fixup tag positioning
8005 (unless (= level 1)
8006 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8007 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8008 (run-hooks 'org-after-promote-entry-hook)))
8010 (defun org-demote ()
8011 "Demote the current heading lower down the tree.
8012 If the region is active in `transient-mark-mode', demote all headings
8013 in the region."
8014 (org-back-to-heading t)
8015 (let* ((level (save-match-data (funcall outline-level)))
8016 (after-change-functions (remove 'flyspell-after-change-function
8017 after-change-functions))
8018 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8019 (diff (abs (- level (length down-head) -1))))
8020 (replace-match down-head nil t)
8021 ;; Fixup tag positioning
8022 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8023 (if org-adapt-indentation (org-fixup-indentation diff))
8024 (run-hooks 'org-after-demote-entry-hook)))
8026 (defun org-cycle-level ()
8027 "Cycle the level of an empty headline through possible states.
8028 This goes first to child, then to parent, level, then up the hierarchy.
8029 After top level, it switches back to sibling level."
8030 (interactive)
8031 (let ((org-adapt-indentation nil))
8032 (when (org-point-at-end-of-empty-headline)
8033 (setq this-command 'org-cycle-level) ; Only needed for caching
8034 (let ((cur-level (org-current-level))
8035 (prev-level (org-get-previous-line-level)))
8036 (cond
8037 ;; If first headline in file, promote to top-level.
8038 ((= prev-level 0)
8039 (loop repeat (/ (- cur-level 1) (org-level-increment))
8040 do (org-do-promote)))
8041 ;; If same level as prev, demote one.
8042 ((= prev-level cur-level)
8043 (org-do-demote))
8044 ;; If parent is top-level, promote to top level if not already.
8045 ((= prev-level 1)
8046 (loop repeat (/ (- cur-level 1) (org-level-increment))
8047 do (org-do-promote)))
8048 ;; If top-level, return to prev-level.
8049 ((= cur-level 1)
8050 (loop repeat (/ (- prev-level 1) (org-level-increment))
8051 do (org-do-demote)))
8052 ;; If less than prev-level, promote one.
8053 ((< cur-level prev-level)
8054 (org-do-promote))
8055 ;; If deeper than prev-level, promote until higher than
8056 ;; prev-level.
8057 ((> cur-level prev-level)
8058 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8059 do (org-do-promote))))
8060 t))))
8062 (defun org-map-tree (fun)
8063 "Call FUN for every heading underneath the current one."
8064 (org-back-to-heading)
8065 (let ((level (funcall outline-level)))
8066 (save-excursion
8067 (funcall fun)
8068 (while (and (progn
8069 (outline-next-heading)
8070 (> (funcall outline-level) level))
8071 (not (eobp)))
8072 (funcall fun)))))
8074 (defun org-map-region (fun beg end)
8075 "Call FUN for every heading between BEG and END."
8076 (let ((org-ignore-region t))
8077 (save-excursion
8078 (setq end (copy-marker end))
8079 (goto-char beg)
8080 (if (and (re-search-forward org-outline-regexp-bol nil t)
8081 (< (point) end))
8082 (funcall fun))
8083 (while (and (progn
8084 (outline-next-heading)
8085 (< (point) end))
8086 (not (eobp)))
8087 (funcall fun)))))
8089 (defvar org-property-end-re) ; silence byte-compiler
8090 (defun org-fixup-indentation (diff)
8091 "Change the indentation in the current entry by DIFF.
8092 However, if any line in the current entry has no indentation, or if it
8093 would end up with no indentation after the change, nothing at all is done."
8094 (save-excursion
8095 (let ((end (save-excursion (outline-next-heading)
8096 (point-marker)))
8097 (prohibit (if (> diff 0)
8098 "^\\S-"
8099 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8100 col)
8101 (unless (save-excursion (end-of-line 1)
8102 (re-search-forward prohibit end t))
8103 (while (and (< (point) end)
8104 (re-search-forward "^[ \t]+" end t))
8105 (goto-char (match-end 0))
8106 (setq col (current-column))
8107 (if (< diff 0) (replace-match ""))
8108 (org-indent-to-column (+ diff col))))
8109 (move-marker end nil))))
8111 (defun org-convert-to-odd-levels ()
8112 "Convert an org-mode file with all levels allowed to one with odd levels.
8113 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8114 level 5 etc."
8115 (interactive)
8116 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8117 (let ((outline-level 'org-outline-level)
8118 (org-odd-levels-only nil) n)
8119 (save-excursion
8120 (goto-char (point-min))
8121 (while (re-search-forward "^\\*\\*+ " nil t)
8122 (setq n (- (length (match-string 0)) 2))
8123 (while (>= (setq n (1- n)) 0)
8124 (org-demote))
8125 (end-of-line 1))))))
8127 (defun org-convert-to-oddeven-levels ()
8128 "Convert an org-mode file with only odd levels to one with odd/even levels.
8129 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8130 file contains a section with an even level, conversion would
8131 destroy the structure of the file. An error is signaled in this
8132 case."
8133 (interactive)
8134 (goto-char (point-min))
8135 ;; First check if there are no even levels
8136 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8137 (org-show-context t)
8138 (error "Not all levels are odd in this file. Conversion not possible"))
8139 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8140 (let ((outline-regexp org-outline-regexp)
8141 (outline-level 'org-outline-level)
8142 (org-odd-levels-only nil) n)
8143 (save-excursion
8144 (goto-char (point-min))
8145 (while (re-search-forward "^\\*\\*+ " nil t)
8146 (setq n (/ (1- (length (match-string 0))) 2))
8147 (while (>= (setq n (1- n)) 0)
8148 (org-promote))
8149 (end-of-line 1))))))
8151 (defun org-tr-level (n)
8152 "Make N odd if required."
8153 (if org-odd-levels-only (1+ (/ n 2)) n))
8155 ;;; Vertical tree motion, cutting and pasting of subtrees
8157 (defun org-move-subtree-up (&optional arg)
8158 "Move the current subtree up past ARG headlines of the same level."
8159 (interactive "p")
8160 (org-move-subtree-down (- (prefix-numeric-value arg))))
8162 (defun org-move-subtree-down (&optional arg)
8163 "Move the current subtree down past ARG headlines of the same level."
8164 (interactive "p")
8165 (setq arg (prefix-numeric-value arg))
8166 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8167 'org-get-last-sibling))
8168 (ins-point (make-marker))
8169 (cnt (abs arg))
8170 (col (current-column))
8171 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8172 ;; Select the tree
8173 (org-back-to-heading)
8174 (setq beg0 (point))
8175 (save-excursion
8176 (setq ne-beg (org-back-over-empty-lines))
8177 (setq beg (point)))
8178 (save-match-data
8179 (save-excursion (outline-end-of-heading)
8180 (setq folded (outline-invisible-p)))
8181 (progn (org-end-of-subtree nil t)
8182 (unless (eobp) (backward-char))))
8183 (outline-next-heading)
8184 (setq ne-end (org-back-over-empty-lines))
8185 (setq end (point))
8186 (goto-char beg0)
8187 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8188 ;; include less whitespace
8189 (save-excursion
8190 (goto-char beg)
8191 (forward-line (- ne-beg ne-end))
8192 (setq beg (point))))
8193 ;; Find insertion point, with error handling
8194 (while (> cnt 0)
8195 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8196 (progn (goto-char beg0)
8197 (user-error "Cannot move past superior level or buffer limit")))
8198 (setq cnt (1- cnt)))
8199 (if (> arg 0)
8200 ;; Moving forward - still need to move over subtree
8201 (progn (org-end-of-subtree t t)
8202 (save-excursion
8203 (org-back-over-empty-lines)
8204 (or (bolp) (newline)))))
8205 (setq ne-ins (org-back-over-empty-lines))
8206 (move-marker ins-point (point))
8207 (setq txt (buffer-substring beg end))
8208 (org-save-markers-in-region beg end)
8209 (delete-region beg end)
8210 (org-remove-empty-overlays-at beg)
8211 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8212 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8213 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8214 (let ((bbb (point)))
8215 (insert-before-markers txt)
8216 (org-reinstall-markers-in-region bbb)
8217 (move-marker ins-point bbb))
8218 (or (bolp) (insert "\n"))
8219 (setq ins-end (point))
8220 (goto-char ins-point)
8221 (org-skip-whitespace)
8222 (when (and (< arg 0)
8223 (org-first-sibling-p)
8224 (> ne-ins ne-beg))
8225 ;; Move whitespace back to beginning
8226 (save-excursion
8227 (goto-char ins-end)
8228 (let ((kill-whole-line t))
8229 (kill-line (- ne-ins ne-beg)) (point)))
8230 (insert (make-string (- ne-ins ne-beg) ?\n)))
8231 (move-marker ins-point nil)
8232 (if folded
8233 (hide-subtree)
8234 (org-show-entry)
8235 (show-children)
8236 (org-cycle-hide-drawers 'children))
8237 (org-clean-visibility-after-subtree-move)
8238 ;; move back to the initial column we were at
8239 (move-to-column col)))
8241 (defvar org-subtree-clip ""
8242 "Clipboard for cut and paste of subtrees.
8243 This is actually only a copy of the kill, because we use the normal kill
8244 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8246 (defvar org-subtree-clip-folded nil
8247 "Was the last copied subtree folded?
8248 This is used to fold the tree back after pasting.")
8250 (defun org-cut-subtree (&optional n)
8251 "Cut the current subtree into the clipboard.
8252 With prefix arg N, cut this many sequential subtrees.
8253 This is a short-hand for marking the subtree and then cutting it."
8254 (interactive "p")
8255 (org-copy-subtree n 'cut))
8257 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8258 "Copy the current subtree it in the clipboard.
8259 With prefix arg N, copy this many sequential subtrees.
8260 This is a short-hand for marking the subtree and then copying it.
8261 If CUT is non-nil, actually cut the subtree.
8262 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8263 of some markers in the region, even if CUT is non-nil. This is
8264 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8265 (interactive "p")
8266 (let (beg end folded (beg0 (point)))
8267 (if (org-called-interactively-p 'any)
8268 (org-back-to-heading nil) ; take what looks like a subtree
8269 (org-back-to-heading t)) ; take what is really there
8270 (setq beg (point))
8271 (skip-chars-forward " \t\r\n")
8272 (save-match-data
8273 (if nosubtrees
8274 (outline-next-heading)
8275 (save-excursion (outline-end-of-heading)
8276 (setq folded (outline-invisible-p)))
8277 (condition-case nil
8278 (org-forward-heading-same-level (1- n) t)
8279 (error nil))
8280 (org-end-of-subtree t t)))
8281 (setq end (point))
8282 (goto-char beg0)
8283 (when (> end beg)
8284 (setq org-subtree-clip-folded folded)
8285 (when (or cut force-store-markers)
8286 (org-save-markers-in-region beg end))
8287 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8288 (setq org-subtree-clip (current-kill 0))
8289 (message "%s: Subtree(s) with %d characters"
8290 (if cut "Cut" "Copied")
8291 (length org-subtree-clip)))))
8293 (defun org-paste-subtree (&optional level tree for-yank)
8294 "Paste the clipboard as a subtree, with modification of headline level.
8295 The entire subtree is promoted or demoted in order to match a new headline
8296 level.
8298 If the cursor is at the beginning of a headline, the same level as
8299 that headline is used to paste the tree.
8301 If not, the new level is derived from the *visible* headings
8302 before and after the insertion point, and taken to be the inferior headline
8303 level of the two. So if the previous visible heading is level 3 and the
8304 next is level 4 (or vice versa), level 4 will be used for insertion.
8305 This makes sure that the subtree remains an independent subtree and does
8306 not swallow low level entries.
8308 You can also force a different level, either by using a numeric prefix
8309 argument, or by inserting the heading marker by hand. For example, if the
8310 cursor is after \"*****\", then the tree will be shifted to level 5.
8312 If optional TREE is given, use this text instead of the kill ring.
8314 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8315 move back over whitespace before inserting, and move point to the end of
8316 the inserted text when done."
8317 (interactive "P")
8318 (setq tree (or tree (and kill-ring (current-kill 0))))
8319 (unless (org-kill-is-subtree-p tree)
8320 (user-error "%s"
8321 (substitute-command-keys
8322 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8323 (org-with-limited-levels
8324 (let* ((visp (not (outline-invisible-p)))
8325 (txt tree)
8326 (^re_ "\\(\\*+\\)[ \t]*")
8327 (old-level (if (string-match org-outline-regexp-bol txt)
8328 (- (match-end 0) (match-beginning 0) 1)
8329 -1))
8330 (force-level (cond (level (prefix-numeric-value level))
8331 ((and (looking-at "[ \t]*$")
8332 (string-match
8333 "^\\*+$" (buffer-substring
8334 (point-at-bol) (point))))
8335 (- (match-end 0) (match-beginning 0)))
8336 ((and (bolp)
8337 (looking-at org-outline-regexp))
8338 (- (match-end 0) (point) 1))))
8339 (previous-level (save-excursion
8340 (condition-case nil
8341 (progn
8342 (outline-previous-visible-heading 1)
8343 (if (looking-at ^re_)
8344 (- (match-end 0) (match-beginning 0) 1)
8346 (error 1))))
8347 (next-level (save-excursion
8348 (condition-case nil
8349 (progn
8350 (or (looking-at org-outline-regexp)
8351 (outline-next-visible-heading 1))
8352 (if (looking-at ^re_)
8353 (- (match-end 0) (match-beginning 0) 1)
8355 (error 1))))
8356 (new-level (or force-level (max previous-level next-level)))
8357 (shift (if (or (= old-level -1)
8358 (= new-level -1)
8359 (= old-level new-level))
8361 (- new-level old-level)))
8362 (delta (if (> shift 0) -1 1))
8363 (func (if (> shift 0) 'org-demote 'org-promote))
8364 (org-odd-levels-only nil)
8365 beg end newend)
8366 ;; Remove the forced level indicator
8367 (if force-level
8368 (delete-region (point-at-bol) (point)))
8369 ;; Paste
8370 (beginning-of-line (if (bolp) 1 2))
8371 (setq beg (point))
8372 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8373 (insert-before-markers txt)
8374 (unless (string-match "\n\\'" txt) (insert "\n"))
8375 (setq newend (point))
8376 (org-reinstall-markers-in-region beg)
8377 (setq end (point))
8378 (goto-char beg)
8379 (skip-chars-forward " \t\n\r")
8380 (setq beg (point))
8381 (if (and (outline-invisible-p) visp)
8382 (save-excursion (outline-show-heading)))
8383 ;; Shift if necessary
8384 (unless (= shift 0)
8385 (save-restriction
8386 (narrow-to-region beg end)
8387 (while (not (= shift 0))
8388 (org-map-region func (point-min) (point-max))
8389 (setq shift (+ delta shift)))
8390 (goto-char (point-min))
8391 (setq newend (point-max))))
8392 (when (or (org-called-interactively-p 'interactive) for-yank)
8393 (message "Clipboard pasted as level %d subtree" new-level))
8394 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8395 kill-ring
8396 (eq org-subtree-clip (current-kill 0))
8397 org-subtree-clip-folded)
8398 ;; The tree was folded before it was killed/copied
8399 (hide-subtree))
8400 (and for-yank (goto-char newend)))))
8402 (defun org-kill-is-subtree-p (&optional txt)
8403 "Check if the current kill is an outline subtree, or a set of trees.
8404 Returns nil if kill does not start with a headline, or if the first
8405 headline level is not the largest headline level in the tree.
8406 So this will actually accept several entries of equal levels as well,
8407 which is OK for `org-paste-subtree'.
8408 If optional TXT is given, check this string instead of the current kill."
8409 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8410 (re (org-get-limited-outline-regexp))
8411 (^re (concat "^" re))
8412 (start-level (and kill
8413 (string-match
8414 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8415 kill)
8416 (- (match-end 2) (match-beginning 2) 1)))
8417 (start (1+ (or (match-beginning 2) -1))))
8418 (if (not start-level)
8419 (progn
8420 nil) ;; does not even start with a heading
8421 (catch 'exit
8422 (while (setq start (string-match ^re kill (1+ start)))
8423 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8424 (throw 'exit nil)))
8425 t))))
8427 (defvar org-markers-to-move nil
8428 "Markers that should be moved with a cut-and-paste operation.
8429 Those markers are stored together with their positions relative to
8430 the start of the region.")
8432 (defun org-save-markers-in-region (beg end)
8433 "Check markers in region.
8434 If these markers are between BEG and END, record their position relative
8435 to BEG, so that after moving the block of text, we can put the markers back
8436 into place.
8437 This function gets called just before an entry or tree gets cut from the
8438 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8439 called immediately, to move the markers with the entries."
8440 (setq org-markers-to-move nil)
8441 (when (featurep 'org-clock)
8442 (org-clock-save-markers-for-cut-and-paste beg end))
8443 (when (featurep 'org-agenda)
8444 (org-agenda-save-markers-for-cut-and-paste beg end)))
8446 (defun org-check-and-save-marker (marker beg end)
8447 "Check if MARKER is between BEG and END.
8448 If yes, remember the marker and the distance to BEG."
8449 (when (and (marker-buffer marker)
8450 (equal (marker-buffer marker) (current-buffer)))
8451 (if (and (>= marker beg) (< marker end))
8452 (push (cons marker (- marker beg)) org-markers-to-move))))
8454 (defun org-reinstall-markers-in-region (beg)
8455 "Move all remembered markers to their position relative to BEG."
8456 (mapc (lambda (x)
8457 (move-marker (car x) (+ beg (cdr x))))
8458 org-markers-to-move)
8459 (setq org-markers-to-move nil))
8461 (defun org-narrow-to-subtree ()
8462 "Narrow buffer to the current subtree."
8463 (interactive)
8464 (save-excursion
8465 (save-match-data
8466 (org-with-limited-levels
8467 (narrow-to-region
8468 (progn (org-back-to-heading t) (point))
8469 (progn (org-end-of-subtree t t)
8470 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8471 (point)))))))
8473 (defun org-narrow-to-block ()
8474 "Narrow buffer to the current block."
8475 (interactive)
8476 (let* ((case-fold-search t)
8477 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8478 "^[ \t]*#\\+end_.*")))
8479 (if blockp
8480 (narrow-to-region (car blockp) (cdr blockp))
8481 (user-error "Not in a block"))))
8483 (eval-when-compile
8484 (defvar org-property-drawer-re))
8486 (defvar org-property-start-re) ;; defined below
8487 (defun org-clone-subtree-with-time-shift (n &optional shift)
8488 "Clone the task (subtree) at point N times.
8489 The clones will be inserted as siblings.
8491 In interactive use, the user will be prompted for the number of
8492 clones to be produced. If the entry has a timestamp, the user
8493 will also be prompted for a time shift, which may be a repeater
8494 as used in time stamps, for example `+3d'. To disable this,
8495 you can call the function with a universal prefix argument.
8497 When a valid repeater is given and the entry contains any time
8498 stamps, the clones will become a sequence in time, with time
8499 stamps in the subtree shifted for each clone produced. If SHIFT
8500 is nil or the empty string, time stamps will be left alone. The
8501 ID property of the original subtree is removed.
8503 If the original subtree did contain time stamps with a repeater,
8504 the following will happen:
8505 - the repeater will be removed in each clone
8506 - an additional clone will be produced, with the current, unshifted
8507 date(s) in the entry.
8508 - the original entry will be placed *after* all the clones, with
8509 repeater intact.
8510 - the start days in the repeater in the original entry will be shifted
8511 to past the last clone.
8512 In this way you can spell out a number of instances of a repeating task,
8513 and still retain the repeater to cover future instances of the task."
8514 (interactive "nNumber of clones to produce: ")
8515 (let ((shift
8516 (or shift
8517 (if (and (not (equal current-prefix-arg '(4)))
8518 (save-excursion
8519 (re-search-forward org-ts-regexp-both
8520 (save-excursion
8521 (org-end-of-subtree t)
8522 (point)) t)))
8523 (read-from-minibuffer
8524 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8525 ""))) ;; No time shift
8526 (n-no-remove -1)
8527 (drawer-re org-drawer-regexp)
8528 beg end template task idprop
8529 shift-n shift-what doshift nmin nmax)
8530 (if (not (and (integerp n) (> n 0)))
8531 (error "Invalid number of replications %s" n))
8532 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8533 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8534 shift)))
8535 (error "Invalid shift specification %s" shift))
8536 (when doshift
8537 (setq shift-n (string-to-number (match-string 1 shift))
8538 shift-what (cdr (assoc (match-string 2 shift)
8539 '(("d" . day) ("w" . week)
8540 ("m" . month) ("y" . year))))))
8541 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8542 (setq nmin 1 nmax n)
8543 (org-back-to-heading t)
8544 (setq beg (point))
8545 (setq idprop (org-entry-get nil "ID"))
8546 (org-end-of-subtree t t)
8547 (or (bolp) (insert "\n"))
8548 (setq end (point))
8549 (setq template (buffer-substring beg end))
8550 (when (and doshift
8551 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8552 (delete-region beg end)
8553 (setq end beg)
8554 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8555 (goto-char end)
8556 (loop for n from nmin to nmax do
8557 ;; prepare clone
8558 (with-temp-buffer
8559 (insert template)
8560 (org-mode)
8561 (goto-char (point-min))
8562 (org-show-subtree)
8563 (and idprop (if org-clone-delete-id
8564 (org-entry-delete nil "ID")
8565 (org-id-get-create t)))
8566 (unless (= n 0)
8567 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8568 (kill-whole-line))
8569 (goto-char (point-min))
8570 (while (re-search-forward drawer-re nil t)
8571 (mapc (lambda (d)
8572 (org-remove-empty-drawer-at d (point)))
8573 org-drawers)))
8574 (goto-char (point-min))
8575 (when doshift
8576 (while (re-search-forward org-ts-regexp-both nil t)
8577 (org-timestamp-change (* n shift-n) shift-what))
8578 (unless (= n n-no-remove)
8579 (goto-char (point-min))
8580 (while (re-search-forward org-ts-regexp nil t)
8581 (save-excursion
8582 (goto-char (match-beginning 0))
8583 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8584 (delete-region (match-beginning 1) (match-end 1)))))))
8585 (setq task (buffer-string)))
8586 (insert task))
8587 (goto-char beg)))
8589 ;;; Outline Sorting
8591 (defun org-sort (with-case)
8592 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8593 Optional argument WITH-CASE means sort case-sensitively."
8594 (interactive "P")
8595 (cond
8596 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8597 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8599 (org-call-with-arg 'org-sort-entries with-case))))
8601 (defun org-sort-remove-invisible (s)
8602 "Remove invisible links from string S."
8603 (remove-text-properties 0 (length s) org-rm-props s)
8604 (while (string-match org-bracket-link-regexp s)
8605 (setq s (replace-match (if (match-end 2)
8606 (match-string 3 s)
8607 (match-string 1 s))
8608 t t s)))
8609 (let ((st (format " %s " s)))
8610 (while (string-match org-emph-re st)
8611 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8612 (setq s (substring st 1 -1)))
8615 (defvar org-priority-regexp) ; defined later in the file
8617 (defvar org-after-sorting-entries-or-items-hook nil
8618 "Hook that is run after a bunch of entries or items have been sorted.
8619 When children are sorted, the cursor is in the parent line when this
8620 hook gets called. When a region or a plain list is sorted, the cursor
8621 will be in the first entry of the sorted region/list.")
8623 (defun org-sort-entries
8624 (&optional with-case sorting-type getkey-func compare-func property)
8625 "Sort entries on a certain level of an outline tree.
8626 If there is an active region, the entries in the region are sorted.
8627 Else, if the cursor is before the first entry, sort the top-level items.
8628 Else, the children of the entry at point are sorted.
8630 Sorting can be alphabetically, numerically, by date/time as given by
8631 a time stamp, by a property, by priority order, or by a custom function.
8633 The command prompts for the sorting type unless it has been given to the
8634 function through the SORTING-TYPE argument, which needs to be a character,
8635 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8636 precise meaning of each character:
8638 n Numerically, by converting the beginning of the entry/item to a number.
8639 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8640 o By order of TODO keywords.
8641 t By date/time, either the first active time stamp in the entry, or, if
8642 none exist, by the first inactive one.
8643 s By the scheduled date/time.
8644 d By deadline date/time.
8645 c By creation time, which is assumed to be the first inactive time stamp
8646 at the beginning of a line.
8647 p By priority according to the cookie.
8648 r By the value of a property.
8650 Capital letters will reverse the sort order.
8652 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8653 called with point at the beginning of the record. It must return either
8654 a string or a number that should serve as the sorting key for that record.
8656 Comparing entries ignores case by default. However, with an optional argument
8657 WITH-CASE, the sorting considers case as well.
8659 Sorting is done against the visible part of the headlines, it ignores hidden
8660 links."
8661 (interactive "P")
8662 (let ((case-func (if with-case 'identity 'downcase))
8663 (cmstr
8664 ;; The clock marker is lost when using `sort-subr', let's
8665 ;; store the clocking string.
8666 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8667 (save-excursion
8668 (goto-char org-clock-marker)
8669 (buffer-substring-no-properties (line-beginning-position)
8670 (point)))))
8671 start beg end stars re re2
8672 txt what tmp)
8673 ;; Find beginning and end of region to sort
8674 (cond
8675 ((org-region-active-p)
8676 ;; we will sort the region
8677 (setq end (region-end)
8678 what "region")
8679 (goto-char (region-beginning))
8680 (if (not (org-at-heading-p)) (outline-next-heading))
8681 (setq start (point)))
8682 ((or (org-at-heading-p)
8683 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8684 ;; we will sort the children of the current headline
8685 (org-back-to-heading)
8686 (setq start (point)
8687 end (progn (org-end-of-subtree t t)
8688 (or (bolp) (insert "\n"))
8689 (when (>= (org-back-over-empty-lines) 1)
8690 (forward-line 1))
8691 (point))
8692 what "children")
8693 (goto-char start)
8694 (show-subtree)
8695 (outline-next-heading))
8697 ;; we will sort the top-level entries in this file
8698 (goto-char (point-min))
8699 (or (org-at-heading-p) (outline-next-heading))
8700 (setq start (point))
8701 (goto-char (point-max))
8702 (beginning-of-line 1)
8703 (when (looking-at ".*?\\S-")
8704 ;; File ends in a non-white line
8705 (end-of-line 1)
8706 (insert "\n"))
8707 (setq end (point-max))
8708 (setq what "top-level")
8709 (goto-char start)
8710 (show-all)))
8712 (setq beg (point))
8713 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8715 (looking-at "\\(\\*+\\)")
8716 (setq stars (match-string 1)
8717 re (concat "^" (regexp-quote stars) " +")
8718 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8719 txt (buffer-substring beg end))
8720 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8721 (if (and (not (equal stars "*")) (string-match re2 txt))
8722 (user-error "Region to sort contains a level above the first entry"))
8724 (unless sorting-type
8725 (message
8726 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8727 [t]ime [s]cheduled [d]eadline [c]reated
8728 A/N/P/R/O/F/T/S/D/C means reversed:"
8729 what)
8730 (setq sorting-type (read-char-exclusive))
8732 (unless getkey-func
8733 (and (= (downcase sorting-type) ?f)
8734 (setq getkey-func
8735 (org-icompleting-read "Sort using function: "
8736 obarray 'fboundp t nil nil))
8737 (setq getkey-func (intern getkey-func))))
8739 (and (= (downcase sorting-type) ?r)
8740 (not property)
8741 (setq property
8742 (org-icompleting-read "Property: "
8743 (mapcar 'list (org-buffer-property-keys t))
8744 nil t))))
8746 (message "Sorting entries...")
8748 (save-restriction
8749 (narrow-to-region start end)
8750 (let ((dcst (downcase sorting-type))
8751 (case-fold-search nil)
8752 (now (current-time)))
8753 (sort-subr
8754 (/= dcst sorting-type)
8755 ;; This function moves to the beginning character of the "record" to
8756 ;; be sorted.
8757 (lambda nil
8758 (if (re-search-forward re nil t)
8759 (goto-char (match-beginning 0))
8760 (goto-char (point-max))))
8761 ;; This function moves to the last character of the "record" being
8762 ;; sorted.
8763 (lambda nil
8764 (save-match-data
8765 (condition-case nil
8766 (outline-forward-same-level 1)
8767 (error
8768 (goto-char (point-max))))))
8769 ;; This function returns the value that gets sorted against.
8770 (lambda nil
8771 (cond
8772 ((= dcst ?n)
8773 (if (looking-at org-complex-heading-regexp)
8774 (string-to-number (org-sort-remove-invisible (match-string 4)))
8775 nil))
8776 ((= dcst ?a)
8777 (if (looking-at org-complex-heading-regexp)
8778 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8779 nil))
8780 ((= dcst ?t)
8781 (let ((end (save-excursion (outline-next-heading) (point))))
8782 (if (or (re-search-forward org-ts-regexp end t)
8783 (re-search-forward org-ts-regexp-both end t))
8784 (org-time-string-to-seconds (match-string 0))
8785 (float-time now))))
8786 ((= dcst ?c)
8787 (let ((end (save-excursion (outline-next-heading) (point))))
8788 (if (re-search-forward
8789 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8790 end t)
8791 (org-time-string-to-seconds (match-string 0))
8792 (float-time now))))
8793 ((= dcst ?s)
8794 (let ((end (save-excursion (outline-next-heading) (point))))
8795 (if (re-search-forward org-scheduled-time-regexp end t)
8796 (org-time-string-to-seconds (match-string 1))
8797 (float-time now))))
8798 ((= dcst ?d)
8799 (let ((end (save-excursion (outline-next-heading) (point))))
8800 (if (re-search-forward org-deadline-time-regexp end t)
8801 (org-time-string-to-seconds (match-string 1))
8802 (float-time now))))
8803 ((= dcst ?p)
8804 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8805 (string-to-char (match-string 2))
8806 org-default-priority))
8807 ((= dcst ?r)
8808 (or (org-entry-get nil property) ""))
8809 ((= dcst ?o)
8810 (if (looking-at org-complex-heading-regexp)
8811 (- 9999 (length (member (match-string 2)
8812 org-todo-keywords-1)))))
8813 ((= dcst ?f)
8814 (if getkey-func
8815 (progn
8816 (setq tmp (funcall getkey-func))
8817 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8818 tmp)
8819 (error "Invalid key function `%s'" getkey-func)))
8820 (t (error "Invalid sorting type `%c'" sorting-type))))
8822 (cond
8823 ((= dcst ?a) 'string<)
8824 ((= dcst ?f) compare-func)
8825 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8826 (run-hooks 'org-after-sorting-entries-or-items-hook)
8827 ;; Reset the clock marker if needed
8828 (when cmstr
8829 (save-excursion
8830 (goto-char start)
8831 (search-forward cmstr nil t)
8832 (move-marker org-clock-marker (point))))
8833 (message "Sorting entries...done")))
8835 (defun org-do-sort (table what &optional with-case sorting-type)
8836 "Sort TABLE of WHAT according to SORTING-TYPE.
8837 The user will be prompted for the SORTING-TYPE if the call to this
8838 function does not specify it. WHAT is only for the prompt, to indicate
8839 what is being sorted. The sorting key will be extracted from
8840 the car of the elements of the table.
8841 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8842 (unless sorting-type
8843 (message
8844 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8845 what)
8846 (setq sorting-type (read-char-exclusive)))
8847 (let ((dcst (downcase sorting-type))
8848 extractfun comparefun)
8849 ;; Define the appropriate functions
8850 (cond
8851 ((= dcst ?n)
8852 (setq extractfun 'string-to-number
8853 comparefun (if (= dcst sorting-type) '< '>)))
8854 ((= dcst ?a)
8855 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8856 (lambda(x) (downcase (org-sort-remove-invisible x))))
8857 comparefun (if (= dcst sorting-type)
8858 'string<
8859 (lambda (a b) (and (not (string< a b))
8860 (not (string= a b)))))))
8861 ((= dcst ?t)
8862 (setq extractfun
8863 (lambda (x)
8864 (if (or (string-match org-ts-regexp x)
8865 (string-match org-ts-regexp-both x))
8866 (float-time
8867 (org-time-string-to-time (match-string 0 x)))
8869 comparefun (if (= dcst sorting-type) '< '>)))
8870 (t (error "Invalid sorting type `%c'" sorting-type)))
8872 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8873 table)
8874 (lambda (a b) (funcall comparefun (car a) (car b))))))
8877 ;;; The orgstruct minor mode
8879 ;; Define a minor mode which can be used in other modes in order to
8880 ;; integrate the org-mode structure editing commands.
8882 ;; This is really a hack, because the org-mode structure commands use
8883 ;; keys which normally belong to the major mode. Here is how it
8884 ;; works: The minor mode defines all the keys necessary to operate the
8885 ;; structure commands, but wraps the commands into a function which
8886 ;; tests if the cursor is currently at a headline or a plain list
8887 ;; item. If that is the case, the structure command is used,
8888 ;; temporarily setting many Org-mode variables like regular
8889 ;; expressions for filling etc. However, when any of those keys is
8890 ;; used at a different location, function uses `key-binding' to look
8891 ;; up if the key has an associated command in another currently active
8892 ;; keymap (minor modes, major mode, global), and executes that
8893 ;; command. There might be problems if any of the keys is otherwise
8894 ;; used as a prefix key.
8896 (defcustom orgstruct-heading-prefix-regexp ""
8897 "Regexp that matches the custom prefix of Org headlines in
8898 orgstruct(++)-mode."
8899 :group 'org
8900 :version "24.4"
8901 :package-version '(Org . "8.3")
8902 :type 'regexp)
8903 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8905 (defcustom orgstruct-setup-hook nil
8906 "Hook run after orgstruct-mode-map is filled."
8907 :group 'org
8908 :version "24.4"
8909 :package-version '(Org . "8.0")
8910 :type 'hook)
8912 (defvar orgstruct-initialized nil)
8914 (defvar org-local-vars nil
8915 "List of local variables, for use by `orgstruct-mode'.")
8917 ;;;###autoload
8918 (define-minor-mode orgstruct-mode
8919 "Toggle the minor mode `orgstruct-mode'.
8920 This mode is for using Org-mode structure commands in other
8921 modes. The following keys behave as if Org-mode were active, if
8922 the cursor is on a headline, or on a plain list item (both as
8923 defined by Org-mode)."
8924 nil " OrgStruct" (make-sparse-keymap)
8925 (funcall (if orgstruct-mode
8926 'add-to-invisibility-spec
8927 'remove-from-invisibility-spec)
8928 '(outline . t))
8929 (when orgstruct-mode
8930 (org-load-modules-maybe)
8931 (unless orgstruct-initialized
8932 (orgstruct-setup)
8933 (setq orgstruct-initialized t))))
8935 ;;;###autoload
8936 (defun turn-on-orgstruct ()
8937 "Unconditionally turn on `orgstruct-mode'."
8938 (orgstruct-mode 1))
8940 (defvar org-fb-vars nil)
8941 (make-variable-buffer-local 'org-fb-vars)
8942 (defun orgstruct++-mode (&optional arg)
8943 "Toggle `orgstruct-mode', the enhanced version of it.
8944 In addition to setting orgstruct-mode, this also exports all
8945 indentation and autofilling variables from org-mode into the
8946 buffer. It will also recognize item context in multiline items."
8947 (interactive "P")
8948 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8949 (if (< arg 1)
8950 (progn (orgstruct-mode -1)
8951 (mapc (lambda(v)
8952 (org-set-local (car v)
8953 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8954 org-fb-vars))
8955 (orgstruct-mode 1)
8956 (setq org-fb-vars nil)
8957 (unless org-local-vars
8958 (setq org-local-vars (org-get-local-variables)))
8959 (let (var val)
8960 (mapc
8961 (lambda (x)
8962 (when (string-match
8963 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8964 (symbol-name (car x)))
8965 (setq var (car x) val (nth 1 x))
8966 (push (list var `(quote ,(eval var))) org-fb-vars)
8967 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8968 org-local-vars)
8969 (org-set-local 'orgstruct-is-++ t))))
8971 (defvar orgstruct-is-++ nil
8972 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8973 (make-variable-buffer-local 'orgstruct-is-++)
8975 ;;;###autoload
8976 (defun turn-on-orgstruct++ ()
8977 "Unconditionally turn on `orgstruct++-mode'."
8978 (orgstruct++-mode 1))
8980 (defun orgstruct-error ()
8981 "Error when there is no default binding for a structure key."
8982 (interactive)
8983 (funcall (if (fboundp 'user-error)
8984 'user-error
8985 'error)
8986 "This key has no function outside structure elements"))
8988 (defun orgstruct-setup ()
8989 "Setup orgstruct keymap."
8990 (dolist (cell '((org-demote . t)
8991 (org-metaleft . t)
8992 (org-metaright . t)
8993 (org-promote . t)
8994 (org-shiftmetaleft . t)
8995 (org-shiftmetaright . t)
8996 org-backward-element
8997 org-backward-heading-same-level
8998 org-ctrl-c-ret
8999 org-ctrl-c-minus
9000 org-ctrl-c-star
9001 org-cycle
9002 org-forward-heading-same-level
9003 org-insert-heading
9004 org-insert-heading-respect-content
9005 org-kill-note-or-show-branches
9006 org-mark-subtree
9007 org-meta-return
9008 org-metadown
9009 org-metaup
9010 org-narrow-to-subtree
9011 org-promote-subtree
9012 org-reveal
9013 org-shiftdown
9014 org-shiftleft
9015 org-shiftmetadown
9016 org-shiftmetaup
9017 org-shiftright
9018 org-shifttab
9019 org-shifttab
9020 org-shiftup
9021 org-show-subtree
9022 org-sort
9023 org-up-element
9024 outline-demote
9025 outline-next-visible-heading
9026 outline-previous-visible-heading
9027 outline-promote
9028 outline-up-heading
9029 show-children))
9030 (let ((f (or (car-safe cell) cell))
9031 (disable-when-heading-prefix (cdr-safe cell)))
9032 (when (fboundp f)
9033 (let ((new-bindings))
9034 (dolist (binding (nconc (where-is-internal f org-mode-map)
9035 (where-is-internal f outline-mode-map)))
9036 (push binding new-bindings)
9037 ;; TODO use local-function-key-map
9038 (dolist (rep '(("<tab>" . "TAB")
9039 ("<return>" . "RET")
9040 ("<escape>" . "ESC")
9041 ("<delete>" . "DEL")))
9042 (setq binding (read-kbd-macro
9043 (let ((case-fold-search))
9044 (replace-regexp-in-string
9045 (regexp-quote (cdr rep))
9046 (car rep)
9047 (key-description binding)))))
9048 (pushnew binding new-bindings :test 'equal)))
9049 (dolist (binding new-bindings)
9050 (let ((key (lookup-key orgstruct-mode-map binding)))
9051 (when (or (not key) (numberp key))
9052 (condition-case nil
9053 (org-defkey orgstruct-mode-map
9054 binding
9055 (orgstruct-make-binding f binding disable-when-heading-prefix))
9056 (error nil)))))))))
9057 (run-hooks 'orgstruct-setup-hook))
9059 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9060 "Create a function for binding in the structure minor mode.
9061 FUN is the command to call inside a table. KEY is the key that
9062 should be checked in for a command to execute outside of tables.
9063 Non-nil `disable-when-heading-prefix' means to disable the command
9064 if `orgstruct-heading-prefix-regexp' is not empty."
9065 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9066 (let ((nname name)
9067 (i 0))
9068 (while (fboundp (intern nname))
9069 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9070 (setq name (intern nname)))
9071 (eval
9072 (let ((bindings '((org-heading-regexp
9073 (concat "^"
9074 orgstruct-heading-prefix-regexp
9075 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9076 (org-outline-regexp
9077 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9078 (org-outline-regexp-bol
9079 (concat "^" org-outline-regexp))
9080 (outline-regexp org-outline-regexp)
9081 (outline-heading-end-regexp "\n")
9082 (outline-level 'org-outline-level)
9083 (outline-heading-alist))))
9084 `(defun ,name (arg)
9085 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9086 "Outside of structure, run the binding of `"
9087 (key-description key) "'."
9088 (when disable-when-heading-prefix
9089 (concat
9090 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9091 "back to the default binding due to limitations of Org's implementation of\n"
9092 "`" (symbol-name fun) "'.")))
9093 (interactive "p")
9094 (let* ((disable
9095 ,(and disable-when-heading-prefix
9096 '(not (string= orgstruct-heading-prefix-regexp ""))))
9097 (fallback
9098 (or disable
9099 (not
9100 (let* ,bindings
9101 (org-context-p 'headline 'item
9102 ,(when (memq fun
9103 '(org-insert-heading
9104 org-insert-heading-respect-content
9105 org-meta-return))
9106 '(when orgstruct-is-++
9107 'item-body))))))))
9108 (if fallback
9109 (let* ((orgstruct-mode)
9110 (binding
9111 (let ((key ,key))
9112 (catch 'exit
9113 (dolist
9114 (rep
9115 '(nil
9116 ("<\\([^>]*\\)tab>" . "\\1TAB")
9117 ("<\\([^>]*\\)return>" . "\\1RET")
9118 ("<\\([^>]*\\)escape>" . "\\1ESC")
9119 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9120 nil)
9121 (when rep
9122 (setq key (read-kbd-macro
9123 (let ((case-fold-search))
9124 (replace-regexp-in-string
9125 (car rep)
9126 (cdr rep)
9127 (key-description key))))))
9128 (when (key-binding key)
9129 (throw 'exit (key-binding key))))))))
9130 (if (keymapp binding)
9131 (org-set-transient-map binding)
9132 (let ((func (or binding
9133 (unless disable
9134 'orgstruct-error))))
9135 (when func
9136 (call-interactively func)))))
9137 (org-run-like-in-org-mode
9138 (lambda ()
9139 (interactive)
9140 (let* ,bindings
9141 (call-interactively ',fun)))))))))
9142 name))
9144 (defun org-contextualize-keys (alist contexts)
9145 "Return valid elements in ALIST depending on CONTEXTS.
9147 `org-agenda-custom-commands' or `org-capture-templates' are the
9148 values used for ALIST, and `org-agenda-custom-commands-contexts'
9149 or `org-capture-templates-contexts' are the associated contexts
9150 definitions."
9151 (let ((contexts
9152 ;; normalize contexts
9153 (mapcar
9154 (lambda(c) (cond ((listp (cadr c))
9155 (list (car c) (car c) (cadr c)))
9156 ((string= "" (cadr c))
9157 (list (car c) (car c) (caddr c)))
9158 (t c)))
9159 contexts))
9160 (a alist) r s)
9161 ;; loop over all commands or templates
9162 (dolist (c a)
9163 (let (vrules repl)
9164 (cond
9165 ((not (assoc (car c) contexts))
9166 (push c r))
9167 ((and (assoc (car c) contexts)
9168 (setq vrules (org-contextualize-validate-key
9169 (car c) contexts)))
9170 (mapc (lambda (vr)
9171 (when (not (equal (car vr) (cadr vr)))
9172 (setq repl vr)))
9173 vrules)
9174 (if (not repl) (push c r)
9175 (push (cadr repl) s)
9176 (push
9177 (cons (car c)
9178 (cdr (or (assoc (cadr repl) alist)
9179 (error "Undefined key `%s' as contextual replacement for `%s'"
9180 (cadr repl) (car c)))))
9181 r))))))
9182 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9183 (delq
9185 (delete-dups
9186 (mapcar (lambda (x)
9187 (let ((tpl (car x)))
9188 (when (not (delq
9190 (mapcar (lambda (y)
9191 (equal y tpl))
9192 s)))
9193 x)))
9194 (reverse r))))))
9196 (defun org-contextualize-validate-key (key contexts)
9197 "Check CONTEXTS for agenda or capture KEY."
9198 (let (rr res)
9199 (dolist (r contexts)
9200 (mapc
9201 (lambda (rr)
9202 (when
9203 (and (equal key (car r))
9204 (if (functionp rr) (funcall rr)
9205 (or (and (eq (car rr) 'in-file)
9206 (buffer-file-name)
9207 (string-match (cdr rr) (buffer-file-name)))
9208 (and (eq (car rr) 'in-mode)
9209 (string-match (cdr rr) (symbol-name major-mode)))
9210 (and (eq (car rr) 'in-buffer)
9211 (string-match (cdr rr) (buffer-name)))
9212 (when (and (eq (car rr) 'not-in-file)
9213 (buffer-file-name))
9214 (not (string-match (cdr rr) (buffer-file-name))))
9215 (when (eq (car rr) 'not-in-mode)
9216 (not (string-match (cdr rr) (symbol-name major-mode))))
9217 (when (eq (car rr) 'not-in-buffer)
9218 (not (string-match (cdr rr) (buffer-name)))))))
9219 (push r res)))
9220 (car (last r))))
9221 (delete-dups (delq nil res))))
9223 (defun org-context-p (&rest contexts)
9224 "Check if local context is any of CONTEXTS.
9225 Possible values in the list of contexts are `table', `headline', and `item'."
9226 (let ((pos (point)))
9227 (goto-char (point-at-bol))
9228 (prog1 (or (and (memq 'table contexts)
9229 (looking-at "[ \t]*|"))
9230 (and (memq 'headline contexts)
9231 (looking-at org-outline-regexp))
9232 (and (memq 'item contexts)
9233 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9234 (and (memq 'item-body contexts)
9235 (org-in-item-p)))
9236 (goto-char pos))))
9238 (defun org-get-local-variables ()
9239 "Return a list of all local variables in an Org mode buffer."
9240 (let (varlist)
9241 (with-current-buffer (get-buffer-create "*Org tmp*")
9242 (erase-buffer)
9243 (org-mode)
9244 (setq varlist (buffer-local-variables)))
9245 (kill-buffer "*Org tmp*")
9246 (delq nil
9247 (mapcar
9248 (lambda (x)
9249 (setq x
9250 (if (symbolp x)
9251 (list x)
9252 (list (car x) (cdr x))))
9253 (if (and (not (get (car x) 'org-state))
9254 (string-match
9255 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9256 (symbol-name (car x))))
9257 x nil))
9258 varlist))))
9260 (defun org-clone-local-variables (from-buffer &optional regexp)
9261 "Clone local variables from FROM-BUFFER.
9262 Optional argument REGEXP selects variables to clone."
9263 (mapc
9264 (lambda (pair)
9265 (and (symbolp (car pair))
9266 (or (null regexp)
9267 (string-match regexp (symbol-name (car pair))))
9268 (set (make-local-variable (car pair))
9269 (cdr pair))))
9270 (buffer-local-variables from-buffer)))
9272 ;;;###autoload
9273 (defun org-run-like-in-org-mode (cmd)
9274 "Run a command, pretending that the current buffer is in Org-mode.
9275 This will temporarily bind local variables that are typically bound in
9276 Org-mode to the values they have in Org-mode, and then interactively
9277 call CMD."
9278 (org-load-modules-maybe)
9279 (unless org-local-vars
9280 (setq org-local-vars (org-get-local-variables)))
9281 (let (binds)
9282 (dolist (var org-local-vars)
9283 (when (or (not (boundp (car var)))
9284 (eq (symbol-value (car var))
9285 (default-value (car var))))
9286 (push (list (car var) `(quote ,(cadr var))) binds)))
9287 (eval `(let ,binds
9288 (call-interactively (quote ,cmd))))))
9290 ;;;; Archiving
9292 (defun org-get-category (&optional pos force-refresh)
9293 "Get the category applying to position POS."
9294 (save-match-data
9295 (if force-refresh (org-refresh-category-properties))
9296 (let ((pos (or pos (point))))
9297 (or (get-text-property pos 'org-category)
9298 (progn (org-refresh-category-properties)
9299 (get-text-property pos 'org-category))))))
9301 (defun org-refresh-category-properties ()
9302 "Refresh category text properties in the buffer."
9303 (let ((case-fold-search t)
9304 (inhibit-read-only t)
9305 (def-cat (cond
9306 ((null org-category)
9307 (if buffer-file-name
9308 (file-name-sans-extension
9309 (file-name-nondirectory buffer-file-name))
9310 "???"))
9311 ((symbolp org-category) (symbol-name org-category))
9312 (t org-category)))
9313 beg end cat pos optionp)
9314 (org-with-silent-modifications
9315 (save-excursion
9316 (save-restriction
9317 (widen)
9318 (goto-char (point-min))
9319 (put-text-property (point) (point-max) 'org-category def-cat)
9320 (while (re-search-forward
9321 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9322 (setq pos (match-end 0)
9323 optionp (equal (char-after (match-beginning 0)) ?#)
9324 cat (org-trim (match-string 2)))
9325 (if optionp
9326 (setq beg (point-at-bol) end (point-max))
9327 (org-back-to-heading t)
9328 (setq beg (point) end (org-end-of-subtree t t)))
9329 (put-text-property beg end 'org-category cat)
9330 (put-text-property beg end 'org-category-position beg)
9331 (goto-char pos)))))))
9333 (defun org-refresh-properties (dprop tprop)
9334 "Refresh buffer text properties.
9335 DPROP is the drawer property and TPROP is the corresponding text
9336 property to set."
9337 (let ((case-fold-search t)
9338 (inhibit-read-only t) p)
9339 (org-with-silent-modifications
9340 (save-excursion
9341 (save-restriction
9342 (widen)
9343 (goto-char (point-min))
9344 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9345 (setq p (org-match-string-no-properties 1))
9346 (save-excursion
9347 (org-back-to-heading t)
9348 (put-text-property
9349 (point-at-bol) (or (outline-next-heading) (point-max)) tprop p))))))))
9352 ;;;; Link Stuff
9354 ;;; Link abbreviations
9356 (defun org-link-expand-abbrev (link)
9357 "Apply replacements as defined in `org-link-abbrev-alist'."
9358 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9359 (let* ((key (match-string 1 link))
9360 (as (or (assoc key org-link-abbrev-alist-local)
9361 (assoc key org-link-abbrev-alist)))
9362 (tag (and (match-end 2) (match-string 3 link)))
9363 rpl)
9364 (if (not as)
9365 link
9366 (setq rpl (cdr as))
9367 (cond
9368 ((symbolp rpl) (funcall rpl tag))
9369 ((string-match "%(\\([^)]+\\))" rpl)
9370 (replace-match
9371 (save-match-data
9372 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9373 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9374 ((string-match "%h" rpl)
9375 (replace-match (url-hexify-string (or tag "")) t t rpl))
9376 (t (concat rpl tag)))))
9377 link))
9379 ;;; Storing and inserting links
9381 (defvar org-insert-link-history nil
9382 "Minibuffer history for links inserted with `org-insert-link'.")
9384 (defvar org-stored-links nil
9385 "Contains the links stored with `org-store-link'.")
9387 (defvar org-store-link-plist nil
9388 "Plist with info about the most recently link created with `org-store-link'.")
9390 (defvar org-link-protocols nil
9391 "Link protocols added to Org-mode using `org-add-link-type'.")
9393 (defvar org-store-link-functions nil
9394 "List of functions that are called to create and store a link.
9395 Each function will be called in turn until one returns a non-nil
9396 value. Each function should check if it is responsible for creating
9397 this link (for example by looking at the major mode).
9398 If not, it must exit and return nil.
9399 If yes, it should return a non-nil value after a calling
9400 `org-store-link-props' with a list of properties and values.
9401 Special properties are:
9403 :type The link prefix, like \"http\". This must be given.
9404 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9405 This is obligatory as well.
9406 :description Optional default description for the second pair
9407 of brackets in an Org-mode link. The user can still change
9408 this when inserting this link into an Org-mode buffer.
9410 In addition to these, any additional properties can be specified
9411 and then used in capture templates.")
9413 (defun org-add-link-type (type &optional follow export)
9414 "Add TYPE to the list of `org-link-types'.
9415 Re-compute all regular expressions depending on `org-link-types'
9417 FOLLOW and EXPORT are two functions.
9419 FOLLOW should take the link path as the single argument and do whatever
9420 is necessary to follow the link, for example find a file or display
9421 a mail message.
9423 EXPORT should format the link path for export to one of the export formats.
9424 It should be a function accepting three arguments:
9426 path the path of the link, the text after the prefix (like \"http:\")
9427 desc the description of the link, if any, or a description added by
9428 org-export-normalize-links if there is none
9429 format the export format, a symbol like `html' or `latex' or `ascii'..
9431 The function may use the FORMAT information to return different values
9432 depending on the format. The return value will be put literally into
9433 the exported file. If the return value is nil, this means Org should
9434 do what it normally does with links which do not have EXPORT defined.
9436 Org-mode has a built-in default for exporting links. If you are happy with
9437 this default, there is no need to define an export function for the link
9438 type. For a simple example of an export function, see `org-bbdb.el'."
9439 (add-to-list 'org-link-types type t)
9440 (org-make-link-regexps)
9441 (if (assoc type org-link-protocols)
9442 (setcdr (assoc type org-link-protocols) (list follow export))
9443 (push (list type follow export) org-link-protocols)))
9445 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9446 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9448 ;;;###autoload
9449 (defun org-store-link (arg)
9450 "\\<org-mode-map>Store an org-link to the current location.
9451 This link is added to `org-stored-links' and can later be inserted
9452 into an org-buffer with \\[org-insert-link].
9454 For some link types, a prefix arg is interpreted.
9455 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9456 For file links, arg negates `org-context-in-file-links'.
9458 A double prefix arg force skipping storing functions that are not
9459 part of Org's core.
9461 A triple prefix arg force storing a link for each line in the
9462 active region."
9463 (interactive "P")
9464 (org-load-modules-maybe)
9465 (if (and (equal arg '(64)) (org-region-active-p))
9466 (save-excursion
9467 (let ((end (region-end)))
9468 (goto-char (region-beginning))
9469 (set-mark (point))
9470 (while (< (point-at-eol) end)
9471 (move-end-of-line 1) (activate-mark)
9472 (let (current-prefix-arg)
9473 (call-interactively 'org-store-link))
9474 (move-beginning-of-line 2)
9475 (set-mark (point)))))
9476 (org-with-limited-levels
9477 (setq org-store-link-plist nil)
9478 (let (link cpltxt desc description search
9479 txt custom-id agenda-link sfuns sfunsn)
9480 (cond
9482 ;; Store a link using an external link type
9483 ((and (not (equal arg '(16)))
9484 (setq sfuns
9485 (delq
9486 nil (mapcar (lambda (f)
9487 (let (fs) (if (funcall f) (push f fs))))
9488 org-store-link-functions))
9489 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9490 (or (and (cdr sfuns)
9491 (funcall (intern
9492 (completing-read
9493 "Which function for creating the link? "
9494 sfunsn nil t (car sfunsn)))))
9495 (funcall (caar sfuns)))
9496 (setq link (plist-get org-store-link-plist :link)
9497 desc (or (plist-get org-store-link-plist
9498 :description)
9499 link))))
9501 ;; Store a link from a source code buffer
9502 ((org-src-edit-buffer-p)
9503 (let (label gc)
9504 (while (or (not label)
9505 (save-excursion
9506 (save-restriction
9507 (widen)
9508 (goto-char (point-min))
9509 (re-search-forward
9510 (regexp-quote (format org-coderef-label-format label))
9511 nil t))))
9512 (when label (message "Label exists already") (sit-for 2))
9513 (setq label (read-string "Code line label: " label)))
9514 (end-of-line 1)
9515 (setq link (format org-coderef-label-format label))
9516 (setq gc (- 79 (length link)))
9517 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9518 (insert link)
9519 (setq link (concat "(" label ")") desc nil)))
9521 ;; We are in the agenda, link to referenced location
9522 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9523 (let ((m (or (get-text-property (point) 'org-hd-marker)
9524 (get-text-property (point) 'org-marker))))
9525 (when m
9526 (org-with-point-at m
9527 (setq agenda-link
9528 (if (org-called-interactively-p 'any)
9529 (call-interactively 'org-store-link)
9530 (org-store-link nil)))))))
9532 ((eq major-mode 'calendar-mode)
9533 (let ((cd (calendar-cursor-to-date)))
9534 (setq link
9535 (format-time-string
9536 (car org-time-stamp-formats)
9537 (apply 'encode-time
9538 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9539 nil nil nil))))
9540 (org-store-link-props :type "calendar" :date cd)))
9542 ((eq major-mode 'help-mode)
9543 (setq link (concat "help:" (save-excursion
9544 (goto-char (point-min))
9545 (looking-at "^[^ ]+")
9546 (match-string 0))))
9547 (org-store-link-props :type "help"))
9549 ((eq major-mode 'w3-mode)
9550 (setq cpltxt (if (and (buffer-name)
9551 (not (string-match "Untitled" (buffer-name))))
9552 (buffer-name)
9553 (url-view-url t))
9554 link (url-view-url t))
9555 (org-store-link-props :type "w3" :url (url-view-url t)))
9557 ((eq major-mode 'image-mode)
9558 (setq cpltxt (concat "file:"
9559 (abbreviate-file-name buffer-file-name))
9560 link cpltxt)
9561 (org-store-link-props :type "image" :file buffer-file-name))
9563 ;; In dired, store a link to the file of the current line
9564 ((eq major-mode 'dired-mode)
9565 (let ((file (dired-get-filename nil t)))
9566 (setq file (if file
9567 (abbreviate-file-name
9568 (expand-file-name (dired-get-filename nil t)))
9569 ;; otherwise, no file so use current directory.
9570 default-directory))
9571 (setq cpltxt (concat "file:" file)
9572 link cpltxt)))
9574 ((setq search (run-hook-with-args-until-success
9575 'org-create-file-search-functions))
9576 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9577 "::" search))
9578 (setq cpltxt (or description link)))
9580 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9581 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9582 (cond
9583 ;; Store a link using the target at point
9584 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9585 (setq cpltxt
9586 (concat "file:"
9587 (abbreviate-file-name
9588 (buffer-file-name (buffer-base-buffer)))
9589 "::" (match-string 1))
9590 link cpltxt))
9591 ((and (featurep 'org-id)
9592 (or (eq org-id-link-to-org-use-id t)
9593 (and (org-called-interactively-p 'any)
9594 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9595 (and (eq org-id-link-to-org-use-id
9596 'create-if-interactive-and-no-custom-id)
9597 (not custom-id))))
9598 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9599 ;; Store a link using the ID at point
9600 (setq link (condition-case nil
9601 (prog1 (org-id-store-link)
9602 (setq desc (or (plist-get org-store-link-plist
9603 :description)
9604 "")))
9605 (error
9606 ;; Probably before first headline, link only to file
9607 (concat "file:"
9608 (abbreviate-file-name
9609 (buffer-file-name (buffer-base-buffer))))))))
9611 ;; Just link to current headline
9612 (setq cpltxt (concat "file:"
9613 (abbreviate-file-name
9614 (buffer-file-name (buffer-base-buffer)))))
9615 ;; Add a context search string
9616 (when (org-xor org-context-in-file-links arg)
9617 (let* ((ee (org-element-at-point))
9618 (et (org-element-type ee))
9619 (ev (plist-get (cadr ee) :value))
9620 (ek (plist-get (cadr ee) :key))
9621 (eok (and (stringp ek) (string-match "name" ek))))
9622 (setq txt (cond
9623 ((org-at-heading-p) nil)
9624 ((and (eq et 'keyword) eok) ev)
9625 ((org-region-active-p)
9626 (buffer-substring (region-beginning) (region-end)))))
9627 (when (or (null txt) (string-match "\\S-" txt))
9628 (setq cpltxt
9629 (concat cpltxt "::"
9630 (condition-case nil
9631 (org-make-org-heading-search-string txt)
9632 (error "")))
9633 desc (or (and (eq et 'keyword) eok ev)
9634 (nth 4 (ignore-errors (org-heading-components)))
9635 "NONE")))))
9636 (if (string-match "::\\'" cpltxt)
9637 (setq cpltxt (substring cpltxt 0 -2)))
9638 (setq link cpltxt))))
9640 ((buffer-file-name (buffer-base-buffer))
9641 ;; Just link to this file here.
9642 (setq cpltxt (concat "file:"
9643 (abbreviate-file-name
9644 (buffer-file-name (buffer-base-buffer)))))
9645 ;; Add a context string.
9646 (when (org-xor org-context-in-file-links arg)
9647 (setq txt (if (org-region-active-p)
9648 (buffer-substring (region-beginning) (region-end))
9649 (buffer-substring (point-at-bol) (point-at-eol))))
9650 ;; Only use search option if there is some text.
9651 (when (string-match "\\S-" txt)
9652 (setq cpltxt
9653 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9654 desc "NONE")))
9655 (setq link cpltxt))
9657 ((org-called-interactively-p 'interactive)
9658 (user-error "No method for storing a link from this buffer"))
9660 (t (setq link nil)))
9662 ;; We're done setting link and desc, clean up
9663 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9664 (setq link (or link cpltxt)
9665 desc (or desc cpltxt))
9666 (cond ((equal desc "NONE") (setq desc nil))
9667 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9668 (let ((d0 (match-string 3 desc))
9669 (p0 (match-string 5 desc)))
9670 (setq desc
9671 (replace-regexp-in-string
9672 org-bracket-link-regexp
9673 (concat (or p0 d0)
9674 (if (equal (length (match-string 0 desc))
9675 (length desc)) "*" "")) desc)))))
9677 ;; Return the link
9678 (if (not (and (or (org-called-interactively-p 'any)
9679 executing-kbd-macro)
9680 link))
9681 (or agenda-link (and link (org-make-link-string link desc)))
9682 (push (list link desc) org-stored-links)
9683 (message "Stored: %s" (or desc link))
9684 (when custom-id
9685 (setq link (concat "file:" (abbreviate-file-name
9686 (buffer-file-name)) "::#" custom-id))
9687 (push (list link desc) org-stored-links))
9688 (car org-stored-links))))))
9690 (defun org-store-link-props (&rest plist)
9691 "Store link properties, extract names and addresses."
9692 (let (x adr)
9693 (when (setq x (plist-get plist :from))
9694 (setq adr (mail-extract-address-components x))
9695 (setq plist (plist-put plist :fromname (car adr)))
9696 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9697 (when (setq x (plist-get plist :to))
9698 (setq adr (mail-extract-address-components x))
9699 (setq plist (plist-put plist :toname (car adr)))
9700 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9701 (let ((from (plist-get plist :from))
9702 (to (plist-get plist :to)))
9703 (when (and from to org-from-is-user-regexp)
9704 (setq plist
9705 (plist-put plist :fromto
9706 (if (string-match org-from-is-user-regexp from)
9707 (concat "to %t")
9708 (concat "from %f"))))))
9709 (setq org-store-link-plist plist))
9711 (defun org-add-link-props (&rest plist)
9712 "Add these properties to the link property list."
9713 (let (key value)
9714 (while plist
9715 (setq key (pop plist) value (pop plist))
9716 (setq org-store-link-plist
9717 (plist-put org-store-link-plist key value)))))
9719 (defun org-email-link-description (&optional fmt)
9720 "Return the description part of an email link.
9721 This takes information from `org-store-link-plist' and formats it
9722 according to FMT (default from `org-email-link-description-format')."
9723 (setq fmt (or fmt org-email-link-description-format))
9724 (let* ((p org-store-link-plist)
9725 (to (plist-get p :toaddress))
9726 (from (plist-get p :fromaddress))
9727 (table
9728 (list
9729 (cons "%c" (plist-get p :fromto))
9730 (cons "%F" (plist-get p :from))
9731 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9732 (cons "%T" (plist-get p :to))
9733 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9734 (cons "%s" (plist-get p :subject))
9735 (cons "%d" (plist-get p :date))
9736 (cons "%m" (plist-get p :message-id)))))
9737 (when (string-match "%c" fmt)
9738 ;; Check if the user wrote this message
9739 (if (and org-from-is-user-regexp from to
9740 (save-match-data (string-match org-from-is-user-regexp from)))
9741 (setq fmt (replace-match "to %t" t t fmt))
9742 (setq fmt (replace-match "from %f" t t fmt))))
9743 (org-replace-escapes fmt table)))
9745 (defun org-make-org-heading-search-string (&optional string)
9746 "Make search string for the current headline or STRING."
9747 (let ((s (or string
9748 (and (derived-mode-p 'org-mode)
9749 (save-excursion
9750 (org-back-to-heading t)
9751 (org-element-property :raw-value (org-element-at-point))))))
9752 (lines org-context-in-file-links))
9753 (or string (setq s (concat "*" s))) ; Add * for headlines
9754 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9755 (when (and string (integerp lines) (> lines 0))
9756 (let ((slines (org-split-string s "\n")))
9757 (when (< lines (length slines))
9758 (setq s (mapconcat
9759 'identity
9760 (reverse (nthcdr (- (length slines) lines)
9761 (reverse slines))) "\n")))))
9762 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9764 (defun org-make-link-string (link &optional description)
9765 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9766 (unless (string-match "\\S-" link)
9767 (error "Empty link"))
9768 (when (and description
9769 (stringp description)
9770 (not (string-match "\\S-" description)))
9771 (setq description nil))
9772 (when (stringp description)
9773 ;; Remove brackets from the description, they are fatal.
9774 (while (string-match "\\[" description)
9775 (setq description (replace-match "{" t t description)))
9776 (while (string-match "\\]" description)
9777 (setq description (replace-match "}" t t description))))
9778 (when (equal link description)
9779 ;; No description needed, it is identical
9780 (setq description nil))
9781 (when (and (not description)
9782 (not (string-match (org-image-file-name-regexp) link))
9783 (not (equal link (org-link-escape link))))
9784 (setq description (org-extract-attributes link)))
9785 (setq link
9786 (cond ((string-match (org-image-file-name-regexp) link) link)
9787 ((string-match org-link-types-re link)
9788 (concat (match-string 1 link)
9789 (org-link-escape (substring link (match-end 1)))))
9790 (t (org-link-escape link))))
9791 (concat "[[" link "]"
9792 (if description (concat "[" description "]") "")
9793 "]"))
9795 (defconst org-link-escape-chars
9796 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9797 "List of characters that should be escaped in link.
9798 This is the list that is used for internal purposes.")
9800 (defconst org-link-escape-chars-browser
9801 '(?\ ?\")
9802 "List of escapes for characters that are problematic in links.
9803 This is the list that is used before handing over to the browser.")
9805 (defun org-link-escape (text &optional table merge)
9806 "Return percent escaped representation of TEXT.
9807 TEXT is a string with the text to escape.
9808 Optional argument TABLE is a list with characters that should be
9809 escaped. When nil, `org-link-escape-chars' is used.
9810 If optional argument MERGE is set, merge TABLE into
9811 `org-link-escape-chars'."
9812 (cond
9813 ((and table merge)
9814 (mapc (lambda (defchr)
9815 (unless (member defchr table)
9816 (setq table (cons defchr table)))) org-link-escape-chars))
9817 ((null table)
9818 (setq table org-link-escape-chars)))
9819 (mapconcat
9820 (lambda (char)
9821 (if (or (member char table)
9822 (and (or (< char 32) (= char 37) (> char 126))
9823 org-url-hexify-p))
9824 (mapconcat (lambda (sequence-element)
9825 (format "%%%.2X" sequence-element))
9826 (or (encode-coding-char char 'utf-8)
9827 (error "Unable to percent escape character: %s"
9828 (char-to-string char))) "")
9829 (char-to-string char))) text ""))
9831 (defun org-link-unescape (str)
9832 "Unhex hexified Unicode strings as returned from the JavaScript function
9833 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9834 (unless (and (null str) (string= "" str))
9835 (let ((pos 0) (case-fold-search t) unhexed)
9836 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9837 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9838 (setq str (replace-match unhexed t t str))
9839 (setq pos (+ pos (length unhexed))))))
9840 str)
9842 (defun org-link-unescape-compound (hex)
9843 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9844 Note: this function also decodes single byte encodings like
9845 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9846 (save-match-data
9847 (let* ((bytes (cdr (split-string hex "%")))
9848 (ret "")
9849 (eat 0)
9850 (sum 0))
9851 (while bytes
9852 (let* ((val (string-to-number (pop bytes) 16))
9853 (shift-xor
9854 (if (= 0 eat)
9855 (cond
9856 ((>= val 252) (cons 6 252))
9857 ((>= val 248) (cons 5 248))
9858 ((>= val 240) (cons 4 240))
9859 ((>= val 224) (cons 3 224))
9860 ((>= val 192) (cons 2 192))
9861 (t (cons 0 0)))
9862 (cons 6 128))))
9863 (if (>= val 192) (setq eat (car shift-xor)))
9864 (setq val (logxor val (cdr shift-xor)))
9865 (setq sum (+ (lsh sum (car shift-xor)) val))
9866 (if (> eat 0) (setq eat (- eat 1)))
9867 (cond
9868 ((= 0 eat) ;multi byte
9869 (setq ret (concat ret (org-char-to-string sum)))
9870 (setq sum 0))
9871 ((not bytes) ; single byte(s)
9872 (setq ret (org-link-unescape-single-byte-sequence hex))))
9873 )) ;; end (while bytes
9874 ret )))
9876 (defun org-link-unescape-single-byte-sequence (hex)
9877 "Unhexify hex-encoded single byte character sequences."
9878 (mapconcat (lambda (byte)
9879 (char-to-string (string-to-number byte 16)))
9880 (cdr (split-string hex "%")) ""))
9882 (defun org-xor (a b)
9883 "Exclusive or."
9884 (if a (not b) b))
9886 (defun org-fixup-message-id-for-http (s)
9887 "Replace special characters in a message id, so it can be used in an http query."
9888 (when (string-match "%" s)
9889 (setq s (mapconcat (lambda (c)
9890 (if (eq c ?%)
9891 "%25"
9892 (char-to-string c)))
9893 s "")))
9894 (while (string-match "<" s)
9895 (setq s (replace-match "%3C" t t s)))
9896 (while (string-match ">" s)
9897 (setq s (replace-match "%3E" t t s)))
9898 (while (string-match "@" s)
9899 (setq s (replace-match "%40" t t s)))
9902 (defun org-link-prettify (link)
9903 "Return a human-readable representation of LINK.
9904 The car of LINK must be a raw link the cdr of LINK must be either
9905 a link description or nil."
9906 (let ((desc (or (cadr link) "<no description>")))
9907 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9908 "<" (car link) ">")))
9910 ;;;###autoload
9911 (defun org-insert-link-global ()
9912 "Insert a link like Org-mode does.
9913 This command can be called in any mode to insert a link in Org-mode syntax."
9914 (interactive)
9915 (org-load-modules-maybe)
9916 (org-run-like-in-org-mode 'org-insert-link))
9918 (defun org-insert-all-links (&optional keep)
9919 "Insert all links in `org-stored-links'."
9920 (interactive "P")
9921 (let ((links (copy-sequence org-stored-links)) l)
9922 (while (setq l (if keep (pop links) (pop org-stored-links)))
9923 (insert "- ")
9924 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9925 (insert "\n"))))
9927 (defun org-link-fontify-links-to-this-file ()
9928 "Fontify links to the current file in `org-stored-links'."
9929 (let ((f (buffer-file-name)) a b)
9930 (setq a (mapcar (lambda(l)
9931 (let ((ll (car l)))
9932 (when (and (string-match "^file:\\(.+\\)::" ll)
9933 (equal f (expand-file-name (match-string 1 ll))))
9934 ll)))
9935 org-stored-links))
9936 (when (featurep 'org-id)
9937 (setq b (mapcar (lambda(l)
9938 (let ((ll (car l)))
9939 (when (and (string-match "^id:\\(.+\\)$" ll)
9940 (equal f (expand-file-name
9941 (or (org-id-find-id-file
9942 (match-string 1 ll)) ""))))
9943 ll)))
9944 org-stored-links)))
9945 (mapcar (lambda(l)
9946 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9947 (delq nil (append a b)))))
9949 (defvar org-link-links-in-this-file nil)
9950 (defun org-insert-link (&optional complete-file link-location default-description)
9951 "Insert a link. At the prompt, enter the link.
9953 Completion can be used to insert any of the link protocol prefixes like
9954 http or ftp in use.
9956 The history can be used to select a link previously stored with
9957 `org-store-link'. When the empty string is entered (i.e. if you just
9958 press RET at the prompt), the link defaults to the most recently
9959 stored link. As SPC triggers completion in the minibuffer, you need to
9960 use M-SPC or C-q SPC to force the insertion of a space character.
9962 You will also be prompted for a description, and if one is given, it will
9963 be displayed in the buffer instead of the link.
9965 If there is already a link at point, this command will allow you to edit link
9966 and description parts.
9968 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9969 be selected using completion. The path to the file will be relative to the
9970 current directory if the file is in the current directory or a subdirectory.
9971 Otherwise, the link will be the absolute path as completed in the minibuffer
9972 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9973 option `org-link-file-path-type'.
9975 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9976 the current directory or below.
9978 With three \\[universal-argument] prefixes, negate the meaning of
9979 `org-keep-stored-link-after-insertion'.
9981 If `org-make-link-description-function' is non-nil, this function will be
9982 called with the link target, and the result will be the default
9983 link description.
9985 If the LINK-LOCATION parameter is non-nil, this value will be
9986 used as the link location instead of reading one interactively.
9988 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9989 be used as the default description."
9990 (interactive "P")
9991 (let* ((wcf (current-window-configuration))
9992 (origbuf (current-buffer))
9993 (region (if (org-region-active-p)
9994 (buffer-substring (region-beginning) (region-end))))
9995 (remove (and region (list (region-beginning) (region-end))))
9996 (desc region)
9997 tmphist ; byte-compile incorrectly complains about this
9998 (link link-location)
9999 (abbrevs org-link-abbrev-alist-local)
10000 entry file all-prefixes auto-desc)
10001 (cond
10002 (link-location) ; specified by arg, just use it.
10003 ((org-in-regexp org-bracket-link-regexp 1)
10004 ;; We do have a link at point, and we are going to edit it.
10005 (setq remove (list (match-beginning 0) (match-end 0)))
10006 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10007 (setq link (read-string "Link: "
10008 (org-link-unescape
10009 (org-match-string-no-properties 1)))))
10010 ((or (org-in-regexp org-angle-link-re)
10011 (org-in-regexp org-plain-link-re))
10012 ;; Convert to bracket link
10013 (setq remove (list (match-beginning 0) (match-end 0))
10014 link (read-string "Link: "
10015 (org-remove-angle-brackets (match-string 0)))))
10016 ((member complete-file '((4) (16)))
10017 ;; Completing read for file names.
10018 (setq link (org-file-complete-link complete-file)))
10020 ;; Read link, with completion for stored links.
10021 (org-link-fontify-links-to-this-file)
10022 (org-switch-to-buffer-other-window "*Org Links*")
10023 (with-current-buffer "*Org Links*"
10024 (erase-buffer)
10025 (insert "Insert a link.
10026 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10027 (when org-stored-links
10028 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10029 (insert (mapconcat 'org-link-prettify
10030 (reverse org-stored-links) "\n")))
10031 (goto-char (point-min)))
10032 (let ((cw (selected-window)))
10033 (select-window (get-buffer-window "*Org Links*" 'visible))
10034 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10035 (unless (pos-visible-in-window-p (point-max))
10036 (org-fit-window-to-buffer))
10037 (and (window-live-p cw) (select-window cw)))
10038 ;; Fake a link history, containing the stored links.
10039 (setq tmphist (append (mapcar 'car org-stored-links)
10040 org-insert-link-history))
10041 (setq all-prefixes (append (mapcar 'car abbrevs)
10042 (mapcar 'car org-link-abbrev-alist)
10043 org-link-types))
10044 (unwind-protect
10045 (progn
10046 (setq link
10047 (org-completing-read
10048 "Link: "
10049 (append
10050 (mapcar (lambda (x) (concat x ":"))
10051 all-prefixes)
10052 (mapcar 'car org-stored-links))
10053 nil nil nil
10054 'tmphist
10055 (caar org-stored-links)))
10056 (if (not (string-match "\\S-" link))
10057 (user-error "No link selected"))
10058 (mapc (lambda(l)
10059 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10060 org-stored-links)
10061 (if (or (member link all-prefixes)
10062 (and (equal ":" (substring link -1))
10063 (member (substring link 0 -1) all-prefixes)
10064 (setq link (substring link 0 -1))))
10065 (setq link (with-current-buffer origbuf
10066 (org-link-try-special-completion link)))))
10067 (set-window-configuration wcf)
10068 (kill-buffer "*Org Links*"))
10069 (setq entry (assoc link org-stored-links))
10070 (or entry (push link org-insert-link-history))
10071 (setq desc (or desc (nth 1 entry)))))
10073 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10074 (not org-keep-stored-link-after-insertion))
10075 (setq org-stored-links (delq (assoc link org-stored-links)
10076 org-stored-links)))
10078 (if (and (string-match org-plain-link-re link)
10079 (not (string-match org-ts-regexp link)))
10080 ;; URL-like link, normalize the use of angular brackets.
10081 (setq link (org-remove-angle-brackets link)))
10083 ;; Check if we are linking to the current file with a search
10084 ;; option If yes, simplify the link by using only the search
10085 ;; option.
10086 (when (and buffer-file-name
10087 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10088 (let* ((path (match-string 1 link))
10089 (case-fold-search nil)
10090 (search (match-string 2 link)))
10091 (save-match-data
10092 (if (equal (file-truename buffer-file-name) (file-truename path))
10093 ;; We are linking to this same file, with a search option
10094 (setq link search)))))
10096 ;; Check if we can/should use a relative path. If yes, simplify the link
10097 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10098 (let* ((type (match-string 1 link))
10099 (path (match-string 2 link))
10100 (origpath path)
10101 (case-fold-search nil))
10102 (cond
10103 ((or (eq org-link-file-path-type 'absolute)
10104 (equal complete-file '(16)))
10105 (setq path (abbreviate-file-name (expand-file-name path))))
10106 ((eq org-link-file-path-type 'noabbrev)
10107 (setq path (expand-file-name path)))
10108 ((eq org-link-file-path-type 'relative)
10109 (setq path (file-relative-name path)))
10111 (save-match-data
10112 (if (string-match (concat "^" (regexp-quote
10113 (expand-file-name
10114 (file-name-as-directory
10115 default-directory))))
10116 (expand-file-name path))
10117 ;; We are linking a file with relative path name.
10118 (setq path (substring (expand-file-name path)
10119 (match-end 0)))
10120 (setq path (abbreviate-file-name (expand-file-name path)))))))
10121 (setq link (concat type path))
10122 (if (equal desc origpath)
10123 (setq desc path))))
10125 (if org-make-link-description-function
10126 (setq desc
10127 (or (condition-case nil
10128 (funcall org-make-link-description-function link desc)
10129 (error (progn (message "Can't get link description from `%s'"
10130 (symbol-name org-make-link-description-function))
10131 (sit-for 2) nil)))
10132 (read-string "Description: " default-description)))
10133 (if default-description (setq desc default-description)
10134 (setq desc (or (and auto-desc desc)
10135 (read-string "Description: " desc)))))
10137 (unless (string-match "\\S-" desc) (setq desc nil))
10138 (if remove (apply 'delete-region remove))
10139 (insert (org-make-link-string link desc))))
10141 (defun org-link-try-special-completion (type)
10142 "If there is completion support for link type TYPE, offer it."
10143 (let ((fun (intern (concat "org-" type "-complete-link"))))
10144 (if (functionp fun)
10145 (funcall fun)
10146 (read-string "Link (no completion support): " (concat type ":")))))
10148 (defun org-file-complete-link (&optional arg)
10149 "Create a file link using completion."
10150 (let (file link)
10151 (setq file (org-iread-file-name "File: "))
10152 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10153 (pwd1 (file-name-as-directory (abbreviate-file-name
10154 (expand-file-name ".")))))
10155 (cond
10156 ((equal arg '(16))
10157 (setq link (concat
10158 "file:"
10159 (abbreviate-file-name (expand-file-name file)))))
10160 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10161 (setq link (concat "file:" (match-string 1 file))))
10162 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10163 (expand-file-name file))
10164 (setq link (concat
10165 "file:" (match-string 1 (expand-file-name file)))))
10166 (t (setq link (concat "file:" file)))))
10167 link))
10169 (defun org-iread-file-name (&rest args)
10170 "Read-file-name using `ido-mode' speedup if available.
10171 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10172 See `read-file-name' for a description of parameters."
10173 (org-without-partial-completion
10174 (if (and org-completion-use-ido
10175 (fboundp 'ido-read-file-name)
10176 (boundp 'ido-mode) ido-mode
10177 (listp (second args)))
10178 (let ((ido-enter-matching-directory nil))
10179 (apply 'ido-read-file-name args))
10180 (apply 'read-file-name args))))
10182 (defun org-completing-read (&rest args)
10183 "Completing-read with SPACE being a normal character."
10184 (let ((enable-recursive-minibuffers t)
10185 (minibuffer-local-completion-map
10186 (copy-keymap minibuffer-local-completion-map)))
10187 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10188 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10189 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10190 (apply 'org-icompleting-read args)))
10192 (defun org-completing-read-no-i (&rest args)
10193 (let (org-completion-use-ido org-completion-use-iswitchb)
10194 (apply 'org-completing-read args)))
10196 (defun org-iswitchb-completing-read (prompt choices &rest args)
10197 "Use iswitch as a completing-read replacement to choose from choices.
10198 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10199 from."
10200 (let* ((iswitchb-use-virtual-buffers nil)
10201 (iswitchb-make-buflist-hook
10202 (lambda ()
10203 (setq iswitchb-temp-buflist choices))))
10204 (iswitchb-read-buffer prompt)))
10206 (defun org-icompleting-read (&rest args)
10207 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10208 (org-without-partial-completion
10209 (if (and org-completion-use-ido
10210 (fboundp 'ido-completing-read)
10211 (boundp 'ido-mode) ido-mode
10212 (listp (second args)))
10213 (let ((ido-enter-matching-directory nil))
10214 (apply 'ido-completing-read (concat (car args))
10215 (if (consp (car (nth 1 args)))
10216 (mapcar 'car (nth 1 args))
10217 (nth 1 args))
10218 (cddr args)))
10219 (if (and org-completion-use-iswitchb
10220 (boundp 'iswitchb-mode) iswitchb-mode
10221 (listp (second args)))
10222 (apply 'org-iswitchb-completing-read (concat (car args))
10223 (if (consp (car (nth 1 args)))
10224 (mapcar 'car (nth 1 args))
10225 (nth 1 args))
10226 (cddr args))
10227 (apply 'completing-read args)))))
10229 (defun org-extract-attributes (s)
10230 "Extract the attributes cookie from a string and set as text property."
10231 (let (a attr (start 0) key value)
10232 (save-match-data
10233 (when (string-match "{{\\([^}]+\\)}}$" s)
10234 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10235 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10236 (setq key (match-string 1 a) value (match-string 2 a)
10237 start (match-end 0)
10238 attr (plist-put attr (intern key) value))))
10239 (org-add-props s nil 'org-attr attr))
10242 ;;; Opening/following a link
10244 (defvar org-link-search-failed nil)
10246 (defvar org-open-link-functions nil
10247 "Hook for functions finding a plain text link.
10248 These functions must take a single argument, the link content.
10249 They will be called for links that look like [[link text][description]]
10250 when LINK TEXT does not have a protocol like \"http:\" and does not look
10251 like a filename (e.g. \"./blue.png\").
10253 These functions will be called *before* Org attempts to resolve the
10254 link by doing text searches in the current buffer - so if you want a
10255 link \"[[target]]\" to still find \"<<target>>\", your function should
10256 handle this as a special case.
10258 When the function does handle the link, it must return a non-nil value.
10259 If it decides that it is not responsible for this link, it must return
10260 nil to indicate that that Org-mode can continue with other options
10261 like exact and fuzzy text search.")
10263 (defun org-next-link (&optional search-backward)
10264 "Move forward to the next link.
10265 If the link is in hidden text, expose it."
10266 (interactive "P")
10267 (when (and org-link-search-failed (eq this-command last-command))
10268 (goto-char (point-min))
10269 (message "Link search wrapped back to beginning of buffer"))
10270 (setq org-link-search-failed nil)
10271 (let* ((pos (point))
10272 (ct (org-context))
10273 (a (assoc :link ct))
10274 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10275 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10276 ((looking-at org-any-link-re)
10277 ;; Don't stay stuck at link without an org-link face
10278 (forward-char (if search-backward -1 1))))
10279 (if (funcall srch-fun org-any-link-re nil t)
10280 (progn
10281 (goto-char (match-beginning 0))
10282 (if (outline-invisible-p) (org-show-context)))
10283 (goto-char pos)
10284 (setq org-link-search-failed t)
10285 (message "No further link found"))))
10287 (defun org-previous-link ()
10288 "Move backward to the previous link.
10289 If the link is in hidden text, expose it."
10290 (interactive)
10291 (funcall 'org-next-link t))
10293 (defun org-translate-link (s)
10294 "Translate a link string if a translation function has been defined."
10295 (if (and org-link-translation-function
10296 (fboundp org-link-translation-function)
10297 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10298 (progn
10299 (setq s (funcall org-link-translation-function
10300 (match-string 1 s) (match-string 2 s)))
10301 (concat (car s) ":" (cdr s)))
10304 (defun org-translate-link-from-planner (type path)
10305 "Translate a link from Emacs Planner syntax so that Org can follow it.
10306 This is still an experimental function, your mileage may vary."
10307 (cond
10308 ((member type '("http" "https" "news" "ftp"))
10309 ;; standard Internet links are the same.
10310 nil)
10311 ((and (equal type "irc") (string-match "^//" path))
10312 ;; Planner has two / at the beginning of an irc link, we have 1.
10313 ;; We should have zero, actually....
10314 (setq path (substring path 1)))
10315 ((and (equal type "lisp") (string-match "^/" path))
10316 ;; Planner has a slash, we do not.
10317 (setq type "elisp" path (substring path 1)))
10318 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10319 ;; A typical message link. Planner has the id after the final slash,
10320 ;; we separate it with a hash mark
10321 (setq path (concat (match-string 1 path) "#"
10322 (org-remove-angle-brackets (match-string 2 path))))))
10323 (cons type path))
10325 (defun org-find-file-at-mouse (ev)
10326 "Open file link or URL at mouse."
10327 (interactive "e")
10328 (mouse-set-point ev)
10329 (org-open-at-point 'in-emacs))
10331 (defun org-open-at-mouse (ev)
10332 "Open file link or URL at mouse.
10333 See the docstring of `org-open-file' for details."
10334 (interactive "e")
10335 (mouse-set-point ev)
10336 (if (eq major-mode 'org-agenda-mode)
10337 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10338 (org-open-at-point))
10340 (defvar org-window-config-before-follow-link nil
10341 "The window configuration before following a link.
10342 This is saved in case the need arises to restore it.")
10344 (defvar org-open-link-marker (make-marker)
10345 "Marker pointing to the location where `org-open-at-point' was called.")
10347 ;;;###autoload
10348 (defun org-open-at-point-global ()
10349 "Follow a link like Org-mode does.
10350 This command can be called in any mode to follow a link that has
10351 Org-mode syntax."
10352 (interactive)
10353 (org-run-like-in-org-mode 'org-open-at-point))
10355 ;;;###autoload
10356 (defun org-open-link-from-string (s &optional arg reference-buffer)
10357 "Open a link in the string S, as if it was in Org-mode."
10358 (interactive "sLink: \nP")
10359 (let ((reference-buffer (or reference-buffer (current-buffer))))
10360 (with-temp-buffer
10361 (let ((org-inhibit-startup (not reference-buffer)))
10362 (org-mode)
10363 (insert s)
10364 (goto-char (point-min))
10365 (when reference-buffer
10366 (setq org-link-abbrev-alist-local
10367 (with-current-buffer reference-buffer
10368 org-link-abbrev-alist-local)))
10369 (org-open-at-point arg reference-buffer)))))
10371 (defvar org-open-at-point-functions nil
10372 "Hook that is run when following a link at point.
10374 Functions in this hook must return t if they identify and follow
10375 a link at point. If they don't find anything interesting at point,
10376 they must return nil.")
10378 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10379 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10380 (defun org-open-at-point (&optional arg reference-buffer)
10381 "Open link at or after point.
10382 If there is no link at point, this function will search forward up to
10383 the end of the current line.
10384 Normally, files will be opened by an appropriate application. If the
10385 optional prefix argument ARG is non-nil, Emacs will visit the file.
10386 With a double prefix argument, try to open outside of Emacs, in the
10387 application the system uses for this file type."
10388 (interactive "P")
10389 ;; if in a code block, then open the block's results
10390 (unless (call-interactively #'org-babel-open-src-block-result)
10391 (org-load-modules-maybe)
10392 (move-marker org-open-link-marker (point))
10393 (setq org-window-config-before-follow-link (current-window-configuration))
10394 (org-remove-occur-highlights nil nil t)
10395 (cond
10396 ((and (org-at-heading-p)
10397 (not (org-at-timestamp-p t))
10398 (not (org-in-regexp
10399 (concat org-plain-link-re "\\|"
10400 org-bracket-link-regexp "\\|"
10401 org-angle-link-re "\\|"
10402 "[ \t]:[^ \t\n]+:[ \t]*$")))
10403 (not (get-text-property (point) 'org-linked-text)))
10404 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10405 (lk0 (car lkall))
10406 (lk (if (stringp lk0) (list lk0) lk0))
10407 (lkend (cdr lkall)))
10408 (mapcar (lambda(l)
10409 (search-forward l nil lkend)
10410 (goto-char (match-beginning 0))
10411 (org-open-at-point))
10412 lk))
10413 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10414 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10415 ((and (org-at-timestamp-p t)
10416 (not (org-in-regexp org-bracket-link-regexp)))
10417 (org-follow-timestamp-link))
10418 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10419 (not (org-in-regexp org-any-link-re)))
10420 (org-footnote-action))
10422 (let (type path link line search (pos (point)))
10423 (catch 'match
10424 (save-excursion
10425 (or (org-in-regexp org-plain-link-re)
10426 (skip-chars-forward "^]\n\r"))
10427 (when (org-in-regexp org-bracket-link-regexp 1)
10428 (setq link (org-extract-attributes
10429 (org-link-unescape (org-match-string-no-properties 1))))
10430 (while (string-match " *\n *" link)
10431 (setq link (replace-match " " t t link)))
10432 (setq link (org-link-expand-abbrev link))
10433 (cond
10434 ((or (file-name-absolute-p link)
10435 (string-match "^\\.\\.?/" link))
10436 (setq type "file" path link))
10437 ((string-match org-link-re-with-space3 link)
10438 (setq type (match-string 1 link) path (match-string 2 link)))
10439 ((string-match "^help:+\\(.+\\)" link)
10440 (setq type "help" path (match-string 1 link)))
10441 (t (setq type "thisfile" path link)))
10442 (throw 'match t)))
10444 (when (get-text-property (point) 'org-linked-text)
10445 (setq type "thisfile"
10446 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10447 (1+ (point)) (point))
10448 path (buffer-substring
10449 (or (previous-single-property-change pos 'org-linked-text)
10450 (point-min))
10451 (or (next-single-property-change pos 'org-linked-text)
10452 (point-max)))
10453 ;; Ensure we will search for a <<<radio>>> link, not
10454 ;; a simple reference like <<ref>>
10455 path (concat "<" path))
10456 (throw 'match t))
10458 (save-excursion
10459 (when (or (org-in-regexp org-angle-link-re)
10460 (let ((match (org-in-regexp org-plain-link-re)))
10461 ;; Check a plain link is not within a bracket link
10462 (and match
10463 (save-excursion
10464 (save-match-data
10465 (progn
10466 (goto-char (car match))
10467 (not (org-in-regexp org-bracket-link-regexp)))))))
10468 (let ((line_ending (save-excursion (end-of-line) (point))))
10469 ;; We are in a line before a plain or bracket link
10470 (or (re-search-forward org-plain-link-re line_ending t)
10471 (re-search-forward org-bracket-link-regexp line_ending t))))
10472 (setq type (match-string 1)
10473 path (org-link-unescape (match-string 2)))
10474 (throw 'match t)))
10475 (save-excursion
10476 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10477 (setq type "tags"
10478 path (match-string 1))
10479 (while (string-match ":" path)
10480 (setq path (replace-match "+" t t path)))
10481 (throw 'match t)))
10482 (when (org-in-regexp "<\\([^><\n]+\\)>")
10483 (setq type "tree-match"
10484 path (match-string 1))
10485 (throw 'match t)))
10486 (unless path
10487 (user-error "No link found"))
10489 ;; switch back to reference buffer
10490 ;; needed when if called in a temporary buffer through
10491 ;; org-open-link-from-string
10492 (with-current-buffer (or reference-buffer (current-buffer))
10494 ;; Remove any trailing spaces in path
10495 (if (string-match " +\\'" path)
10496 (setq path (replace-match "" t t path)))
10497 (if (and org-link-translation-function
10498 (fboundp org-link-translation-function))
10499 ;; Check if we need to translate the link
10500 (let ((tmp (funcall org-link-translation-function type path)))
10501 (setq type (car tmp) path (cdr tmp))))
10503 (cond
10505 ((assoc type org-link-protocols)
10506 (funcall (nth 1 (assoc type org-link-protocols)) path))
10508 ((equal type "help")
10509 (let ((f-or-v (intern path)))
10510 (cond ((fboundp f-or-v)
10511 (describe-function f-or-v))
10512 ((boundp f-or-v)
10513 (describe-variable f-or-v))
10514 (t (error "Not a known function or variable")))))
10516 ((equal type "mailto")
10517 (let ((cmd (car org-link-mailto-program))
10518 (args (cdr org-link-mailto-program)) args1
10519 (address path) (subject "") a)
10520 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10521 (setq address (match-string 1 path)
10522 subject (org-link-escape (match-string 2 path))))
10523 (while args
10524 (cond
10525 ((not (stringp (car args))) (push (pop args) args1))
10526 (t (setq a (pop args))
10527 (if (string-match "%a" a)
10528 (setq a (replace-match address t t a)))
10529 (if (string-match "%s" a)
10530 (setq a (replace-match subject t t a)))
10531 (push a args1))))
10532 (apply cmd (nreverse args1))))
10534 ((member type '("http" "https" "ftp" "news"))
10535 (browse-url
10536 (concat type ":"
10537 (if (org-string-match-p
10538 (concat "[[:nonascii:]"
10539 org-link-escape-chars-browser "]")
10540 path)
10541 (org-link-escape path org-link-escape-chars-browser)
10542 path))))
10544 ((string= type "doi")
10545 (browse-url
10546 (concat org-doi-server-url
10547 (if (org-string-match-p
10548 (concat "[[:nonascii:]"
10549 org-link-escape-chars-browser "]")
10550 path)
10551 (org-link-escape path org-link-escape-chars-browser)
10552 path))))
10554 ((member type '("message"))
10555 (browse-url (concat type ":" path)))
10557 ((string= type "tags")
10558 (org-tags-view arg path))
10560 ((string= type "tree-match")
10561 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10563 ((string= type "file")
10564 (if (string-match "::\\([0-9]+\\)\\'" path)
10565 (setq line (string-to-number (match-string 1 path))
10566 path (substring path 0 (match-beginning 0)))
10567 (if (string-match "::\\(.+\\)\\'" path)
10568 (setq search (match-string 1 path)
10569 path (substring path 0 (match-beginning 0)))))
10570 (if (string-match "[*?{]" (file-name-nondirectory path))
10571 (dired path)
10572 (org-open-file path arg line search)))
10574 ((string= type "shell")
10575 (let ((buf (generate-new-buffer "*Org Shell Output"))
10576 (cmd path))
10577 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10578 (string-match org-confirm-shell-link-not-regexp cmd))
10579 (not org-confirm-shell-link-function)
10580 (funcall org-confirm-shell-link-function
10581 (format "Execute \"%s\" in shell? "
10582 (org-add-props cmd nil
10583 'face 'org-warning))))
10584 (progn
10585 (message "Executing %s" cmd)
10586 (shell-command cmd buf)
10587 (if (featurep 'midnight)
10588 (setq clean-buffer-list-kill-buffer-names
10589 (cons buf clean-buffer-list-kill-buffer-names))))
10590 (error "Abort"))))
10592 ((string= type "elisp")
10593 (let ((cmd path))
10594 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10595 (string-match org-confirm-elisp-link-not-regexp cmd))
10596 (not org-confirm-elisp-link-function)
10597 (funcall org-confirm-elisp-link-function
10598 (format "Execute \"%s\" as elisp? "
10599 (org-add-props cmd nil
10600 'face 'org-warning))))
10601 (message "%s => %s" cmd
10602 (if (equal (string-to-char cmd) ?\()
10603 (eval (read cmd))
10604 (call-interactively (read cmd))))
10605 (error "Abort"))))
10607 ((and (string= type "thisfile")
10608 (or (run-hook-with-args-until-success
10609 'org-open-link-functions path)
10610 (and link
10611 (string-match "^id:" link)
10612 (or (featurep 'org-id) (require 'org-id))
10613 (progn
10614 (funcall (nth 1 (assoc "id" org-link-protocols))
10615 (substring path 3))
10616 t)))))
10618 ((string= type "thisfile")
10619 (if arg
10620 (switch-to-buffer-other-window
10621 (org-get-buffer-for-internal-link (current-buffer)))
10622 (org-mark-ring-push))
10623 (let ((cmd `(org-link-search
10624 ,path
10625 ,(cond ((equal arg '(4)) ''occur)
10626 ((equal arg '(16)) ''org-occur))
10627 ,pos)))
10628 (condition-case nil (let ((org-link-search-inhibit-query t))
10629 (eval cmd))
10630 (error (progn (widen) (eval cmd))))))
10632 (t (browse-url-at-point)))))))
10633 (move-marker org-open-link-marker nil)
10634 (run-hook-with-args 'org-follow-link-hook)))
10636 (defsubst org-uniquify (list)
10637 "Non-destructively remove duplicate elements from LIST."
10638 (let ((res (copy-sequence list))) (delete-dups res)))
10640 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10641 "Offer links in the current entry and return the selected link.
10642 If there is only one link, return it.
10643 If NTH is an integer, return the NTH link found.
10644 If ZERO is a string, check also this string for a link, and if
10645 there is one, return it."
10646 (with-current-buffer buffer
10647 (save-excursion
10648 (save-restriction
10649 (widen)
10650 (goto-char marker)
10651 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10652 "\\(" org-angle-link-re "\\)\\|"
10653 "\\(" org-plain-link-re "\\)"))
10654 (cnt ?0)
10655 (in-emacs (if (integerp nth) nil nth))
10656 have-zero end links link c)
10657 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10658 (push (match-string 0 zero) links)
10659 (setq cnt (1- cnt) have-zero t))
10660 (save-excursion
10661 (org-back-to-heading t)
10662 (setq end (save-excursion (outline-next-heading) (point)))
10663 (while (re-search-forward re end t)
10664 (push (match-string 0) links))
10665 (setq links (org-uniquify (reverse links))))
10666 (cond
10667 ((null links)
10668 (message "No links"))
10669 ((equal (length links) 1)
10670 (setq link (car links)))
10671 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10672 (setq link (nth (if have-zero nth (1- nth)) links)))
10673 (t ; we have to select a link
10674 (save-excursion
10675 (save-window-excursion
10676 (delete-other-windows)
10677 (with-output-to-temp-buffer "*Select Link*"
10678 (mapc (lambda (l)
10679 (if (not (string-match org-bracket-link-regexp l))
10680 (princ (format "[%c] %s\n" (incf cnt)
10681 (org-remove-angle-brackets l)))
10682 (if (match-end 3)
10683 (princ (format "[%c] %s (%s)\n" (incf cnt)
10684 (match-string 3 l) (match-string 1 l)))
10685 (princ (format "[%c] %s\n" (incf cnt)
10686 (match-string 1 l))))))
10687 links))
10688 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10689 (message "Select link to open, RET to open all:")
10690 (setq c (read-char-exclusive))
10691 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10692 (when (equal c ?q) (error "Abort"))
10693 (if (equal c ?\C-m)
10694 (setq link links)
10695 (setq nth (- c ?0))
10696 (if have-zero (setq nth (1+ nth)))
10697 (unless (and (integerp nth) (>= (length links) nth))
10698 (user-error "Invalid link selection"))
10699 (setq link (nth (1- nth) links)))))
10700 (cons link end))))))
10702 ;; Add special file links that specify the way of opening
10704 (org-add-link-type "file+sys" 'org-open-file-with-system)
10705 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10706 (defun org-open-file-with-system (path)
10707 "Open file at PATH using the system way of opening it."
10708 (org-open-file path 'system))
10709 (defun org-open-file-with-emacs (path)
10710 "Open file at PATH in Emacs."
10711 (org-open-file path 'emacs))
10714 ;;; File search
10716 (defvar org-create-file-search-functions nil
10717 "List of functions to construct the right search string for a file link.
10718 These functions are called in turn with point at the location to
10719 which the link should point.
10721 A function in the hook should first test if it would like to
10722 handle this file type, for example by checking the `major-mode'
10723 or the file extension. If it decides not to handle this file, it
10724 should just return nil to give other functions a chance. If it
10725 does handle the file, it must return the search string to be used
10726 when following the link. The search string will be part of the
10727 file link, given after a double colon, and `org-open-at-point'
10728 will automatically search for it. If special measures must be
10729 taken to make the search successful, another function should be
10730 added to the companion hook `org-execute-file-search-functions',
10731 which see.
10733 A function in this hook may also use `setq' to set the variable
10734 `description' to provide a suggestion for the descriptive text to
10735 be used for this link when it gets inserted into an Org-mode
10736 buffer with \\[org-insert-link].")
10738 (defvar org-execute-file-search-functions nil
10739 "List of functions to execute a file search triggered by a link.
10741 Functions added to this hook must accept a single argument, the
10742 search string that was part of the file link, the part after the
10743 double colon. The function must first check if it would like to
10744 handle this search, for example by checking the `major-mode' or
10745 the file extension. If it decides not to handle this search, it
10746 should just return nil to give other functions a chance. If it
10747 does handle the search, it must return a non-nil value to keep
10748 other functions from trying.
10750 Each function can access the current prefix argument through the
10751 variable `current-prefix-arg'. Note that a single prefix is used
10752 to force opening a link in Emacs, so it may be good to only use a
10753 numeric or double prefix to guide the search function.
10755 In case this is needed, a function in this hook can also restore
10756 the window configuration before `org-open-at-point' was called using:
10758 (set-window-configuration org-window-config-before-follow-link)")
10760 (defun org-link-search (s &optional type avoid-pos stealth)
10761 "Search for a link search option.
10762 If S is surrounded by forward slashes, it is interpreted as a
10763 regular expression. In org-mode files, this will create an `org-occur'
10764 sparse tree. In ordinary files, `occur' will be used to list matches.
10765 If the current buffer is in `dired-mode', grep will be used to search
10766 in all files. If AVOID-POS is given, ignore matches near that position.
10768 When optional argument STEALTH is non-nil, do not modify
10769 visibility around point, thus ignoring
10770 `org-show-hierarchy-above', `org-show-following-heading' and
10771 `org-show-siblings' variables."
10772 (let ((case-fold-search t)
10773 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10774 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10775 (append '(("") (" ") ("\t") ("\n"))
10776 org-emphasis-alist)
10777 "\\|") "\\)"))
10778 (pos (point))
10779 (pre nil) (post nil)
10780 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10781 (cond
10782 ;; First check if there are any special search functions
10783 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10784 ;; Now try the builtin stuff
10785 ((and (equal (string-to-char s0) ?#)
10786 (> (length s0) 1)
10787 (save-excursion
10788 (goto-char (point-min))
10789 (and
10790 (re-search-forward
10791 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10792 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10793 (setq type 'dedicated
10794 pos (match-beginning 0))))
10795 ;; There is an exact target for this
10796 (goto-char pos)
10797 (org-back-to-heading t)))
10798 ((save-excursion
10799 (goto-char (point-min))
10800 (and
10801 (re-search-forward
10802 (concat "<<" (regexp-quote s0) ">>") nil t)
10803 (setq type 'dedicated
10804 pos (match-beginning 0))))
10805 ;; There is an exact target for this
10806 (goto-char pos))
10807 ((save-excursion
10808 (goto-char (point-min))
10809 (and
10810 (re-search-forward
10811 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10812 (setq type 'dedicated pos (match-beginning 0))))
10813 ;; Found an element with a matching #+name affiliated keyword.
10814 (goto-char pos))
10815 ((and (string-match "^(\\(.*\\))$" s0)
10816 (save-excursion
10817 (goto-char (point-min))
10818 (and
10819 (re-search-forward
10820 (concat "[^[]" (regexp-quote
10821 (format org-coderef-label-format
10822 (match-string 1 s0))))
10823 nil t)
10824 (setq type 'dedicated
10825 pos (1+ (match-beginning 0))))))
10826 ;; There is a coderef target for this
10827 (goto-char pos))
10828 ((string-match "^/\\(.*\\)/$" s)
10829 ;; A regular expression
10830 (cond
10831 ((derived-mode-p 'org-mode)
10832 (org-occur (match-string 1 s)))
10833 (t (org-do-occur (match-string 1 s)))))
10834 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10835 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10836 (goto-char (point-min))
10837 (cond
10838 ((let (case-fold-search)
10839 (re-search-forward (format org-complex-heading-regexp-format
10840 (regexp-quote s))
10841 nil t))
10842 ;; OK, found a match
10843 (setq type 'dedicated)
10844 (goto-char (match-beginning 0)))
10845 ((and (not org-link-search-inhibit-query)
10846 (eq org-link-search-must-match-exact-headline 'query-to-create)
10847 (y-or-n-p "No match - create this as a new heading? "))
10848 (goto-char (point-max))
10849 (or (bolp) (newline))
10850 (insert "* " s "\n")
10851 (beginning-of-line 0))
10853 (goto-char pos)
10854 (error "No match"))))
10856 ;; A normal search string
10857 (when (equal (string-to-char s) ?*)
10858 ;; Anchor on headlines, post may include tags.
10859 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10860 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10861 s (substring s 1)))
10862 (remove-text-properties
10863 0 (length s)
10864 '(face nil mouse-face nil keymap nil fontified nil) s)
10865 ;; Make a series of regular expressions to find a match
10866 (setq words (org-split-string s "[ \n\r\t]+")
10868 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10869 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10870 "\\)" markers)
10871 re2a_ (concat "\\(" (mapconcat 'downcase words
10872 "[ \t\r\n]+") "\\)[ \t\r\n]")
10873 re2a (concat "[ \t\r\n]" re2a_)
10874 re4_ (concat "\\(" (mapconcat 'downcase words
10875 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10876 re4 (concat "[^a-zA-Z_]" re4_)
10878 re1 (concat pre re2 post)
10879 re3 (concat pre (if pre re4_ re4) post)
10880 re5 (concat pre ".*" re4)
10881 re2 (concat pre re2)
10882 re2a (concat pre (if pre re2a_ re2a))
10883 re4 (concat pre (if pre re4_ re4))
10884 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10885 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10886 re5 "\\)"))
10887 (cond
10888 ((eq type 'org-occur) (org-occur reall))
10889 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10890 (t (goto-char (point-min))
10891 (setq type 'fuzzy)
10892 (if (or (and (org-search-not-self 1 re0 nil t)
10893 (setq type 'dedicated))
10894 (org-search-not-self 1 re1 nil t)
10895 (org-search-not-self 1 re2 nil t)
10896 (org-search-not-self 1 re2a nil t)
10897 (org-search-not-self 1 re3 nil t)
10898 (org-search-not-self 1 re4 nil t)
10899 (org-search-not-self 1 re5 nil t))
10900 (goto-char (match-beginning 1))
10901 (goto-char pos)
10902 (error "No match"))))))
10903 (and (derived-mode-p 'org-mode)
10904 (not stealth)
10905 (org-show-context 'link-search))
10906 type))
10908 (defun org-search-not-self (group &rest args)
10909 "Execute `re-search-forward', but only accept matches that do not
10910 enclose the position of `org-open-link-marker'."
10911 (let ((m org-open-link-marker))
10912 (catch 'exit
10913 (while (apply #'re-search-forward args)
10914 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10915 (goto-char (match-end group))
10916 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10917 (> (match-beginning 0) (marker-position m))
10918 (< (match-end 0) (marker-position m)))
10919 (save-match-data
10920 (or (not (org-in-regexp
10921 org-bracket-link-analytic-regexp 1))
10922 (not (match-end 4)) ; no description
10923 (and (<= (match-beginning 4) (point))
10924 (>= (match-end 4) (point))))))
10925 (throw 'exit (point))))))))
10927 (defun org-get-buffer-for-internal-link (buffer)
10928 "Return a buffer to be used for displaying the link target of internal links."
10929 (cond
10930 ((not org-display-internal-link-with-indirect-buffer)
10931 buffer)
10932 ((string-match "(Clone)$" (buffer-name buffer))
10933 (message "Buffer is already a clone, not making another one")
10934 ;; we also do not modify visibility in this case
10935 buffer)
10936 (t ; make a new indirect buffer for displaying the link
10937 (let* ((bn (buffer-name buffer))
10938 (ibn (concat bn "(Clone)"))
10939 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10940 (with-current-buffer ib (org-overview))
10941 ib))))
10943 (defun org-do-occur (regexp &optional cleanup)
10944 "Call the Emacs command `occur'.
10945 If CLEANUP is non-nil, remove the printout of the regular expression
10946 in the *Occur* buffer. This is useful if the regex is long and not useful
10947 to read."
10948 (occur regexp)
10949 (when cleanup
10950 (let ((cwin (selected-window)) win beg end)
10951 (when (setq win (get-buffer-window "*Occur*"))
10952 (select-window win))
10953 (goto-char (point-min))
10954 (when (re-search-forward "match[a-z]+" nil t)
10955 (setq beg (match-end 0))
10956 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10957 (setq end (1- (match-beginning 0)))))
10958 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10959 (goto-char (point-min))
10960 (select-window cwin))))
10962 ;;; The mark ring for links jumps
10964 (defvar org-mark-ring nil
10965 "Mark ring for positions before jumps in Org-mode.")
10966 (defvar org-mark-ring-last-goto nil
10967 "Last position in the mark ring used to go back.")
10968 ;; Fill and close the ring
10969 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10970 (loop for i from 1 to org-mark-ring-length do
10971 (push (make-marker) org-mark-ring))
10972 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10973 org-mark-ring)
10975 (defun org-mark-ring-push (&optional pos buffer)
10976 "Put the current position or POS into the mark ring and rotate it."
10977 (interactive)
10978 (setq pos (or pos (point)))
10979 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10980 (move-marker (car org-mark-ring)
10981 (or pos (point))
10982 (or buffer (current-buffer)))
10983 (message "%s"
10984 (substitute-command-keys
10985 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10987 (defun org-mark-ring-goto (&optional n)
10988 "Jump to the previous position in the mark ring.
10989 With prefix arg N, jump back that many stored positions. When
10990 called several times in succession, walk through the entire ring.
10991 Org-mode commands jumping to a different position in the current file,
10992 or to another Org-mode file, automatically push the old position
10993 onto the ring."
10994 (interactive "p")
10995 (let (p m)
10996 (if (eq last-command this-command)
10997 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10998 (setq p org-mark-ring))
10999 (setq org-mark-ring-last-goto p)
11000 (setq m (car p))
11001 (org-pop-to-buffer-same-window (marker-buffer m))
11002 (goto-char m)
11003 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11005 (defun org-remove-angle-brackets (s)
11006 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11007 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11009 (defun org-add-angle-brackets (s)
11010 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11011 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11013 (defun org-remove-double-quotes (s)
11014 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11015 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11018 ;;; Following specific links
11020 (defun org-follow-timestamp-link ()
11021 "Open an agenda view for the time-stamp date/range at point."
11022 (cond
11023 ((org-at-date-range-p t)
11024 (let ((org-agenda-start-on-weekday)
11025 (t1 (match-string 1))
11026 (t2 (match-string 2)) tt1 tt2)
11027 (setq tt1 (time-to-days (org-time-string-to-time t1))
11028 tt2 (time-to-days (org-time-string-to-time t2)))
11029 (let ((org-agenda-buffer-tmp-name
11030 (format "*Org Agenda(a:%s)"
11031 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11032 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11033 ((org-at-timestamp-p t)
11034 (let ((org-agenda-buffer-tmp-name
11035 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11036 (org-agenda-list nil (time-to-days (org-time-string-to-time
11037 (substring (match-string 1) 0 10)))
11038 1)))
11039 (t (error "This should not happen"))))
11042 ;;; Following file links
11043 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11044 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11045 (declare-function mailcap-mime-info
11046 "mailcap" (string &optional request no-decode))
11047 (defvar org-wait nil)
11048 (defun org-open-file (path &optional in-emacs line search)
11049 "Open the file at PATH.
11050 First, this expands any special file name abbreviations. Then the
11051 configuration variable `org-file-apps' is checked if it contains an
11052 entry for this file type, and if yes, the corresponding command is launched.
11054 If no application is found, Emacs simply visits the file.
11056 With optional prefix argument IN-EMACS, Emacs will visit the file.
11057 With a double \\[universal-argument] \\[universal-argument] \
11058 prefix arg, Org tries to avoid opening in Emacs
11059 and to use an external application to visit the file.
11061 Optional LINE specifies a line to go to, optional SEARCH a string
11062 to search for. If LINE or SEARCH is given, the file will be
11063 opened in Emacs, unless an entry from org-file-apps that makes
11064 use of groups in a regexp matches.
11066 If you want to change the way frames are used when following a
11067 link, please customize `org-link-frame-setup'.
11069 If the file does not exist, an error is thrown."
11070 (let* ((file (if (equal path "")
11071 buffer-file-name
11072 (substitute-in-file-name (expand-file-name path))))
11073 (file-apps (append org-file-apps (org-default-apps)))
11074 (apps (org-remove-if
11075 'org-file-apps-entry-match-against-dlink-p file-apps))
11076 (apps-dlink (org-remove-if-not
11077 'org-file-apps-entry-match-against-dlink-p file-apps))
11078 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11079 (dirp (if remp nil (file-directory-p file)))
11080 (file (if (and dirp org-open-directory-means-index-dot-org)
11081 (concat (file-name-as-directory file) "index.org")
11082 file))
11083 (a-m-a-p (assq 'auto-mode apps))
11084 (dfile (downcase file))
11085 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11086 (link (cond ((and (eq line nil)
11087 (eq search nil))
11088 file)
11089 (line
11090 (concat file "::" (number-to-string line)))
11091 (search
11092 (concat file "::" search))))
11093 (dlink (downcase link))
11094 (old-buffer (current-buffer))
11095 (old-pos (point))
11096 (old-mode major-mode)
11097 ext cmd link-match-data)
11098 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11099 (setq ext (match-string 1 dfile))
11100 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11101 (setq ext (match-string 1 dfile))))
11102 (cond
11103 ((member in-emacs '((16) system))
11104 (setq cmd (cdr (assoc 'system apps))))
11105 (in-emacs (setq cmd 'emacs))
11107 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11108 (and dirp (cdr (assoc 'directory apps)))
11109 ; first, try matching against apps-dlink
11110 ; if we get a match here, store the match data for later
11111 (let ((match (assoc-default dlink apps-dlink
11112 'string-match)))
11113 (if match
11114 (progn (setq link-match-data (match-data))
11115 match)
11116 (progn (setq in-emacs (or in-emacs line search))
11117 nil))) ; if we have no match in apps-dlink,
11118 ; always open the file in emacs if line or search
11119 ; is given (for backwards compatibility)
11120 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11121 'string-match)
11122 (cdr (assoc ext apps))
11123 (cdr (assoc t apps))))))
11124 (when (eq cmd 'system)
11125 (setq cmd (cdr (assoc 'system apps))))
11126 (when (eq cmd 'default)
11127 (setq cmd (cdr (assoc t apps))))
11128 (when (eq cmd 'mailcap)
11129 (require 'mailcap)
11130 (mailcap-parse-mailcaps)
11131 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11132 (command (mailcap-mime-info mime-type)))
11133 (if (stringp command)
11134 (setq cmd command)
11135 (setq cmd 'emacs))))
11136 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11137 (not (file-exists-p file))
11138 (not org-open-non-existing-files))
11139 (user-error "No such file: %s" file))
11140 (cond
11141 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11142 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11143 (while (string-match "['\"]%s['\"]" cmd)
11144 (setq cmd (replace-match "%s" t t cmd)))
11145 (while (string-match "%s" cmd)
11146 (setq cmd (replace-match
11147 (save-match-data
11148 (shell-quote-argument
11149 (convert-standard-filename file)))
11150 t t cmd)))
11152 ;; Replace "%1", "%2" etc. in command with group matches from regex
11153 (save-match-data
11154 (let ((match-index 1)
11155 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11156 (set-match-data link-match-data)
11157 (while (<= match-index number-of-groups)
11158 (let ((regex (concat "%" (number-to-string match-index)))
11159 (replace-with (match-string match-index dlink)))
11160 (while (string-match regex cmd)
11161 (setq cmd (replace-match replace-with t t cmd))))
11162 (setq match-index (+ match-index 1)))))
11164 (save-window-excursion
11165 (message "Running %s...done" cmd)
11166 (start-process-shell-command cmd nil cmd)
11167 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11168 ((or (stringp cmd)
11169 (eq cmd 'emacs))
11170 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11171 (widen)
11172 (if line (org-goto-line line)
11173 (if search (org-link-search search))))
11174 ((consp cmd)
11175 (let ((file (convert-standard-filename file)))
11176 (save-match-data
11177 (set-match-data link-match-data)
11178 (eval cmd))))
11179 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11180 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11181 (or (not (equal old-buffer (current-buffer)))
11182 (not (equal old-pos (point))))
11183 (org-mark-ring-push old-pos old-buffer))))
11185 (defun org-file-apps-entry-match-against-dlink-p (entry)
11186 "This function returns non-nil if `entry' uses a regular
11187 expression which should be matched against the whole link by
11188 org-open-file.
11190 It assumes that is the case when the entry uses a regular
11191 expression which has at least one grouping construct and the
11192 action is either a lisp form or a command string containing
11193 `%1', i.e. using at least one subexpression match as a
11194 parameter."
11195 (let ((selector (car entry))
11196 (action (cdr entry)))
11197 (if (stringp selector)
11198 (and (> (regexp-opt-depth selector) 0)
11199 (or (and (stringp action)
11200 (string-match "%[0-9]" action))
11201 (consp action)))
11202 nil)))
11204 (defun org-default-apps ()
11205 "Return the default applications for this operating system."
11206 (cond
11207 ((eq system-type 'darwin)
11208 org-file-apps-defaults-macosx)
11209 ((eq system-type 'windows-nt)
11210 org-file-apps-defaults-windowsnt)
11211 (t org-file-apps-defaults-gnu)))
11213 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11214 "Convert extensions to regular expressions in the cars of LIST.
11215 Also, weed out any non-string entries, because the return value is used
11216 only for regexp matching.
11217 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11218 point to the symbol `emacs', indicating that the file should
11219 be opened in Emacs."
11220 (append
11221 (delq nil
11222 (mapcar (lambda (x)
11223 (if (not (stringp (car x)))
11225 (if (string-match "\\W" (car x))
11227 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11228 list))
11229 (if add-auto-mode
11230 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11232 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11233 (defun org-file-remote-p (file)
11234 "Test whether FILE specifies a location on a remote system.
11235 Return non-nil if the location is indeed remote.
11237 For example, the filename \"/user@host:/foo\" specifies a location
11238 on the system \"/user@host:\"."
11239 (cond ((fboundp 'file-remote-p)
11240 (file-remote-p file))
11241 ((fboundp 'tramp-handle-file-remote-p)
11242 (tramp-handle-file-remote-p file))
11243 ((and (boundp 'ange-ftp-name-format)
11244 (string-match (car ange-ftp-name-format) file))
11245 t)))
11248 ;;;; Refiling
11250 (defun org-get-org-file ()
11251 "Read a filename, with default directory `org-directory'."
11252 (let ((default (or org-default-notes-file remember-data-file)))
11253 (read-file-name (format "File name [%s]: " default)
11254 (file-name-as-directory org-directory)
11255 default)))
11257 (defun org-notes-order-reversed-p ()
11258 "Check if the current file should receive notes in reversed order."
11259 (cond
11260 ((not org-reverse-note-order) nil)
11261 ((eq t org-reverse-note-order) t)
11262 ((not (listp org-reverse-note-order)) nil)
11263 (t (catch 'exit
11264 (dolist (entry org-reverse-note-order)
11265 (if (string-match (car entry) buffer-file-name)
11266 (throw 'exit (cdr entry))))))))
11268 (defvar org-refile-target-table nil
11269 "The list of refile targets, created by `org-refile'.")
11271 (defvar org-agenda-new-buffers nil
11272 "Buffers created to visit agenda files.")
11274 (defvar org-refile-cache nil
11275 "Cache for refile targets.")
11277 (defvar org-refile-markers nil
11278 "All the markers used for caching refile locations.")
11280 (defun org-refile-marker (pos)
11281 "Get a new refile marker, but only if caching is in use."
11282 (if (not org-refile-use-cache)
11284 (let ((m (make-marker)))
11285 (move-marker m pos)
11286 (push m org-refile-markers)
11287 m)))
11289 (defun org-refile-cache-clear ()
11290 "Clear the refile cache and disable all the markers."
11291 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11292 (setq org-refile-markers nil)
11293 (setq org-refile-cache nil)
11294 (message "Refile cache has been cleared"))
11296 (defun org-refile-cache-check-set (set)
11297 "Check if all the markers in the cache still have live buffers."
11298 (let (marker)
11299 (catch 'exit
11300 (while (and set (setq marker (nth 3 (pop set))))
11301 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11302 (when (and marker (null (marker-buffer marker)))
11303 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11304 (sit-for 3)
11305 (throw 'exit nil)))
11306 t)))
11308 (defun org-refile-cache-put (set &rest identifiers)
11309 "Push the refile targets SET into the cache, under IDENTIFIERS."
11310 (let* ((key (sha1 (prin1-to-string identifiers)))
11311 (entry (assoc key org-refile-cache)))
11312 (if entry
11313 (setcdr entry set)
11314 (push (cons key set) org-refile-cache))))
11316 (defun org-refile-cache-get (&rest identifiers)
11317 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11318 (cond
11319 ((not org-refile-cache) nil)
11320 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11322 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11323 org-refile-cache))))
11324 (and set (org-refile-cache-check-set set) set)))))
11326 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11327 "Produce a table with refile targets."
11328 (let ((case-fold-search nil)
11329 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11330 (entries (or org-refile-targets '((nil . (:level . 1)))))
11331 targets tgs txt re files desc descre fast-path-p level pos0)
11332 (message "Getting targets...")
11333 (with-current-buffer (or default-buffer (current-buffer))
11334 (dolist (entry entries)
11335 (setq files (car entry) desc (cdr entry))
11336 (setq fast-path-p nil)
11337 (cond
11338 ((null files) (setq files (list (current-buffer))))
11339 ((eq files 'org-agenda-files)
11340 (setq files (org-agenda-files 'unrestricted)))
11341 ((and (symbolp files) (fboundp files))
11342 (setq files (funcall files)))
11343 ((and (symbolp files) (boundp files))
11344 (setq files (symbol-value files))))
11345 (if (stringp files) (setq files (list files)))
11346 (cond
11347 ((eq (car desc) :tag)
11348 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11349 ((eq (car desc) :todo)
11350 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11351 ((eq (car desc) :regexp)
11352 (setq descre (cdr desc)))
11353 ((eq (car desc) :level)
11354 (setq descre (concat "^\\*\\{" (number-to-string
11355 (if org-odd-levels-only
11356 (1- (* 2 (cdr desc)))
11357 (cdr desc)))
11358 "\\}[ \t]")))
11359 ((eq (car desc) :maxlevel)
11360 (setq fast-path-p t)
11361 (setq descre (concat "^\\*\\{1," (number-to-string
11362 (if org-odd-levels-only
11363 (1- (* 2 (cdr desc)))
11364 (cdr desc)))
11365 "\\}[ \t]")))
11366 (t (error "Bad refiling target description %s" desc)))
11367 (dolist (f files)
11368 (with-current-buffer
11369 (if (bufferp f) f (org-get-agenda-file-buffer f))
11371 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11372 (progn
11373 (if (bufferp f) (setq f (buffer-file-name
11374 (buffer-base-buffer f))))
11375 (setq f (and f (expand-file-name f)))
11376 (if (eq org-refile-use-outline-path 'file)
11377 (push (list (file-name-nondirectory f) f nil nil) tgs))
11378 (save-excursion
11379 (save-restriction
11380 (widen)
11381 (goto-char (point-min))
11382 (while (re-search-forward descre nil t)
11383 (goto-char (setq pos0 (point-at-bol)))
11384 (catch 'next
11385 (when org-refile-target-verify-function
11386 (save-match-data
11387 (or (funcall org-refile-target-verify-function)
11388 (throw 'next t))))
11389 (when (and (looking-at org-complex-heading-regexp)
11390 (not (member (match-string 4) excluded-entries))
11391 (match-string 4))
11392 (setq level (org-reduced-level
11393 (- (match-end 1) (match-beginning 1)))
11394 txt (org-link-display-format (match-string 4))
11395 txt (replace-regexp-in-string "\\( *[[0-9]+/?[0-9]*%?]\\)+$" "" txt)
11396 re (format org-complex-heading-regexp-format
11397 (regexp-quote (match-string 4))))
11398 (when org-refile-use-outline-path
11399 (setq txt (mapconcat
11400 'org-protect-slash
11401 (append
11402 (if (eq org-refile-use-outline-path
11403 'file)
11404 (list (file-name-nondirectory
11405 (buffer-file-name
11406 (buffer-base-buffer))))
11407 (if (eq org-refile-use-outline-path
11408 'full-file-path)
11409 (list (buffer-file-name
11410 (buffer-base-buffer)))))
11411 (org-get-outline-path fast-path-p
11412 level txt)
11413 (list txt))
11414 "/")))
11415 (push (list txt f re (org-refile-marker (point)))
11416 tgs)))
11417 (when (= (point) pos0)
11418 ;; verification function has not moved point
11419 (goto-char (point-at-eol))))))))
11420 (when org-refile-use-cache
11421 (org-refile-cache-put tgs (buffer-file-name) descre))
11422 (setq targets (append tgs targets))))))
11423 (message "Getting targets...done")
11424 (nreverse targets)))
11426 (defun org-protect-slash (s)
11427 (while (string-match "/" s)
11428 (setq s (replace-match "\\" t t s)))
11431 (defvar org-olpa (make-vector 20 nil))
11433 (defun org-get-outline-path (&optional fastp level heading)
11434 "Return the outline path to the current entry, as a list.
11436 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11437 routine which makes outline path derivations for an entire file,
11438 avoiding backtracing. Refile target collection makes use of that."
11439 (if fastp
11440 (progn
11441 (if (> level 19)
11442 (error "Outline path failure, more than 19 levels"))
11443 (loop for i from level upto 19 do
11444 (aset org-olpa i nil))
11445 (prog1
11446 (delq nil (append org-olpa nil))
11447 (aset org-olpa level heading)))
11448 (let (rtn case-fold-search)
11449 (save-excursion
11450 (save-restriction
11451 (widen)
11452 (while (org-up-heading-safe)
11453 (when (looking-at org-complex-heading-regexp)
11454 (push (org-trim
11455 (replace-regexp-in-string
11456 ;; Remove statistical/checkboxes cookies
11457 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11458 (org-match-string-no-properties 4)))
11459 rtn)))
11460 rtn)))))
11462 (defun org-format-outline-path (path &optional width prefix separator)
11463 "Format the outline path PATH for display.
11464 WIDTH is the maximum number of characters that is available.
11465 PREFIX is a prefix to be included in the returned string,
11466 such as the file name.
11467 SEPARATOR is inserted between the different parts of the path,
11468 the default is \"/\"."
11469 (setq width (or width 79))
11470 (if prefix (setq width (- width (length prefix))))
11471 (if (not path)
11472 (or prefix "")
11473 (let* ((nsteps (length path))
11474 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11475 (maxwidth (if (<= total-width width)
11476 10000 ;; everything fits
11477 ;; we need to shorten the level headings
11478 (/ (- width nsteps) nsteps)))
11479 (org-odd-levels-only nil)
11480 (n 0)
11481 (total (1+ (length prefix))))
11482 (setq maxwidth (max maxwidth 10))
11483 (concat prefix
11484 (if prefix (or separator "/"))
11485 (mapconcat
11486 (lambda (h)
11487 (setq n (1+ n))
11488 (if (and (= n nsteps) (< maxwidth 10000))
11489 (setq maxwidth (- total-width total)))
11490 (if (< (length h) maxwidth)
11491 (progn (setq total (+ total (length h) 1)) h)
11492 (setq h (substring h 0 (- maxwidth 2))
11493 total (+ total maxwidth 1))
11494 (if (string-match "[ \t]+\\'" h)
11495 (setq h (substring h 0 (match-beginning 0))))
11496 (setq h (concat h "..")))
11497 (org-add-props h nil 'face
11498 (nth (% (1- n) org-n-level-faces)
11499 org-level-faces))
11501 path (or separator "/"))))))
11503 (defun org-display-outline-path (&optional file current separator just-return-string)
11504 "Display the current outline path in the echo area.
11506 If FILE is non-nil, prepend the output with the file name.
11507 If CURRENT is non-nil, append the current heading to the output.
11508 SEPARATOR is passed through to `org-format-outline-path'. It separates
11509 the different parts of the path and defaults to \"/\".
11510 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11511 (interactive "P")
11512 (let* (case-fold-search
11513 (bfn (buffer-file-name (buffer-base-buffer)))
11514 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11515 res)
11516 (if current (setq path (append path
11517 (save-excursion
11518 (org-back-to-heading t)
11519 (if (looking-at org-complex-heading-regexp)
11520 (list (match-string 4)))))))
11521 (setq res
11522 (org-format-outline-path
11523 path
11524 (1- (frame-width))
11525 (and file bfn (concat (file-name-nondirectory bfn) separator))
11526 separator))
11527 (if just-return-string
11528 (org-no-properties res)
11529 (org-unlogged-message "%s" res))))
11531 (defvar org-refile-history nil
11532 "History for refiling operations.")
11534 (defvar org-after-refile-insert-hook nil
11535 "Hook run after `org-refile' has inserted its stuff at the new location.
11536 Note that this is still *before* the stuff will be removed from
11537 the *old* location.")
11539 (defvar org-capture-last-stored-marker)
11540 (defvar org-refile-keep nil
11541 "Non-nil means `org-refile' will copy instead of refile.")
11543 (defun org-copy ()
11544 "Like `org-refile', but copy."
11545 (interactive)
11546 (let ((org-refile-keep t))
11547 (funcall 'org-refile nil nil nil "Copy")))
11549 (defun org-refile (&optional goto default-buffer rfloc msg)
11550 "Move the entry or entries at point to another heading.
11551 The list of target headings is compiled using the information in
11552 `org-refile-targets', which see.
11554 At the target location, the entry is filed as a subitem of the target
11555 heading. Depending on `org-reverse-note-order', the new subitem will
11556 either be the first or the last subitem.
11558 If there is an active region, all entries in that region will be moved.
11559 However, the region must fulfill the requirement that the first heading
11560 is the first one sets the top-level of the moved text - at most siblings
11561 below it are allowed.
11563 With prefix arg GOTO, the command will only visit the target location
11564 and not actually move anything.
11566 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11567 go to the location where the last refiling operation has put the subtree.
11569 With a numeric prefix argument of `2', refile to the running clock.
11571 With a numeric prefix argument of `3', emulate `org-refile-keep'
11572 being set to t and copy to the target location, don't move it.
11573 Beware that keeping refiled entries may result in duplicated ID
11574 properties.
11576 RFLOC can be a refile location obtained in a different way.
11578 MSG is a string to replace \"Refile\" in the default prompt with
11579 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11581 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11583 If you are using target caching (see `org-refile-use-cache'),
11584 you have to clear the target cache in order to find new targets.
11585 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11586 prefix argument (`C-u C-u C-u C-c C-w')."
11588 (interactive "P")
11589 (if (member goto '(0 (64)))
11590 (org-refile-cache-clear)
11591 (let* ((actionmsg (cond (msg msg)
11592 ((equal goto 3) "Refile (and keep)")
11593 (t "Refile")))
11594 (cbuf (current-buffer))
11595 (regionp (org-region-active-p))
11596 (region-start (and regionp (region-beginning)))
11597 (region-end (and regionp (region-end)))
11598 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11599 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11600 pos it nbuf file re level reversed)
11601 (setq last-command nil)
11602 (when regionp
11603 (goto-char region-start)
11604 (or (bolp) (goto-char (point-at-bol)))
11605 (setq region-start (point))
11606 (unless (or (org-kill-is-subtree-p
11607 (buffer-substring region-start region-end))
11608 (prog1 org-refile-active-region-within-subtree
11609 (let ((s (point-at-eol)))
11610 (org-toggle-heading)
11611 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11612 (user-error "The region is not a (sequence of) subtree(s)")))
11613 (if (equal goto '(16))
11614 (org-refile-goto-last-stored)
11615 (when (or
11616 (and (equal goto 2)
11617 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11618 (prog1
11619 (setq it (list (or org-clock-heading "running clock")
11620 (buffer-file-name
11621 (marker-buffer org-clock-hd-marker))
11623 (marker-position org-clock-hd-marker)))
11624 (setq goto nil)))
11625 (setq it (or rfloc
11626 (let (heading-text)
11627 (save-excursion
11628 (unless (and goto (listp goto))
11629 (org-back-to-heading t)
11630 (setq heading-text
11631 (nth 4 (org-heading-components))))
11633 (org-refile-get-location
11634 (cond ((and goto (listp goto)) "Goto")
11635 (regionp (concat actionmsg " region to"))
11636 (t (concat actionmsg " subtree \""
11637 heading-text "\" to")))
11638 default-buffer
11639 (and (not (equal '(4) goto))
11640 org-refile-allow-creating-parent-nodes)
11641 goto))))))
11642 (setq file (nth 1 it)
11643 re (nth 2 it)
11644 pos (nth 3 it))
11645 (if (and (not goto)
11647 (equal (buffer-file-name) file)
11648 (if regionp
11649 (and (>= pos region-start)
11650 (<= pos region-end))
11651 (and (>= pos (point))
11652 (< pos (save-excursion
11653 (org-end-of-subtree t t))))))
11654 (error "Cannot refile to position inside the tree or region"))
11656 (setq nbuf (or (find-buffer-visiting file)
11657 (find-file-noselect file)))
11658 (if (and goto (not (equal goto 3)))
11659 (progn
11660 (org-pop-to-buffer-same-window nbuf)
11661 (goto-char pos)
11662 (org-show-context 'org-goto))
11663 (if regionp
11664 (progn
11665 (org-kill-new (buffer-substring region-start region-end))
11666 (org-save-markers-in-region region-start region-end))
11667 (org-copy-subtree 1 nil t))
11668 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11669 (find-file-noselect file)))
11670 (setq reversed (org-notes-order-reversed-p))
11671 (save-excursion
11672 (save-restriction
11673 (widen)
11674 (if pos
11675 (progn
11676 (goto-char pos)
11677 (looking-at org-outline-regexp)
11678 (setq level (org-get-valid-level (funcall outline-level) 1))
11679 (goto-char
11680 (if reversed
11681 (or (outline-next-heading) (point-max))
11682 (or (save-excursion (org-get-next-sibling))
11683 (org-end-of-subtree t t)
11684 (point-max)))))
11685 (setq level 1)
11686 (if (not reversed)
11687 (goto-char (point-max))
11688 (goto-char (point-min))
11689 (or (outline-next-heading) (goto-char (point-max)))))
11690 (if (not (bolp)) (newline))
11691 (org-paste-subtree level)
11692 (when org-log-refile
11693 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11694 (unless (eq org-log-refile 'note)
11695 (save-excursion (org-add-log-note))))
11696 (and org-auto-align-tags
11697 (let ((org-loop-over-headlines-in-active-region nil))
11698 (org-set-tags nil t)))
11699 (let ((bookmark-name (plist-get org-bookmark-names-plist
11700 :last-refile)))
11701 (when bookmark-name
11702 (with-demoted-errors
11703 (bookmark-set bookmark-name))))
11704 ;; If we are refiling for capture, make sure that the
11705 ;; last-capture pointers point here
11706 (when (org-bound-and-true-p org-refile-for-capture)
11707 (let ((bookmark-name (plist-get org-bookmark-names-plist
11708 :last-capture-marker)))
11709 (when bookmark-name
11710 (with-demoted-errors
11711 (bookmark-set bookmark-name))))
11712 (move-marker org-capture-last-stored-marker (point)))
11713 (if (fboundp 'deactivate-mark) (deactivate-mark))
11714 (run-hooks 'org-after-refile-insert-hook))))
11715 (unless org-refile-keep
11716 (if regionp
11717 (delete-region (point) (+ (point) (- region-end region-start)))
11718 (delete-region
11719 (and (org-back-to-heading t) (point))
11720 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11721 (when (featurep 'org-inlinetask)
11722 (org-inlinetask-remove-END-maybe))
11723 (setq org-markers-to-move nil)
11724 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11726 (defun org-refile-goto-last-stored ()
11727 "Go to the location where the last refile was stored."
11728 (interactive)
11729 (bookmark-jump "org-refile-last-stored")
11730 (message "This is the location of the last refile"))
11732 (defun org-refile--get-location (refloc tbl)
11733 "When user refile to REFLOC, find the associated target in TBL.
11734 Also check `org-refile-target-table'."
11735 (car (delq
11737 (mapcar
11738 (lambda (r) (or (assoc r tbl)
11739 (assoc r org-refile-target-table)))
11740 (list (replace-regexp-in-string "/$" "" refloc)
11741 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11743 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11744 no-exclude)
11745 "Prompt the user for a refile location, using PROMPT.
11746 PROMPT should not be suffixed with a colon and a space, because
11747 this function appends the default value from
11748 `org-refile-history' automatically, if that is not empty.
11749 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11750 this is used for the GOTO interface."
11751 (let ((org-refile-targets org-refile-targets)
11752 (org-refile-use-outline-path org-refile-use-outline-path)
11753 excluded-entries)
11754 (when (and (derived-mode-p 'org-mode)
11755 (not org-refile-use-cache)
11756 (not no-exclude))
11757 (org-map-tree
11758 (lambda()
11759 (setq excluded-entries
11760 (append excluded-entries (list (org-get-heading t t)))))))
11761 (setq org-refile-target-table
11762 (org-refile-get-targets default-buffer excluded-entries)))
11763 (unless org-refile-target-table
11764 (user-error "No refile targets"))
11765 (let* ((cbuf (current-buffer))
11766 (partial-completion-mode nil)
11767 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11768 (cfunc (if (and org-refile-use-outline-path
11769 org-outline-path-complete-in-steps)
11770 'org-olpath-completing-read
11771 'org-icompleting-read))
11772 (extra (if org-refile-use-outline-path "/" ""))
11773 (cbnex (concat (buffer-name) extra))
11774 (filename (and cfn (expand-file-name cfn)))
11775 (tbl (mapcar
11776 (lambda (x)
11777 (if (and (not (member org-refile-use-outline-path
11778 '(file full-file-path)))
11779 (not (equal filename (nth 1 x))))
11780 (cons (concat (car x) extra " ("
11781 (file-name-nondirectory (nth 1 x)) ")")
11782 (cdr x))
11783 (cons (concat (car x) extra) (cdr x))))
11784 org-refile-target-table))
11785 (completion-ignore-case t)
11786 cdef
11787 (prompt (concat prompt
11788 (or (and (car org-refile-history)
11789 (concat " (default " (car org-refile-history) ")"))
11790 (and (assoc cbnex tbl) (setq cdef cbnex)
11791 (concat " (default " cbnex ")"))) ": "))
11792 pa answ parent-target child parent old-hist)
11793 (setq old-hist org-refile-history)
11794 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11795 nil 'org-refile-history (or cdef (car org-refile-history))))
11796 (if (setq pa (org-refile--get-location answ tbl))
11797 (progn
11798 (org-refile-check-position pa)
11799 (when (or (not org-refile-history)
11800 (not (eq old-hist org-refile-history))
11801 (not (equal (car pa) (car org-refile-history))))
11802 (setq org-refile-history
11803 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11804 org-refile-history
11805 (cdr org-refile-history))))
11806 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11807 (pop org-refile-history)))
11809 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11810 (progn
11811 (setq parent (match-string 1 answ)
11812 child (match-string 2 answ))
11813 (setq parent-target (org-refile--get-location parent tbl))
11814 (when (and parent-target
11815 (or (eq new-nodes t)
11816 (and (eq new-nodes 'confirm)
11817 (y-or-n-p (format "Create new node \"%s\"? "
11818 child)))))
11819 (org-refile-new-child parent-target child)))
11820 (user-error "Invalid target location")))))
11822 (declare-function org-string-nw-p "org-macs" (s))
11823 (defun org-refile-check-position (refile-pointer)
11824 "Check if the refile pointer matches the headline to which it points."
11825 (let* ((file (nth 1 refile-pointer))
11826 (re (nth 2 refile-pointer))
11827 (pos (nth 3 refile-pointer))
11828 buffer)
11829 (if (and (not (markerp pos)) (not file))
11830 (user-error "Please save the buffer to a file before refiling")
11831 (when (org-string-nw-p re)
11832 (setq buffer (if (markerp pos)
11833 (marker-buffer pos)
11834 (or (find-buffer-visiting file)
11835 (find-file-noselect file))))
11836 (with-current-buffer buffer
11837 (save-excursion
11838 (save-restriction
11839 (widen)
11840 (goto-char pos)
11841 (beginning-of-line 1)
11842 (unless (org-looking-at-p re)
11843 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11845 (defun org-refile-new-child (parent-target child)
11846 "Use refile target PARENT-TARGET to add new CHILD below it."
11847 (unless parent-target
11848 (error "Cannot find parent for new node"))
11849 (let ((file (nth 1 parent-target))
11850 (pos (nth 3 parent-target))
11851 level)
11852 (with-current-buffer (or (find-buffer-visiting file)
11853 (find-file-noselect file))
11854 (save-excursion
11855 (save-restriction
11856 (widen)
11857 (if pos
11858 (goto-char pos)
11859 (goto-char (point-max))
11860 (if (not (bolp)) (newline)))
11861 (when (looking-at org-outline-regexp)
11862 (setq level (funcall outline-level))
11863 (org-end-of-subtree t t))
11864 (org-back-over-empty-lines)
11865 (insert "\n" (make-string
11866 (if pos (org-get-valid-level level 1) 1) ?*)
11867 " " child "\n")
11868 (beginning-of-line 0)
11869 (list (concat (car parent-target) "/" child) file "" (point)))))))
11871 (defun org-olpath-completing-read (prompt collection &rest args)
11872 "Read an outline path like a file name."
11873 (let ((thetable collection)
11874 (org-completion-use-ido nil) ; does not work with ido.
11875 (org-completion-use-iswitchb nil)) ; or iswitchb
11876 (apply
11877 'org-icompleting-read prompt
11878 (lambda (string predicate &optional flag)
11879 (let (rtn r f (l (length string)))
11880 (cond
11881 ((eq flag nil)
11882 ;; try completion
11883 (try-completion string thetable))
11884 ((eq flag t)
11885 ;; all-completions
11886 (setq rtn (all-completions string thetable predicate))
11887 (mapcar
11888 (lambda (x)
11889 (setq r (substring x l))
11890 (if (string-match " ([^)]*)$" x)
11891 (setq f (match-string 0 x))
11892 (setq f ""))
11893 (if (string-match "/" r)
11894 (concat string (substring r 0 (match-end 0)) f)
11896 rtn))
11897 ((eq flag 'lambda)
11898 ;; exact match?
11899 (assoc string thetable)))))
11900 args)))
11902 ;;;; Dynamic blocks
11904 (defun org-find-dblock (name)
11905 "Find the first dynamic block with name NAME in the buffer.
11906 If not found, stay at current position and return nil."
11907 (let ((case-fold-search t) pos)
11908 (save-excursion
11909 (goto-char (point-min))
11910 (setq pos (and (re-search-forward
11911 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11912 (match-beginning 0))))
11913 (if pos (goto-char pos))
11914 pos))
11916 (defconst org-dblock-start-re
11917 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11918 "Matches the start line of a dynamic block, with parameters.")
11920 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11921 "Matches the end of a dynamic block.")
11923 (defun org-create-dblock (plist)
11924 "Create a dynamic block section, with parameters taken from PLIST.
11925 PLIST must contain a :name entry which is used as name of the block."
11926 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11927 (end-of-line 1)
11928 (newline))
11929 (let ((col (current-column))
11930 (name (plist-get plist :name)))
11931 (insert "#+BEGIN: " name)
11932 (while plist
11933 (if (eq (car plist) :name)
11934 (setq plist (cddr plist))
11935 (insert " " (prin1-to-string (pop plist)))))
11936 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11937 (beginning-of-line -2)))
11939 (defun org-prepare-dblock ()
11940 "Prepare dynamic block for refresh.
11941 This empties the block, puts the cursor at the insert position and returns
11942 the property list including an extra property :name with the block name."
11943 (unless (looking-at org-dblock-start-re)
11944 (user-error "Not at a dynamic block"))
11945 (let* ((begdel (1+ (match-end 0)))
11946 (name (org-no-properties (match-string 1)))
11947 (params (append (list :name name)
11948 (read (concat "(" (match-string 3) ")")))))
11949 (save-excursion
11950 (beginning-of-line 1)
11951 (skip-chars-forward " \t")
11952 (setq params (plist-put params :indentation-column (current-column))))
11953 (unless (re-search-forward org-dblock-end-re nil t)
11954 (error "Dynamic block not terminated"))
11955 (setq params
11956 (append params
11957 (list :content (buffer-substring
11958 begdel (match-beginning 0)))))
11959 (delete-region begdel (match-beginning 0))
11960 (goto-char begdel)
11961 (open-line 1)
11962 params))
11964 (defun org-map-dblocks (&optional command)
11965 "Apply COMMAND to all dynamic blocks in the current buffer.
11966 If COMMAND is not given, use `org-update-dblock'."
11967 (let ((cmd (or command 'org-update-dblock)))
11968 (save-excursion
11969 (goto-char (point-min))
11970 (while (re-search-forward org-dblock-start-re nil t)
11971 (goto-char (match-beginning 0))
11972 (save-excursion
11973 (condition-case nil
11974 (funcall cmd)
11975 (error (message "Error during update of dynamic block"))))
11976 (unless (re-search-forward org-dblock-end-re nil t)
11977 (error "Dynamic block not terminated"))))))
11979 (defun org-dblock-update (&optional arg)
11980 "User command for updating dynamic blocks.
11981 Update the dynamic block at point. With prefix ARG, update all dynamic
11982 blocks in the buffer."
11983 (interactive "P")
11984 (if arg
11985 (org-update-all-dblocks)
11986 (or (looking-at org-dblock-start-re)
11987 (org-beginning-of-dblock))
11988 (org-update-dblock)))
11990 (defun org-update-dblock ()
11991 "Update the dynamic block at point.
11992 This means to empty the block, parse for parameters and then call
11993 the correct writing function."
11994 (interactive)
11995 (save-excursion
11996 (let* ((win (selected-window))
11997 (pos (point))
11998 (line (org-current-line))
11999 (params (org-prepare-dblock))
12000 (name (plist-get params :name))
12001 (indent (plist-get params :indentation-column))
12002 (cmd (intern (concat "org-dblock-write:" name))))
12003 (message "Updating dynamic block `%s' at line %d..." name line)
12004 (funcall cmd params)
12005 (message "Updating dynamic block `%s' at line %d...done" name line)
12006 (goto-char pos)
12007 (when (and indent (> indent 0))
12008 (setq indent (make-string indent ?\ ))
12009 (save-excursion
12010 (select-window win)
12011 (org-beginning-of-dblock)
12012 (forward-line 1)
12013 (while (not (looking-at org-dblock-end-re))
12014 (insert indent)
12015 (beginning-of-line 2))
12016 (when (looking-at org-dblock-end-re)
12017 (and (looking-at "[ \t]+")
12018 (replace-match ""))
12019 (insert indent)))))))
12021 (defun org-beginning-of-dblock ()
12022 "Find the beginning of the dynamic block at point.
12023 Error if there is no such block at point."
12024 (let ((pos (point))
12025 beg)
12026 (end-of-line 1)
12027 (if (and (re-search-backward org-dblock-start-re nil t)
12028 (setq beg (match-beginning 0))
12029 (re-search-forward org-dblock-end-re nil t)
12030 (> (match-end 0) pos))
12031 (goto-char beg)
12032 (goto-char pos)
12033 (error "Not in a dynamic block"))))
12035 (defun org-update-all-dblocks ()
12036 "Update all dynamic blocks in the buffer.
12037 This function can be used in a hook."
12038 (interactive)
12039 (when (derived-mode-p 'org-mode)
12040 (org-map-dblocks 'org-update-dblock)))
12043 ;;;; Completion
12045 (defun org-get-export-keywords ()
12046 "Return a list of all currently understood export keywords.
12047 Export keywords include options, block names, attributes and
12048 keywords relative to each registered export back-end."
12049 (let (keywords)
12050 (dolist (backend
12051 (org-bound-and-true-p org-export--registered-backends)
12052 (delq nil keywords))
12053 ;; Back-end name (for keywords, like #+LATEX:)
12054 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12055 (dolist (option-entry (org-export-backend-options backend))
12056 ;; Back-end options.
12057 (push (nth 1 option-entry) keywords)))))
12059 (defconst org-options-keywords
12060 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12061 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12062 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12063 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12064 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12066 (defcustom org-structure-template-alist
12067 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12068 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12069 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12070 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12071 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12072 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12073 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12074 "<literal style=\"latex\">\n?\n</literal>")
12075 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12076 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12077 "<literal style=\"html\">\n?\n</literal>")
12078 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12079 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12080 ("A" "#+ASCII: " "")
12081 ("i" "#+INDEX: ?" "#+INDEX: ?")
12082 ("I" "#+INCLUDE: %file ?"
12083 "<include file=%file markup=\"?\">"))
12084 "Structure completion elements.
12085 This is a list of abbreviation keys and values. The value gets inserted
12086 if you type `<' followed by the key and then press the completion key,
12087 usually `M-TAB'. %file will be replaced by a file name after prompting
12088 for the file using completion. The cursor will be placed at the position
12089 of the `?' in the template.
12090 There are two templates for each key, the first uses the original Org syntax,
12091 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12092 the default when the /org-mtags.el/ module has been loaded. See also the
12093 variable `org-mtags-prefer-muse-templates'."
12094 :group 'org-completion
12095 :type '(repeat
12096 (list
12097 (string :tag "Key")
12098 (string :tag "Template")
12099 (string :tag "Muse Template"))))
12101 (defun org-try-structure-completion ()
12102 "Try to complete a structure template before point.
12103 This looks for strings like \"<e\" on an otherwise empty line and
12104 expands them."
12105 (let ((l (buffer-substring (point-at-bol) (point)))
12107 (when (and (looking-at "[ \t]*$")
12108 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12109 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12110 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12111 (match-beginning 1)) a)
12112 t)))
12114 (defun org-complete-expand-structure-template (start cell)
12115 "Expand a structure template."
12116 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12117 (rpl (nth (if musep 2 1) cell))
12118 (ind ""))
12119 (delete-region start (point))
12120 (when (string-match "\\`#\\+" rpl)
12121 (cond
12122 ((bolp))
12123 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12124 (setq ind (buffer-substring (point-at-bol) (point))))
12125 (t (newline))))
12126 (setq start (point))
12127 (if (string-match "%file" rpl)
12128 (setq rpl (replace-match
12129 (concat
12130 "\""
12131 (save-match-data
12132 (abbreviate-file-name (read-file-name "Include file: ")))
12133 "\"")
12134 t t rpl)))
12135 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12136 (concat "\n" ind)))
12137 (insert rpl)
12138 (if (re-search-backward "\\?" start t) (delete-char 1))))
12140 ;;;; TODO, DEADLINE, Comments
12142 (defun org-toggle-comment ()
12143 "Change the COMMENT state of an entry."
12144 (interactive)
12145 (save-excursion
12146 (org-back-to-heading)
12147 (let (case-fold-search)
12148 (cond
12149 ((looking-at (format org-heading-keyword-regexp-format
12150 org-comment-string))
12151 (goto-char (match-end 1))
12152 (looking-at (concat " +" org-comment-string))
12153 (replace-match "" t t)
12154 (when (eolp) (insert " ")))
12155 ((looking-at org-outline-regexp)
12156 (goto-char (match-end 0))
12157 (insert org-comment-string " "))))))
12159 (defvar org-last-todo-state-is-todo nil
12160 "This is non-nil when the last TODO state change led to a TODO state.
12161 If the last change removed the TODO tag or switched to DONE, then
12162 this is nil.")
12164 (defvar org-setting-tags nil) ; dynamically skipped
12166 (defvar org-todo-setup-filter-hook nil
12167 "Hook for functions that pre-filter todo specs.
12168 Each function takes a todo spec and returns either nil or the spec
12169 transformed into canonical form." )
12171 (defvar org-todo-get-default-hook nil
12172 "Hook for functions that get a default item for todo.
12173 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12174 nil or a string to be used for the todo mark." )
12176 (defvar org-agenda-headline-snapshot-before-repeat)
12178 (defun org-current-effective-time ()
12179 "Return current time adjusted for `org-extend-today-until' variable."
12180 (let* ((ct (org-current-time))
12181 (dct (decode-time ct))
12182 (ct1
12183 (cond
12184 (org-use-last-clock-out-time-as-effective-time
12185 (or (org-clock-get-last-clock-out-time) ct))
12186 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12187 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12188 (t ct))))
12189 ct1))
12191 (defun org-todo-yesterday (&optional arg)
12192 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12193 (interactive "P")
12194 (if (eq major-mode 'org-agenda-mode)
12195 (apply 'org-agenda-todo-yesterday arg)
12196 (let* ((hour (third (decode-time
12197 (org-current-time))))
12198 (org-extend-today-until (1+ hour)))
12199 (org-todo arg))))
12201 (defvar org-block-entry-blocking ""
12202 "First entry preventing the TODO state change.")
12204 (defun org-todo (&optional arg)
12205 "Change the TODO state of an item.
12206 The state of an item is given by a keyword at the start of the heading,
12207 like
12208 *** TODO Write paper
12209 *** DONE Call mom
12211 The different keywords are specified in the variable `org-todo-keywords'.
12212 By default the available states are \"TODO\" and \"DONE\".
12213 So for this example: when the item starts with TODO, it is changed to DONE.
12214 When it starts with DONE, the DONE is removed. And when neither TODO nor
12215 DONE are present, add TODO at the beginning of the heading.
12217 With \\[universal-argument] prefix arg, use completion to determine the new \
12218 state.
12219 With numeric prefix arg, switch to that state.
12220 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12221 keywords (nextset).
12222 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12223 With a numeric prefix arg of 0, inhibit note taking for the change.
12225 For calling through lisp, arg is also interpreted in the following way:
12226 `none' -> empty state
12227 \"\" (empty string) -> switch to empty state
12228 `done' -> switch to DONE
12229 `nextset' -> switch to the next set of keywords
12230 `previousset' -> switch to the previous set of keywords
12231 \"WAITING\" -> switch to the specified keyword, but only if it
12232 really is a member of `org-todo-keywords'."
12233 (interactive "P")
12234 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12235 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12236 'region-start-level 'region))
12237 org-loop-over-headlines-in-active-region)
12238 (org-map-entries
12239 `(org-todo ,arg)
12240 org-loop-over-headlines-in-active-region
12241 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12242 (if (equal arg '(16)) (setq arg 'nextset))
12243 (let ((org-blocker-hook org-blocker-hook)
12244 commentp
12245 case-fold-search)
12246 (when (equal arg '(64))
12247 (setq arg nil org-blocker-hook nil))
12248 (when (and org-blocker-hook
12249 (or org-inhibit-blocking
12250 (org-entry-get nil "NOBLOCKING")))
12251 (setq org-blocker-hook nil))
12252 (save-excursion
12253 (catch 'exit
12254 (org-back-to-heading t)
12255 (when (looking-at (concat "^\\*+ " org-comment-string))
12256 (org-toggle-comment)
12257 (setq commentp t))
12258 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12259 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12260 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12261 (let* ((match-data (match-data))
12262 (startpos (point-at-bol))
12263 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12264 (org-log-done org-log-done)
12265 (org-log-repeat org-log-repeat)
12266 (org-todo-log-states org-todo-log-states)
12267 (org-inhibit-logging
12268 (if (equal arg 0)
12269 (progn (setq arg nil) 'note) org-inhibit-logging))
12270 (this (match-string 1))
12271 (hl-pos (match-beginning 0))
12272 (head (org-get-todo-sequence-head this))
12273 (ass (assoc head org-todo-kwd-alist))
12274 (interpret (nth 1 ass))
12275 (done-word (nth 3 ass))
12276 (final-done-word (nth 4 ass))
12277 (org-last-state (or this ""))
12278 (completion-ignore-case t)
12279 (member (member this org-todo-keywords-1))
12280 (tail (cdr member))
12281 (org-state (cond
12282 ((and org-todo-key-trigger
12283 (or (and (equal arg '(4))
12284 (eq org-use-fast-todo-selection 'prefix))
12285 (and (not arg) org-use-fast-todo-selection
12286 (not (eq org-use-fast-todo-selection
12287 'prefix)))))
12288 ;; Use fast selection
12289 (org-fast-todo-selection))
12290 ((and (equal arg '(4))
12291 (or (not org-use-fast-todo-selection)
12292 (not org-todo-key-trigger)))
12293 ;; Read a state with completion
12294 (org-icompleting-read
12295 "State: " (mapcar 'list org-todo-keywords-1)
12296 nil t))
12297 ((eq arg 'right)
12298 (if this
12299 (if tail (car tail) nil)
12300 (car org-todo-keywords-1)))
12301 ((eq arg 'left)
12302 (if (equal member org-todo-keywords-1)
12304 (if this
12305 (nth (- (length org-todo-keywords-1)
12306 (length tail) 2)
12307 org-todo-keywords-1)
12308 (org-last org-todo-keywords-1))))
12309 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12310 (setq arg nil))) ; hack to fall back to cycling
12311 (arg
12312 ;; user or caller requests a specific state
12313 (cond
12314 ((equal arg "") nil)
12315 ((eq arg 'none) nil)
12316 ((eq arg 'done) (or done-word (car org-done-keywords)))
12317 ((eq arg 'nextset)
12318 (or (car (cdr (member head org-todo-heads)))
12319 (car org-todo-heads)))
12320 ((eq arg 'previousset)
12321 (let ((org-todo-heads (reverse org-todo-heads)))
12322 (or (car (cdr (member head org-todo-heads)))
12323 (car org-todo-heads))))
12324 ((car (member arg org-todo-keywords-1)))
12325 ((stringp arg)
12326 (user-error "State `%s' not valid in this file" arg))
12327 ((nth (1- (prefix-numeric-value arg))
12328 org-todo-keywords-1))))
12329 ((null member) (or head (car org-todo-keywords-1)))
12330 ((equal this final-done-word) nil) ;; -> make empty
12331 ((null tail) nil) ;; -> first entry
12332 ((memq interpret '(type priority))
12333 (if (eq this-command last-command)
12334 (car tail)
12335 (if (> (length tail) 0)
12336 (or done-word (car org-done-keywords))
12337 nil)))
12339 (car tail))))
12340 (org-state (or
12341 (run-hook-with-args-until-success
12342 'org-todo-get-default-hook org-state org-last-state)
12343 org-state))
12344 (next (if org-state (concat " " org-state " ") " "))
12345 (change-plist (list :type 'todo-state-change :from this :to org-state
12346 :position startpos))
12347 dolog now-done-p)
12348 (when org-blocker-hook
12349 (setq org-last-todo-state-is-todo
12350 (not (member this org-done-keywords)))
12351 (unless (save-excursion
12352 (save-match-data
12353 (org-with-wide-buffer
12354 (run-hook-with-args-until-failure
12355 'org-blocker-hook change-plist))))
12356 (if (org-called-interactively-p 'interactive)
12357 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12358 this org-state org-block-entry-blocking)
12359 ;; fail silently
12360 (message "TODO state change from %s to %s blocked (by \"%s\")"
12361 this org-state org-block-entry-blocking)
12362 (throw 'exit nil))))
12363 (store-match-data match-data)
12364 (replace-match next t t)
12365 (unless (pos-visible-in-window-p hl-pos)
12366 (message "TODO state changed to %s" (org-trim next)))
12367 (unless head
12368 (setq head (org-get-todo-sequence-head org-state)
12369 ass (assoc head org-todo-kwd-alist)
12370 interpret (nth 1 ass)
12371 done-word (nth 3 ass)
12372 final-done-word (nth 4 ass)))
12373 (when (memq arg '(nextset previousset))
12374 (message "Keyword-Set %d/%d: %s"
12375 (- (length org-todo-sets) -1
12376 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12377 (length org-todo-sets)
12378 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12379 (setq org-last-todo-state-is-todo
12380 (not (member org-state org-done-keywords)))
12381 (setq now-done-p (and (member org-state org-done-keywords)
12382 (not (member this org-done-keywords))))
12383 (and logging (org-local-logging logging))
12384 (when (and (or org-todo-log-states org-log-done)
12385 (not (eq org-inhibit-logging t))
12386 (not (memq arg '(nextset previousset))))
12387 ;; we need to look at recording a time and note
12388 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12389 (nth 2 (assoc this org-todo-log-states))))
12390 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12391 (setq dolog 'time))
12392 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12393 (and org-state
12394 (member org-state org-not-done-keywords)
12395 (not (member this org-not-done-keywords))))
12396 ;; This is now a todo state and was not one before
12397 ;; If there was a CLOSED time stamp, get rid of it.
12398 (org-add-planning-info nil nil 'closed))
12399 (when (and now-done-p org-log-done)
12400 ;; It is now done, and it was not done before
12401 (org-add-planning-info 'closed (org-current-effective-time))
12402 (if (and (not dolog) (eq 'note org-log-done))
12403 (org-add-log-setup 'done org-state this 'findpos 'note)))
12404 (when (and org-state dolog)
12405 ;; This is a non-nil state, and we need to log it
12406 (org-add-log-setup 'state org-state this 'findpos dolog)))
12407 ;; Fixup tag positioning
12408 (org-todo-trigger-tag-changes org-state)
12409 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12410 (when org-provide-todo-statistics
12411 (org-update-parent-todo-statistics))
12412 (run-hooks 'org-after-todo-state-change-hook)
12413 (if (and arg (not (member org-state org-done-keywords)))
12414 (setq head (org-get-todo-sequence-head org-state)))
12415 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12416 ;; Do we need to trigger a repeat?
12417 (when now-done-p
12418 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12419 ;; This is for the agenda, take a snapshot of the headline.
12420 (save-match-data
12421 (setq org-agenda-headline-snapshot-before-repeat
12422 (org-get-heading))))
12423 (org-auto-repeat-maybe org-state))
12424 ;; Fixup cursor location if close to the keyword
12425 (if (and (outline-on-heading-p)
12426 (not (bolp))
12427 (save-excursion (beginning-of-line 1)
12428 (looking-at org-todo-line-regexp))
12429 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12430 (progn
12431 (goto-char (or (match-end 2) (match-end 1)))
12432 (and (looking-at " ") (just-one-space))))
12433 (when org-trigger-hook
12434 (save-excursion
12435 (run-hook-with-args 'org-trigger-hook change-plist)))
12436 (when commentp (org-toggle-comment))))))))
12438 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12439 "Block turning an entry into a TODO, using the hierarchy.
12440 This checks whether the current task should be blocked from state
12441 changes. Such blocking occurs when:
12443 1. The task has children which are not all in a completed state.
12445 2. A task has a parent with the property :ORDERED:, and there
12446 are siblings prior to the current task with incomplete
12447 status.
12449 3. The parent of the task is blocked because it has siblings that should
12450 be done first, or is child of a block grandparent TODO entry."
12452 (if (not org-enforce-todo-dependencies)
12453 t ; if locally turned off don't block
12454 (catch 'dont-block
12455 ;; If this is not a todo state change, or if this entry is already DONE,
12456 ;; do not block
12457 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12458 (member (plist-get change-plist :from)
12459 (cons 'done org-done-keywords))
12460 (member (plist-get change-plist :to)
12461 (cons 'todo org-not-done-keywords))
12462 (not (plist-get change-plist :to)))
12463 (throw 'dont-block t))
12464 ;; If this task has children, and any are undone, it's blocked
12465 (save-excursion
12466 (org-back-to-heading t)
12467 (let ((this-level (funcall outline-level)))
12468 (outline-next-heading)
12469 (let ((child-level (funcall outline-level)))
12470 (while (and (not (eobp))
12471 (> child-level this-level))
12472 ;; this todo has children, check whether they are all
12473 ;; completed
12474 (if (and (not (org-entry-is-done-p))
12475 (org-entry-is-todo-p))
12476 (progn (setq org-block-entry-blocking (org-get-heading))
12477 (throw 'dont-block nil)))
12478 (outline-next-heading)
12479 (setq child-level (funcall outline-level))))))
12480 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12481 ;; any previous siblings are undone, it's blocked
12482 (save-excursion
12483 (org-back-to-heading t)
12484 (let* ((pos (point))
12485 (parent-pos (and (org-up-heading-safe) (point))))
12486 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12487 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12488 (forward-line 1)
12489 (re-search-forward org-not-done-heading-regexp pos t))
12490 (setq org-block-entry-blocking (match-string 0))
12491 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12492 ;; Search further up the hierarchy, to see if an ancestor is blocked
12493 (while t
12494 (goto-char parent-pos)
12495 (if (not (looking-at org-not-done-heading-regexp))
12496 (throw 'dont-block t)) ; do not block, parent is not a TODO
12497 (setq pos (point))
12498 (setq parent-pos (and (org-up-heading-safe) (point)))
12499 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12500 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12501 (forward-line 1)
12502 (re-search-forward org-not-done-heading-regexp pos t)
12503 (setq org-block-entry-blocking (org-get-heading)))
12504 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12506 (defcustom org-track-ordered-property-with-tag nil
12507 "Should the ORDERED property also be shown as a tag?
12508 The ORDERED property decides if an entry should require subtasks to be
12509 completed in sequence. Since a property is not very visible, setting
12510 this option means that toggling the ORDERED property with the command
12511 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12512 not relevant for the behavior, but it makes things more visible.
12514 Note that toggling the tag with tags commands will not change the property
12515 and therefore not influence behavior!
12517 This can be t, meaning the tag ORDERED should be used, It can also be a
12518 string to select a different tag for this task."
12519 :group 'org-todo
12520 :type '(choice
12521 (const :tag "No tracking" nil)
12522 (const :tag "Track with ORDERED tag" t)
12523 (string :tag "Use other tag")))
12525 (defun org-toggle-ordered-property ()
12526 "Toggle the ORDERED property of the current entry.
12527 For better visibility, you can track the value of this property with a tag.
12528 See variable `org-track-ordered-property-with-tag'."
12529 (interactive)
12530 (let* ((t1 org-track-ordered-property-with-tag)
12531 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12532 (save-excursion
12533 (org-back-to-heading)
12534 (if (org-entry-get nil "ORDERED")
12535 (progn
12536 (org-delete-property "ORDERED" "PROPERTIES")
12537 (and tag (org-toggle-tag tag 'off))
12538 (message "Subtasks can be completed in arbitrary order"))
12539 (org-entry-put nil "ORDERED" "t")
12540 (and tag (org-toggle-tag tag 'on))
12541 (message "Subtasks must be completed in sequence")))))
12543 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12544 (defun org-block-todo-from-checkboxes (change-plist)
12545 "Block turning an entry into a TODO, using checkboxes.
12546 This checks whether the current task should be blocked from state
12547 changes because there are unchecked boxes in this entry."
12548 (if (not org-enforce-todo-checkbox-dependencies)
12549 t ; if locally turned off don't block
12550 (catch 'dont-block
12551 ;; If this is not a todo state change, or if this entry is already DONE,
12552 ;; do not block
12553 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12554 (member (plist-get change-plist :from)
12555 (cons 'done org-done-keywords))
12556 (member (plist-get change-plist :to)
12557 (cons 'todo org-not-done-keywords))
12558 (not (plist-get change-plist :to)))
12559 (throw 'dont-block t))
12560 ;; If this task has checkboxes that are not checked, it's blocked
12561 (save-excursion
12562 (org-back-to-heading t)
12563 (let ((beg (point)) end)
12564 (outline-next-heading)
12565 (setq end (point))
12566 (goto-char beg)
12567 (if (org-list-search-forward
12568 (concat (org-item-beginning-re)
12569 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12570 "\\[[- ]\\]")
12571 end t)
12572 (progn
12573 (if (boundp 'org-blocked-by-checkboxes)
12574 (setq org-blocked-by-checkboxes t))
12575 (throw 'dont-block nil)))))
12576 t))) ; do not block
12578 (defun org-entry-blocked-p ()
12579 "Is the current entry blocked?"
12580 (org-with-silent-modifications
12581 (if (org-entry-get nil "NOBLOCKING")
12582 nil ;; Never block this entry
12583 (not (run-hook-with-args-until-failure
12584 'org-blocker-hook
12585 (list :type 'todo-state-change
12586 :position (point)
12587 :from 'todo
12588 :to 'done))))))
12590 (defun org-update-statistics-cookies (all)
12591 "Update the statistics cookie, either from TODO or from checkboxes.
12592 This should be called with the cursor in a line with a statistics cookie."
12593 (interactive "P")
12594 (if all
12595 (progn
12596 (org-update-checkbox-count 'all)
12597 (org-map-entries 'org-update-parent-todo-statistics))
12598 (if (not (org-at-heading-p))
12599 (org-update-checkbox-count)
12600 (let ((pos (point-marker))
12601 end l1 l2)
12602 (ignore-errors (org-back-to-heading t))
12603 (if (not (org-at-heading-p))
12604 (org-update-checkbox-count)
12605 (setq l1 (org-outline-level))
12606 (setq end (save-excursion
12607 (outline-next-heading)
12608 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12609 (point)))
12610 (if (and (save-excursion
12611 (re-search-forward
12612 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12613 (not (save-excursion (re-search-forward
12614 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12615 (org-update-checkbox-count)
12616 (if (and l2 (> l2 l1))
12617 (progn
12618 (goto-char end)
12619 (org-update-parent-todo-statistics))
12620 (goto-char pos)
12621 (beginning-of-line 1)
12622 (while (re-search-forward
12623 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12624 (point-at-eol) t)
12625 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12626 (goto-char pos)
12627 (move-marker pos nil)))))
12629 (defvar org-entry-property-inherited-from) ;; defined below
12630 (defun org-update-parent-todo-statistics ()
12631 "Update any statistics cookie in the parent of the current headline.
12632 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12633 the entire subtree and this will travel up the hierarchy and update
12634 statistics everywhere."
12635 (let* ((prop (save-excursion (org-up-heading-safe)
12636 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12637 (recursive (or (not org-hierarchical-todo-statistics)
12638 (and prop (string-match "\\<recursive\\>" prop))))
12639 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12641 (first t)
12642 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12643 level ltoggle l1 new ndel
12644 (cnt-all 0) (cnt-done 0) is-percent kwd
12645 checkbox-beg ov ovs ove cookie-present)
12646 (catch 'exit
12647 (save-excursion
12648 (beginning-of-line 1)
12649 (setq ltoggle (funcall outline-level))
12650 ;; Three situations are to consider:
12652 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12653 ;; to the top-level ancestor on the headline;
12655 ;; 2. If parent has "recursive" property, repeat up to the
12656 ;; headline setting that property, taking inheritance into
12657 ;; account;
12659 ;; 3. Else, move up to direct parent and proceed only once.
12660 (while (and (setq level (org-up-heading-safe))
12661 (or recursive first)
12662 (>= (point) lim))
12663 (setq first nil cookie-present nil)
12664 (unless (and level
12665 (not (string-match
12666 "\\<checkbox\\>"
12667 (downcase (or (org-entry-get nil "COOKIE_DATA")
12668 "")))))
12669 (throw 'exit nil))
12670 (while (re-search-forward box-re (point-at-eol) t)
12671 (setq cnt-all 0 cnt-done 0 cookie-present t)
12672 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12673 (save-match-data
12674 (unless (outline-next-heading) (throw 'exit nil))
12675 (while (and (looking-at org-complex-heading-regexp)
12676 (> (setq l1 (length (match-string 1))) level))
12677 (setq kwd (and (or recursive (= l1 ltoggle))
12678 (match-string 2)))
12679 (if (or (eq org-provide-todo-statistics 'all-headlines)
12680 (and (listp org-provide-todo-statistics)
12681 (or (member kwd org-provide-todo-statistics)
12682 (member kwd org-done-keywords))))
12683 (setq cnt-all (1+ cnt-all))
12684 (if (eq org-provide-todo-statistics t)
12685 (and kwd (setq cnt-all (1+ cnt-all)))))
12686 (and (member kwd org-done-keywords)
12687 (setq cnt-done (1+ cnt-done)))
12688 (outline-next-heading)))
12689 (setq new
12690 (if is-percent
12691 (format "[%d%%]" (floor (* 100.0 cnt-done)
12692 (max 1 cnt-all)))
12693 (format "[%d/%d]" cnt-done cnt-all))
12694 ndel (- (match-end 0) checkbox-beg))
12695 ;; handle overlays when updating cookie from column view
12696 (when (setq ov (car (overlays-at checkbox-beg)))
12697 (setq ovs (overlay-start ov) ove (overlay-end ov))
12698 (delete-overlay ov))
12699 (goto-char checkbox-beg)
12700 (insert new)
12701 (delete-region (point) (+ (point) ndel))
12702 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12703 (when ov (move-overlay ov ovs ove)))
12704 (when cookie-present
12705 (run-hook-with-args 'org-after-todo-statistics-hook
12706 cnt-done (- cnt-all cnt-done))))))
12707 (run-hooks 'org-todo-statistics-hook)))
12709 (defvar org-after-todo-statistics-hook nil
12710 "Hook that is called after a TODO statistics cookie has been updated.
12711 Each function is called with two arguments: the number of not-done entries
12712 and the number of done entries.
12714 For example, the following function, when added to this hook, will switch
12715 an entry to DONE when all children are done, and back to TODO when new
12716 entries are set to a TODO status. Note that this hook is only called
12717 when there is a statistics cookie in the headline!
12719 (defun org-summary-todo (n-done n-not-done)
12720 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12721 (let (org-log-done org-log-states) ; turn off logging
12722 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12725 (defvar org-todo-statistics-hook nil
12726 "Hook that is run whenever Org thinks TODO statistics should be updated.
12727 This hook runs even if there is no statistics cookie present, in which case
12728 `org-after-todo-statistics-hook' would not run.")
12730 (defun org-todo-trigger-tag-changes (state)
12731 "Apply the changes defined in `org-todo-state-tags-triggers'."
12732 (let ((l org-todo-state-tags-triggers)
12733 changes)
12734 (when (or (not state) (equal state ""))
12735 (setq changes (append changes (cdr (assoc "" l)))))
12736 (when (and (stringp state) (> (length state) 0))
12737 (setq changes (append changes (cdr (assoc state l)))))
12738 (when (member state org-not-done-keywords)
12739 (setq changes (append changes (cdr (assoc 'todo l)))))
12740 (when (member state org-done-keywords)
12741 (setq changes (append changes (cdr (assoc 'done l)))))
12742 (dolist (c changes)
12743 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12745 (defun org-local-logging (value)
12746 "Get logging settings from a property VALUE."
12747 ;; Directly set the variables, they are already local.
12748 (setq org-log-done nil
12749 org-log-repeat nil
12750 org-todo-log-states nil)
12751 (dolist (w (org-split-string value))
12752 (let* (a)
12753 (cond
12754 ((setq a (assoc w org-startup-options))
12755 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12756 (set (nth 1 a) (nth 2 a))))
12757 ((setq a (org-extract-log-state-settings w))
12758 (and (member (car a) org-todo-keywords-1)
12759 (push a org-todo-log-states)))))))
12761 (defun org-get-todo-sequence-head (kwd)
12762 "Return the head of the TODO sequence to which KWD belongs.
12763 If KWD is not set, check if there is a text property remembering the
12764 right sequence."
12765 (let (p)
12766 (cond
12767 ((not kwd)
12768 (or (get-text-property (point-at-bol) 'org-todo-head)
12769 (progn
12770 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12771 nil (point-at-eol)))
12772 (get-text-property p 'org-todo-head))))
12773 ((not (member kwd org-todo-keywords-1))
12774 (car org-todo-keywords-1))
12775 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12777 (defun org-fast-todo-selection ()
12778 "Fast TODO keyword selection with single keys.
12779 Returns the new TODO keyword, or nil if no state change should occur."
12780 (let* ((fulltable org-todo-key-alist)
12781 (done-keywords org-done-keywords) ;; needed for the faces.
12782 (maxlen (apply 'max (mapcar
12783 (lambda (x)
12784 (if (stringp (car x)) (string-width (car x)) 0))
12785 fulltable)))
12786 (expert nil)
12787 (fwidth (+ maxlen 3 1 3))
12788 (ncol (/ (- (window-width) 4) fwidth))
12789 tg cnt c tbl
12790 groups ingroup)
12791 (save-excursion
12792 (save-window-excursion
12793 (if expert
12794 (set-buffer (get-buffer-create " *Org todo*"))
12795 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12796 (erase-buffer)
12797 (org-set-local 'org-done-keywords done-keywords)
12798 (setq tbl fulltable cnt 0)
12799 (dolist (e tbl)
12800 (cond
12801 ((equal e '(:startgroup))
12802 (push '() groups) (setq ingroup t)
12803 (when (not (= cnt 0))
12804 (setq cnt 0)
12805 (insert "\n"))
12806 (insert "{ "))
12807 ((equal e '(:endgroup))
12808 (setq ingroup nil cnt 0)
12809 (insert "}\n"))
12810 ((equal e '(:newline))
12811 (when (not (= cnt 0))
12812 (setq cnt 0)
12813 (insert "\n")
12814 (setq e (car tbl))
12815 (while (equal (car tbl) '(:newline))
12816 (insert "\n")
12817 (setq tbl (cdr tbl)))))
12819 (setq tg (car e) c (cdr e))
12820 (if ingroup (push tg (car groups)))
12821 (setq tg (org-add-props tg nil 'face
12822 (org-get-todo-face tg)))
12823 (if (and (= cnt 0) (not ingroup)) (insert " "))
12824 (insert "[" c "] " tg (make-string
12825 (- fwidth 4 (length tg)) ?\ ))
12826 (when (= (setq cnt (1+ cnt)) ncol)
12827 (insert "\n")
12828 (if ingroup (insert " "))
12829 (setq cnt 0)))))
12830 (insert "\n")
12831 (goto-char (point-min))
12832 (if (not expert) (org-fit-window-to-buffer))
12833 (message "[a-z..]:Set [SPC]:clear")
12834 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12835 (cond
12836 ((or (= c ?\C-g)
12837 (and (= c ?q) (not (rassoc c fulltable))))
12838 (setq quit-flag t))
12839 ((= c ?\ ) nil)
12840 ((setq e (rassoc c fulltable) tg (car e))
12842 (t (setq quit-flag t)))))))
12844 (defun org-entry-is-todo-p ()
12845 (member (org-get-todo-state) org-not-done-keywords))
12847 (defun org-entry-is-done-p ()
12848 (member (org-get-todo-state) org-done-keywords))
12850 (defun org-get-todo-state ()
12851 "Return the TODO keyword of the current subtree."
12852 (save-excursion
12853 (org-back-to-heading t)
12854 (and (looking-at org-todo-line-regexp)
12855 (match-end 2)
12856 (match-string 2))))
12858 (defun org-at-date-range-p (&optional inactive-ok)
12859 "Is the cursor inside a date range?"
12860 (interactive)
12861 (save-excursion
12862 (catch 'exit
12863 (let ((pos (point)))
12864 (skip-chars-backward "^[<\r\n")
12865 (skip-chars-backward "<[")
12866 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12867 (>= (match-end 0) pos)
12868 (throw 'exit t))
12869 (skip-chars-backward "^<[\r\n")
12870 (skip-chars-backward "<[")
12871 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12872 (>= (match-end 0) pos)
12873 (throw 'exit t)))
12874 nil)))
12876 (defun org-get-repeat (&optional tagline)
12877 "Check if there is a deadline/schedule with repeater in this entry."
12878 (save-match-data
12879 (save-excursion
12880 (org-back-to-heading t)
12881 (and (re-search-forward (if tagline
12882 (concat tagline "\\s-*" org-repeat-re)
12883 org-repeat-re)
12884 (org-entry-end-position) t)
12885 (match-string-no-properties 1)))))
12887 (defvar org-last-changed-timestamp)
12888 (defvar org-last-inserted-timestamp)
12889 (defvar org-log-post-message)
12890 (defvar org-log-note-purpose)
12891 (defvar org-log-note-how)
12892 (defvar org-log-note-extra)
12893 (defun org-auto-repeat-maybe (done-word)
12894 "Check if the current headline contains a repeated deadline/schedule.
12895 If yes, set TODO state back to what it was and change the base date
12896 of repeating deadline/scheduled time stamps to new date.
12897 This function is run automatically after each state change to a DONE state."
12898 ;; last-state is dynamically scoped into this function
12899 (let* ((repeat (org-get-repeat))
12900 (aa (assoc org-last-state org-todo-kwd-alist))
12901 (interpret (nth 1 aa))
12902 (head (nth 2 aa))
12903 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12904 (msg "Entry repeats: ")
12905 (org-log-done nil)
12906 (org-todo-log-states nil)
12907 re type n what ts time to-state)
12908 (when repeat
12909 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12910 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12911 org-todo-repeat-to-state))
12912 (unless (and to-state (member to-state org-todo-keywords-1))
12913 (setq to-state (if (eq interpret 'type) org-last-state head)))
12914 (org-todo to-state)
12915 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12916 (org-entry-put nil "LAST_REPEAT" (format-time-string
12917 (org-time-stamp-format t t))))
12918 (when org-log-repeat
12919 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12920 (memq 'org-add-log-note post-command-hook))
12921 ;; OK, we are already setup for some record
12922 (if (eq org-log-repeat 'note)
12923 ;; make sure we take a note, not only a time stamp
12924 (setq org-log-note-how 'note))
12925 ;; Set up for taking a record
12926 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12927 org-last-state
12928 'findpos org-log-repeat)))
12929 (org-back-to-heading t)
12930 (org-add-planning-info nil nil 'closed)
12931 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12932 org-deadline-time-regexp "\\)\\|\\("
12933 org-ts-regexp "\\)"))
12934 (while (re-search-forward
12935 re (save-excursion (outline-next-heading) (point)) t)
12936 (setq type (if (match-end 1) org-scheduled-string
12937 (if (match-end 3) org-deadline-string "Plain:"))
12938 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12939 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12940 (setq n (string-to-number (match-string 2 ts))
12941 what (match-string 3 ts))
12942 (if (equal what "w") (setq n (* n 7) what "d"))
12943 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12944 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12945 ;; Preparation, see if we need to modify the start date for the change
12946 (when (match-end 1)
12947 (setq time (save-match-data (org-time-string-to-time ts)))
12948 (cond
12949 ((equal (match-string 1 ts) ".")
12950 ;; Shift starting date to today
12951 (org-timestamp-change
12952 (- (org-today) (time-to-days time))
12953 'day))
12954 ((equal (match-string 1 ts) "+")
12955 (let ((nshiftmax 10) (nshift 0))
12956 (while (or (= nshift 0)
12957 (<= (time-to-days time)
12958 (time-to-days (current-time))))
12959 (when (= (incf nshift) nshiftmax)
12960 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12961 (error "Abort")))
12962 (org-timestamp-change n (cdr (assoc what whata)))
12963 (org-at-timestamp-p t)
12964 (setq ts (match-string 1))
12965 (setq time (save-match-data (org-time-string-to-time ts)))))
12966 (org-timestamp-change (- n) (cdr (assoc what whata)))
12967 ;; rematch, so that we have everything in place for the real shift
12968 (org-at-timestamp-p t)
12969 (setq ts (match-string 1))
12970 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12971 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12972 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12973 (setq org-log-post-message msg)
12974 (message "%s" msg))))
12976 (defun org-show-todo-tree (arg)
12977 "Make a compact tree which shows all headlines marked with TODO.
12978 The tree will show the lines where the regexp matches, and all higher
12979 headlines above the match.
12980 With a \\[universal-argument] prefix, prompt for a regexp to match.
12981 With a numeric prefix N, construct a sparse tree for the Nth element
12982 of `org-todo-keywords-1'."
12983 (interactive "P")
12984 (let ((case-fold-search nil)
12985 (kwd-re
12986 (cond ((null arg) org-not-done-regexp)
12987 ((equal arg '(4))
12988 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12989 (mapcar 'list org-todo-keywords-1))))
12990 (concat "\\("
12991 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12992 "\\)\\>")))
12993 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12994 (regexp-quote (nth (1- (prefix-numeric-value arg))
12995 org-todo-keywords-1)))
12996 (t (user-error "Invalid prefix argument: %s" arg)))))
12997 (message "%d TODO entries found"
12998 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13000 (defun org-deadline (arg &optional time)
13001 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13002 With one universal prefix argument, remove any deadline from the item.
13003 With two universal prefix arguments, prompt for a warning delay.
13004 With argument TIME, set the deadline at the corresponding date. TIME
13005 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13006 (interactive "P")
13007 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13008 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13009 'region-start-level 'region))
13010 org-loop-over-headlines-in-active-region)
13011 (org-map-entries
13012 `(org-deadline ',arg ,time)
13013 org-loop-over-headlines-in-active-region
13014 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13015 (let* ((old-date (org-entry-get nil "DEADLINE"))
13016 (old-date-time (if old-date (org-time-string-to-time old-date)))
13017 (repeater (and old-date
13018 (string-match
13019 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13020 old-date)
13021 (match-string 1 old-date))))
13022 (cond
13023 ((equal arg '(4))
13024 (when (and old-date org-log-redeadline)
13025 (org-add-log-setup 'deldeadline nil old-date 'findpos
13026 org-log-redeadline))
13027 (org-remove-timestamp-with-keyword org-deadline-string)
13028 (message "Item no longer has a deadline."))
13029 ((equal arg '(16))
13030 (save-excursion
13031 (org-back-to-heading t)
13032 (if (re-search-forward
13033 org-deadline-time-regexp
13034 (save-excursion (outline-next-heading) (point)) t)
13035 (let* ((rpl0 (match-string 1))
13036 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13037 (replace-match
13038 (concat org-deadline-string
13039 " <" rpl
13040 (format " -%dd"
13041 (abs
13042 (- (time-to-days
13043 (save-match-data
13044 (org-read-date nil t nil "Warn starting from" old-date-time)))
13045 (time-to-days old-date-time))))
13046 ">") t t))
13047 (user-error "No deadline information to update"))))
13049 (org-add-planning-info 'deadline time 'closed)
13050 (when (and old-date org-log-redeadline
13051 (not (equal old-date
13052 (substring org-last-inserted-timestamp 1 -1))))
13053 (org-add-log-setup 'redeadline nil old-date 'findpos
13054 org-log-redeadline))
13055 (when repeater
13056 (save-excursion
13057 (org-back-to-heading t)
13058 (when (re-search-forward (concat org-deadline-string " "
13059 org-last-inserted-timestamp)
13060 (save-excursion
13061 (outline-next-heading) (point)) t)
13062 (goto-char (1- (match-end 0)))
13063 (insert " " repeater)
13064 (setq org-last-inserted-timestamp
13065 (concat (substring org-last-inserted-timestamp 0 -1)
13066 " " repeater
13067 (substring org-last-inserted-timestamp -1))))))
13068 (message "Deadline on %s" org-last-inserted-timestamp))))))
13070 (defun org-schedule (arg &optional time)
13071 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13072 With one universal prefix argument, remove any scheduling date from the item.
13073 With two universal prefix arguments, prompt for a delay cookie.
13074 With argument TIME, scheduled at the corresponding date. TIME can
13075 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13076 (interactive "P")
13077 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13078 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13079 'region-start-level 'region))
13080 org-loop-over-headlines-in-active-region)
13081 (org-map-entries
13082 `(org-schedule ',arg ,time)
13083 org-loop-over-headlines-in-active-region
13084 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13085 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13086 (old-date-time (if old-date (org-time-string-to-time old-date)))
13087 (repeater (and old-date
13088 (string-match
13089 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13090 old-date)
13091 (match-string 1 old-date))))
13092 (cond
13093 ((equal arg '(4))
13094 (progn
13095 (when (and old-date org-log-reschedule)
13096 (org-add-log-setup 'delschedule nil old-date 'findpos
13097 org-log-reschedule))
13098 (org-remove-timestamp-with-keyword org-scheduled-string)
13099 (message "Item is no longer scheduled.")))
13100 ((equal arg '(16))
13101 (save-excursion
13102 (org-back-to-heading t)
13103 (if (re-search-forward
13104 org-scheduled-time-regexp
13105 (save-excursion (outline-next-heading) (point)) t)
13106 (let* ((rpl0 (match-string 1))
13107 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13108 (replace-match
13109 (concat org-scheduled-string
13110 " <" rpl
13111 (format " -%dd"
13112 (abs
13113 (- (time-to-days
13114 (save-match-data
13115 (org-read-date nil t nil "Delay until" old-date-time)))
13116 (time-to-days old-date-time))))
13117 ">") t t))
13118 (user-error "No scheduled information to update"))))
13120 (org-add-planning-info 'scheduled time 'closed)
13121 (when (and old-date org-log-reschedule
13122 (not (equal old-date
13123 (substring org-last-inserted-timestamp 1 -1))))
13124 (org-add-log-setup 'reschedule nil old-date 'findpos
13125 org-log-reschedule))
13126 (when repeater
13127 (save-excursion
13128 (org-back-to-heading t)
13129 (when (re-search-forward (concat org-scheduled-string " "
13130 org-last-inserted-timestamp)
13131 (save-excursion
13132 (outline-next-heading) (point)) t)
13133 (goto-char (1- (match-end 0)))
13134 (insert " " repeater)
13135 (setq org-last-inserted-timestamp
13136 (concat (substring org-last-inserted-timestamp 0 -1)
13137 " " repeater
13138 (substring org-last-inserted-timestamp -1))))))
13139 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13141 (defun org-get-scheduled-time (pom &optional inherit)
13142 "Get the scheduled time as a time tuple, of a format suitable
13143 for calling org-schedule with, or if there is no scheduling,
13144 returns nil."
13145 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13146 (when time
13147 (apply 'encode-time (org-parse-time-string time)))))
13149 (defun org-get-deadline-time (pom &optional inherit)
13150 "Get the deadline as a time tuple, of a format suitable for
13151 calling org-deadline with, or if there is no scheduling, returns
13152 nil."
13153 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13154 (when time
13155 (apply 'encode-time (org-parse-time-string time)))))
13157 (defun org-remove-timestamp-with-keyword (keyword)
13158 "Remove all time stamps with KEYWORD in the current entry."
13159 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13160 beg)
13161 (save-excursion
13162 (org-back-to-heading t)
13163 (setq beg (point))
13164 (outline-next-heading)
13165 (while (re-search-backward re beg t)
13166 (replace-match "")
13167 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13168 (equal (char-before) ?\ ))
13169 (backward-delete-char 1)
13170 (if (string-match "^[ \t]*$" (buffer-substring
13171 (point-at-bol) (point-at-eol)))
13172 (delete-region (point-at-bol)
13173 (min (point-max) (1+ (point-at-eol))))))))))
13175 (defvar org-time-was-given) ; dynamically scoped parameter
13176 (defvar org-end-time-was-given) ; dynamically scoped parameter
13178 (defun org-add-planning-info (what &optional time &rest remove)
13179 "Insert new timestamp with keyword in the line directly after the headline.
13180 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13181 If non is given, the user is prompted for a date.
13182 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13183 be removed."
13184 (interactive)
13185 (let (org-time-was-given org-end-time-was-given ts
13186 end default-time default-input)
13188 (catch 'exit
13189 (when (and (memq what '(scheduled deadline))
13190 (or (not time)
13191 (and (stringp time)
13192 (string-match "^[-+]+[0-9]" time))))
13193 ;; Try to get a default date/time from existing timestamp
13194 (save-excursion
13195 (org-back-to-heading t)
13196 (setq end (save-excursion (outline-next-heading) (point)))
13197 (when (re-search-forward (if (eq what 'scheduled)
13198 org-scheduled-time-regexp
13199 org-deadline-time-regexp)
13200 end t)
13201 (setq ts (match-string 1)
13202 default-time
13203 (apply 'encode-time (org-parse-time-string ts))
13204 default-input (and ts (org-get-compact-tod ts))))))
13205 (when what
13206 (setq time
13207 (if (stringp time)
13208 ;; This is a string (relative or absolute), set proper date
13209 (apply 'encode-time
13210 (org-read-date-analyze
13211 time default-time (decode-time default-time)))
13212 ;; If necessary, get the time from the user
13213 (or time (org-read-date nil 'to-time nil nil
13214 default-time default-input)))))
13216 (when (and org-insert-labeled-timestamps-at-point
13217 (member what '(scheduled deadline)))
13218 (insert
13219 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13220 (org-insert-time-stamp time org-time-was-given
13221 nil nil nil (list org-end-time-was-given))
13222 (setq what nil))
13223 (save-excursion
13224 (save-restriction
13225 (let (col list elt ts buffer-invisibility-spec)
13226 (org-back-to-heading t)
13227 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13228 (goto-char (match-end 1))
13229 (setq col (current-column))
13230 (goto-char (match-end 0))
13231 (if (eobp) (insert "\n") (forward-char 1))
13232 (when (and (not what)
13233 (not (looking-at
13234 (concat "[ \t]*"
13235 org-keyword-time-not-clock-regexp))))
13236 ;; Nothing to add, nothing to remove...... :-)
13237 (throw 'exit nil))
13238 (if (and (not (looking-at org-outline-regexp))
13239 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13240 "[^\r\n]*"))
13241 (not (equal (match-string 1) org-clock-string)))
13242 (narrow-to-region (match-beginning 0) (match-end 0))
13243 (insert-before-markers "\n")
13244 (backward-char 1)
13245 (narrow-to-region (point) (point))
13246 (and org-adapt-indentation (org-indent-to-column col)))
13247 ;; Check if we have to remove something.
13248 (setq list (cons what remove))
13249 (while list
13250 (setq elt (pop list))
13251 (when (or (and (eq elt 'scheduled)
13252 (re-search-forward org-scheduled-time-regexp nil t))
13253 (and (eq elt 'deadline)
13254 (re-search-forward org-deadline-time-regexp nil t))
13255 (and (eq elt 'closed)
13256 (re-search-forward org-closed-time-regexp nil t)))
13257 (replace-match "")
13258 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13259 (and (looking-at "[ \t]+") (replace-match ""))
13260 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13261 (when what
13262 (insert
13263 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13264 (cond ((eq what 'scheduled) org-scheduled-string)
13265 ((eq what 'deadline) org-deadline-string)
13266 ((eq what 'closed) org-closed-string))
13267 " ")
13268 (setq ts (org-insert-time-stamp
13269 time
13270 (or org-time-was-given
13271 (and (eq what 'closed) org-log-done-with-time))
13272 (eq what 'closed)
13273 nil nil (list org-end-time-was-given)))
13274 (insert
13275 (if (not (or (bolp) (eq (char-before) ?\ )
13276 (memq (char-after) '(32 10))
13277 (eobp))) " " ""))
13278 (end-of-line 1))
13279 (goto-char (point-min))
13280 (widen)
13281 (if (and (looking-at "[ \t]*\n")
13282 (equal (char-before) ?\n))
13283 (delete-region (1- (point)) (point-at-eol)))
13284 ts))))))
13286 (defvar org-log-note-marker (make-marker))
13287 (defvar org-log-note-purpose nil)
13288 (defvar org-log-note-state nil)
13289 (defvar org-log-note-previous-state nil)
13290 (defvar org-log-note-how nil)
13291 (defvar org-log-note-extra nil)
13292 (defvar org-log-note-window-configuration nil)
13293 (defvar org-log-note-return-to (make-marker))
13294 (defvar org-log-note-effective-time nil
13295 "Remembered current time so that dynamically scoped
13296 `org-extend-today-until' affects tha timestamps in state change
13297 log")
13299 (defvar org-log-post-message nil
13300 "Message to be displayed after a log note has been stored.
13301 The auto-repeater uses this.")
13303 (defun org-add-note ()
13304 "Add a note to the current entry.
13305 This is done in the same way as adding a state change note."
13306 (interactive)
13307 (org-add-log-setup 'note nil nil 'findpos nil))
13309 (defvar org-property-end-re)
13310 (defun org-add-log-setup (&optional purpose state prev-state
13311 findpos how extra)
13312 "Set up the post command hook to take a note.
13313 If this is about to TODO state change, the new state is expected in STATE.
13314 When FINDPOS is non-nil, find the correct position for the note in
13315 the current entry. If not, assume that it can be inserted at point.
13316 HOW is an indicator what kind of note should be created.
13317 EXTRA is additional text that will be inserted into the notes buffer."
13318 (let* ((org-log-into-drawer (org-log-into-drawer))
13319 (drawer (cond ((stringp org-log-into-drawer)
13320 org-log-into-drawer)
13321 (org-log-into-drawer "LOGBOOK"))))
13322 (save-restriction
13323 (save-excursion
13324 (when findpos
13325 (org-back-to-heading t)
13326 (narrow-to-region (point) (save-excursion
13327 (outline-next-heading) (point)))
13328 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13329 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13330 "[^\r\n]*\\)?"))
13331 (goto-char (match-end 0))
13332 (cond
13333 (drawer
13334 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13335 nil t)
13336 (progn
13337 (goto-char (match-end 0))
13338 (or org-log-states-order-reversed
13339 (and (re-search-forward org-property-end-re nil t)
13340 (goto-char (1- (match-beginning 0))))))
13341 (insert "\n:" drawer ":\n:END:")
13342 (beginning-of-line 0)
13343 (org-indent-line)
13344 (beginning-of-line 2)
13345 (org-indent-line)
13346 (end-of-line 0)))
13347 ((and org-log-state-notes-insert-after-drawers
13348 (save-excursion
13349 (forward-line) (looking-at org-drawer-regexp)))
13350 (forward-line)
13351 (while (looking-at org-drawer-regexp)
13352 (goto-char (match-end 0))
13353 (re-search-forward org-property-end-re (point-max) t)
13354 (forward-line))
13355 (forward-line -1)))
13356 (unless org-log-states-order-reversed
13357 (and (= (char-after) ?\n) (forward-char 1))
13358 (org-skip-over-state-notes)
13359 (skip-chars-backward " \t\n\r")))
13360 (move-marker org-log-note-marker (point))
13361 (setq org-log-note-purpose purpose
13362 org-log-note-state state
13363 org-log-note-previous-state prev-state
13364 org-log-note-how how
13365 org-log-note-extra extra
13366 org-log-note-effective-time (org-current-effective-time))
13367 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13369 (defun org-skip-over-state-notes ()
13370 "Skip past the list of State notes in an entry."
13371 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13372 (when (ignore-errors (goto-char (org-in-item-p)))
13373 (let* ((struct (org-list-struct))
13374 (prevs (org-list-prevs-alist struct)))
13375 (while (looking-at "[ \t]*- State")
13376 (goto-char (or (org-list-get-next-item (point) struct prevs)
13377 (org-list-get-item-end (point) struct)))))))
13379 (defun org-add-log-note (&optional purpose)
13380 "Pop up a window for taking a note, and add this note later at point."
13381 (remove-hook 'post-command-hook 'org-add-log-note)
13382 (setq org-log-note-window-configuration (current-window-configuration))
13383 (delete-other-windows)
13384 (move-marker org-log-note-return-to (point))
13385 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13386 (goto-char org-log-note-marker)
13387 (org-switch-to-buffer-other-window "*Org Note*")
13388 (erase-buffer)
13389 (if (memq org-log-note-how '(time state))
13390 (let (current-prefix-arg) (org-store-log-note))
13391 (let ((org-inhibit-startup t)) (org-mode))
13392 (insert (format "# Insert note for %s.
13393 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13394 (cond
13395 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13396 ((eq org-log-note-purpose 'done) "closed todo item")
13397 ((eq org-log-note-purpose 'state)
13398 (format "state change from \"%s\" to \"%s\""
13399 (or org-log-note-previous-state "")
13400 (or org-log-note-state "")))
13401 ((eq org-log-note-purpose 'reschedule)
13402 "rescheduling")
13403 ((eq org-log-note-purpose 'delschedule)
13404 "no longer scheduled")
13405 ((eq org-log-note-purpose 'redeadline)
13406 "changing deadline")
13407 ((eq org-log-note-purpose 'deldeadline)
13408 "removing deadline")
13409 ((eq org-log-note-purpose 'refile)
13410 "refiling")
13411 ((eq org-log-note-purpose 'note)
13412 "this entry")
13413 (t (error "This should not happen")))))
13414 (if org-log-note-extra (insert org-log-note-extra))
13415 (org-set-local 'org-finish-function 'org-store-log-note)
13416 (run-hooks 'org-log-buffer-setup-hook)))
13418 (defvar org-note-abort nil) ; dynamically scoped
13419 (defun org-store-log-note ()
13420 "Finish taking a log note, and insert it to where it belongs."
13421 (let ((txt (buffer-string)))
13422 (kill-buffer (current-buffer))
13423 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13424 lines ind bul)
13425 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13426 (setq txt (replace-match "" t t txt)))
13427 (if (string-match "\\s-+\\'" txt)
13428 (setq txt (replace-match "" t t txt)))
13429 (setq lines (org-split-string txt "\n"))
13430 (when (and note (string-match "\\S-" note))
13431 (setq note
13432 (org-replace-escapes
13433 note
13434 (list (cons "%u" (user-login-name))
13435 (cons "%U" user-full-name)
13436 (cons "%t" (format-time-string
13437 (org-time-stamp-format 'long 'inactive)
13438 org-log-note-effective-time))
13439 (cons "%T" (format-time-string
13440 (org-time-stamp-format 'long nil)
13441 org-log-note-effective-time))
13442 (cons "%d" (format-time-string
13443 (org-time-stamp-format nil 'inactive)
13444 org-log-note-effective-time))
13445 (cons "%D" (format-time-string
13446 (org-time-stamp-format nil nil)
13447 org-log-note-effective-time))
13448 (cons "%s" (if org-log-note-state
13449 (concat "\"" org-log-note-state "\"")
13450 ""))
13451 (cons "%S" (if org-log-note-previous-state
13452 (concat "\"" org-log-note-previous-state "\"")
13453 "\"\"")))))
13454 (if lines (setq note (concat note " \\\\")))
13455 (push note lines))
13456 (when (or current-prefix-arg org-note-abort)
13457 (when org-log-into-drawer
13458 (org-remove-empty-drawer-at
13459 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13460 org-log-note-marker))
13461 (setq lines nil))
13462 (when lines
13463 (with-current-buffer (marker-buffer org-log-note-marker)
13464 (save-excursion
13465 (goto-char org-log-note-marker)
13466 (move-marker org-log-note-marker nil)
13467 (end-of-line 1)
13468 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13469 (setq ind (save-excursion
13470 (if (ignore-errors (goto-char (org-in-item-p)))
13471 (let ((struct (org-list-struct)))
13472 (org-list-get-ind
13473 (org-list-get-top-point struct) struct))
13474 (skip-chars-backward " \r\t\n")
13475 (cond
13476 ((and (org-at-heading-p)
13477 org-adapt-indentation)
13478 (1+ (org-current-level)))
13479 ((org-at-heading-p) 0)
13480 (t (org-get-indentation))))))
13481 (setq bul (org-list-bullet-string "-"))
13482 (org-indent-line-to ind)
13483 (insert bul (pop lines))
13484 (let ((ind-body (+ (length bul) ind)))
13485 (while lines
13486 (insert "\n")
13487 (org-indent-line-to ind-body)
13488 (insert (pop lines))))
13489 (message "Note stored")
13490 (org-back-to-heading t)
13491 (org-cycle-hide-drawers 'children))
13492 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13493 ;; from within `org-add-log-note' because `buffer-undo-list'
13494 ;; is then modified outside of `org-with-remote-undo'.
13495 (when (eq this-command 'org-agenda-todo)
13496 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13497 ;; Don't add undo information when called from `org-agenda-todo'
13498 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13499 (set-window-configuration org-log-note-window-configuration)
13500 (with-current-buffer (marker-buffer org-log-note-return-to)
13501 (goto-char org-log-note-return-to))
13502 (move-marker org-log-note-return-to nil)
13503 (and org-log-post-message (message "%s" org-log-post-message))))
13505 (defun org-remove-empty-drawer-at (drawer pos)
13506 "Remove an empty drawer DRAWER at position POS.
13507 POS may also be a marker."
13508 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13509 (save-excursion
13510 (save-restriction
13511 (widen)
13512 (goto-char pos)
13513 (if (org-in-regexp
13514 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13515 (replace-match ""))))))
13517 (defvar org-ts-type nil)
13518 (defun org-sparse-tree (&optional arg type)
13519 "Create a sparse tree, prompt for the details.
13520 This command can create sparse trees. You first need to select the type
13521 of match used to create the tree:
13523 t Show all TODO entries.
13524 T Show entries with a specific TODO keyword.
13525 m Show entries selected by a tags/property match.
13526 p Enter a property name and its value (both with completion on existing
13527 names/values) and show entries with that property.
13528 r Show entries matching a regular expression (`/' can be used as well).
13529 b Show deadlines and scheduled items before a date.
13530 a Show deadlines and scheduled items after a date.
13531 d Show deadlines due within `org-deadline-warning-days'.
13532 D Show deadlines and scheduled items between a date range."
13533 (interactive "P")
13534 (setq type (or type org-sparse-tree-default-date-type))
13535 (setq org-ts-type type)
13536 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13537 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13538 [c]ycle through date types: %s"
13539 (case type
13540 (all "all timestamps")
13541 (scheduled "only scheduled")
13542 (deadline "only deadline")
13543 (active "only active timestamps")
13544 (inactive "only inactive timestamps")
13545 (scheduled-or-deadline "scheduled/deadline")
13546 (closed "with a closed time-stamp")
13547 (otherwise "scheduled/deadline")))
13548 (let ((answer (read-char-exclusive)))
13549 (case answer
13551 (org-sparse-tree
13553 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13554 inactive closed)))))
13555 (?d (call-interactively #'org-check-deadlines))
13556 (?b (call-interactively #'org-check-before-date))
13557 (?a (call-interactively #'org-check-after-date))
13558 (?D (call-interactively #'org-check-dates-range))
13559 (?t (call-interactively #'org-show-todo-tree))
13560 (?T (org-show-todo-tree '(4)))
13561 (?m (call-interactively #'org-match-sparse-tree))
13562 ((?p ?P)
13563 (let* ((kwd (org-icompleting-read
13564 "Property: " (mapcar #'list (org-buffer-property-keys))))
13565 (value (org-icompleting-read
13566 "Value: " (mapcar #'list (org-property-values kwd)))))
13567 (unless (string-match "\\`{.*}\\'" value)
13568 (setq value (concat "\"" value "\"")))
13569 (org-match-sparse-tree arg (concat kwd "=" value))))
13570 ((?r ?R ?/) (call-interactively #'org-occur))
13571 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13573 (defvar org-occur-highlights nil
13574 "List of overlays used for occur matches.")
13575 (make-variable-buffer-local 'org-occur-highlights)
13576 (defvar org-occur-parameters nil
13577 "Parameters of the active org-occur calls.
13578 This is a list, each call to org-occur pushes as cons cell,
13579 containing the regular expression and the callback, onto the list.
13580 The list can contain several entries if `org-occur' has been called
13581 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13582 will only contain one set of parameters. When the highlights are
13583 removed (for example with `C-c C-c', or with the next edit (depending
13584 on `org-remove-highlights-with-change'), this variable is emptied
13585 as well.")
13586 (make-variable-buffer-local 'org-occur-parameters)
13588 (defun org-occur (regexp &optional keep-previous callback)
13589 "Make a compact tree which shows all matches of REGEXP.
13590 The tree will show the lines where the regexp matches, and all higher
13591 headlines above the match. It will also show the heading after the match,
13592 to make sure editing the matching entry is easy.
13593 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13594 call to `org-occur' will be kept, to allow stacking of calls to this
13595 command.
13596 If CALLBACK is non-nil, it is a function which is called to confirm
13597 that the match should indeed be shown."
13598 (interactive "sRegexp: \nP")
13599 (when (equal regexp "")
13600 (user-error "Regexp cannot be empty"))
13601 (unless keep-previous
13602 (org-remove-occur-highlights nil nil t))
13603 (push (cons regexp callback) org-occur-parameters)
13604 (let ((cnt 0))
13605 (save-excursion
13606 (goto-char (point-min))
13607 (if (or (not keep-previous) ; do not want to keep
13608 (not org-occur-highlights)) ; no previous matches
13609 ;; hide everything
13610 (org-overview))
13611 (while (re-search-forward regexp nil t)
13612 (when (or (not callback)
13613 (save-match-data (funcall callback)))
13614 (setq cnt (1+ cnt))
13615 (when org-highlight-sparse-tree-matches
13616 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13617 (org-show-context 'occur-tree))))
13618 (when org-remove-highlights-with-change
13619 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13620 nil 'local))
13621 (unless org-sparse-tree-open-archived-trees
13622 (org-hide-archived-subtrees (point-min) (point-max)))
13623 (run-hooks 'org-occur-hook)
13624 (if (org-called-interactively-p 'interactive)
13625 (message "%d match(es) for regexp %s" cnt regexp))
13626 cnt))
13628 (defun org-occur-next-match (&optional n reset)
13629 "Function for `next-error-function' to find sparse tree matches.
13630 N is the number of matches to move, when negative move backwards.
13631 RESET is entirely ignored - this function always goes back to the
13632 starting point when no match is found."
13633 (let* ((limit (if (< n 0) (point-min) (point-max)))
13634 (search-func (if (< n 0)
13635 'previous-single-char-property-change
13636 'next-single-char-property-change))
13637 (n (abs n))
13638 (pos (point))
13640 (catch 'exit
13641 (while (setq p1 (funcall search-func (point) 'org-type))
13642 (when (equal p1 limit)
13643 (goto-char pos)
13644 (error "No more matches"))
13645 (when (equal (get-char-property p1 'org-type) 'org-occur)
13646 (setq n (1- n))
13647 (when (= n 0)
13648 (goto-char p1)
13649 (throw 'exit (point))))
13650 (goto-char p1))
13651 (goto-char p1)
13652 (error "No more matches"))))
13654 (defun org-show-context (&optional key)
13655 "Make sure point and context are visible.
13656 How much context is shown depends upon the variables
13657 `org-show-hierarchy-above', `org-show-following-heading',
13658 `org-show-entry-below' and `org-show-siblings'."
13659 (let ((heading-p (org-at-heading-p t))
13660 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13661 (following-p (org-get-alist-option org-show-following-heading key))
13662 (entry-p (org-get-alist-option org-show-entry-below key))
13663 (siblings-p (org-get-alist-option org-show-siblings key)))
13664 ;; Show heading or entry text
13665 (if (and heading-p (not entry-p))
13666 (org-flag-heading nil) ; only show the heading
13667 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13668 (org-show-hidden-entry))) ; show entire entry
13669 (when following-p
13670 ;; Show next sibling, or heading below text
13671 (save-excursion
13672 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13673 (org-flag-heading nil))))
13674 (when siblings-p (org-show-siblings))
13675 (when hierarchy-p
13676 ;; show all higher headings, possibly with siblings
13677 (save-excursion
13678 (while (and (condition-case nil
13679 (progn (org-up-heading-all 1) t)
13680 (error nil))
13681 (not (bobp)))
13682 (org-flag-heading nil)
13683 (when siblings-p (org-show-siblings)))))))
13685 (defvar org-reveal-start-hook nil
13686 "Hook run before revealing a location.")
13688 (defun org-reveal (&optional siblings)
13689 "Show current entry, hierarchy above it, and the following headline.
13690 This can be used to show a consistent set of context around locations
13691 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13692 not t for the search context.
13694 With optional argument SIBLINGS, on each level of the hierarchy all
13695 siblings are shown. This repairs the tree structure to what it would
13696 look like when opened with hierarchical calls to `org-cycle'.
13697 With double optional argument \\[universal-argument] \\[universal-argument], \
13698 go to the parent and show the
13699 entire tree."
13700 (interactive "P")
13701 (run-hooks 'org-reveal-start-hook)
13702 (let ((org-show-hierarchy-above t)
13703 (org-show-following-heading t)
13704 (org-show-siblings (if siblings t org-show-siblings)))
13705 (org-show-context nil))
13706 (when (equal siblings '(16))
13707 (save-excursion
13708 (when (org-up-heading-safe)
13709 (org-show-subtree)
13710 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13712 (defun org-highlight-new-match (beg end)
13713 "Highlight from BEG to END and mark the highlight is an occur headline."
13714 (let ((ov (make-overlay beg end)))
13715 (overlay-put ov 'face 'secondary-selection)
13716 (overlay-put ov 'org-type 'org-occur)
13717 (push ov org-occur-highlights)))
13719 (defun org-remove-occur-highlights (&optional beg end noremove)
13720 "Remove the occur highlights from the buffer.
13721 BEG and END are ignored. If NOREMOVE is nil, remove this function
13722 from the `before-change-functions' in the current buffer."
13723 (interactive)
13724 (unless org-inhibit-highlight-removal
13725 (mapc 'delete-overlay org-occur-highlights)
13726 (setq org-occur-highlights nil)
13727 (setq org-occur-parameters nil)
13728 (unless noremove
13729 (remove-hook 'before-change-functions
13730 'org-remove-occur-highlights 'local))))
13732 ;;;; Priorities
13734 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13735 "Regular expression matching the priority indicator.")
13737 (defvar org-remove-priority-next-time nil)
13739 (defun org-priority-up ()
13740 "Increase the priority of the current item."
13741 (interactive)
13742 (org-priority 'up))
13744 (defun org-priority-down ()
13745 "Decrease the priority of the current item."
13746 (interactive)
13747 (org-priority 'down))
13749 (defun org-priority (&optional action show)
13750 "Change the priority of an item.
13751 ACTION can be `set', `up', `down', or a character."
13752 (interactive "P")
13753 (if (equal action '(4))
13754 (org-show-priority)
13755 (unless org-enable-priority-commands
13756 (user-error "Priority commands are disabled"))
13757 (setq action (or action 'set))
13758 (let (current new news have remove)
13759 (save-excursion
13760 (org-back-to-heading t)
13761 (if (looking-at org-priority-regexp)
13762 (setq current (string-to-char (match-string 2))
13763 have t))
13764 (cond
13765 ((eq action 'remove)
13766 (setq remove t new ?\ ))
13767 ((or (eq action 'set)
13768 (if (featurep 'xemacs) (characterp action) (integerp action)))
13769 (if (not (eq action 'set))
13770 (setq new action)
13771 (message "Priority %c-%c, SPC to remove: "
13772 org-highest-priority org-lowest-priority)
13773 (save-match-data
13774 (setq new (read-char-exclusive))))
13775 (if (and (= (upcase org-highest-priority) org-highest-priority)
13776 (= (upcase org-lowest-priority) org-lowest-priority))
13777 (setq new (upcase new)))
13778 (cond ((equal new ?\ ) (setq remove t))
13779 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13780 (user-error "Priority must be between `%c' and `%c'"
13781 org-highest-priority org-lowest-priority))))
13782 ((eq action 'up)
13783 (setq new (if have
13784 (1- current) ; normal cycling
13785 ;; last priority was empty
13786 (if (eq last-command this-command)
13787 org-lowest-priority ; wrap around empty to lowest
13788 ;; default
13789 (if org-priority-start-cycle-with-default
13790 org-default-priority
13791 (1- org-default-priority))))))
13792 ((eq action 'down)
13793 (setq new (if have
13794 (1+ current) ; normal cycling
13795 ;; last priority was empty
13796 (if (eq last-command this-command)
13797 org-highest-priority ; wrap around empty to highest
13798 ;; default
13799 (if org-priority-start-cycle-with-default
13800 org-default-priority
13801 (1+ org-default-priority))))))
13802 (t (user-error "Invalid action")))
13803 (if (or (< (upcase new) org-highest-priority)
13804 (> (upcase new) org-lowest-priority))
13805 (if (and (memq action '(up down))
13806 (not have) (not (eq last-command this-command)))
13807 ;; `new' is from default priority
13808 (error
13809 "The default can not be set, see `org-default-priority' why")
13810 ;; normal cycling: `new' is beyond highest/lowest priority
13811 ;; and is wrapped around to the empty priority
13812 (setq remove t)))
13813 (setq news (format "%c" new))
13814 (if have
13815 (if remove
13816 (replace-match "" t t nil 1)
13817 (replace-match news t t nil 2))
13818 (if remove
13819 (user-error "No priority cookie found in line")
13820 (let ((case-fold-search nil))
13821 (looking-at org-todo-line-regexp))
13822 (if (match-end 2)
13823 (progn
13824 (goto-char (match-end 2))
13825 (insert " [#" news "]"))
13826 (goto-char (match-beginning 3))
13827 (insert "[#" news "] "))))
13828 (org-preserve-lc (org-set-tags nil 'align)))
13829 (if remove
13830 (message "Priority removed")
13831 (message "Priority of current item set to %s" news)))))
13833 (defun org-show-priority ()
13834 "Show the priority of the current item.
13835 This priority is composed of the main priority given with the [#A] cookies,
13836 and by additional input from the age of a schedules or deadline entry."
13837 (interactive)
13838 (let ((pri (if (eq major-mode 'org-agenda-mode)
13839 (org-get-at-bol 'priority)
13840 (save-excursion
13841 (save-match-data
13842 (beginning-of-line)
13843 (and (looking-at org-heading-regexp)
13844 (org-get-priority (match-string 0))))))))
13845 (message "Priority is %d" (if pri pri -1000))))
13847 (defun org-get-priority (s)
13848 "Find priority cookie and return priority."
13849 (save-match-data
13850 (if (functionp org-get-priority-function)
13851 (funcall org-get-priority-function)
13852 (if (not (string-match org-priority-regexp s))
13853 (* 1000 (- org-lowest-priority org-default-priority))
13854 (* 1000 (- org-lowest-priority
13855 (string-to-char (match-string 2 s))))))))
13857 ;;;; Tags
13859 (defvar org-agenda-archives-mode)
13860 (defvar org-map-continue-from nil
13861 "Position from where mapping should continue.
13862 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13864 (defvar org-scanner-tags nil
13865 "The current tag list while the tags scanner is running.")
13866 (defvar org-trust-scanner-tags nil
13867 "Should `org-get-tags-at' use the tags for the scanner.
13868 This is for internal dynamical scoping only.
13869 When this is non-nil, the function `org-get-tags-at' will return the value
13870 of `org-scanner-tags' instead of building the list by itself. This
13871 can lead to large speed-ups when the tags scanner is used in a file with
13872 many entries, and when the list of tags is retrieved, for example to
13873 obtain a list of properties. Building the tags list for each entry in such
13874 a file becomes an N^2 operation - but with this variable set, it scales
13875 as N.")
13877 (defun org-scan-tags (action matcher todo-only &optional start-level)
13878 "Scan headline tags with inheritance and produce output ACTION.
13880 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13881 or `agenda' to produce an entry list for an agenda view. It can also be
13882 a Lisp form or a function that should be called at each matched headline, in
13883 this case the return value is a list of all return values from these calls.
13885 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13886 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13887 only lines with a not-done TODO keyword are included in the output.
13888 This should be the same variable that was scoped into
13889 and set by `org-make-tags-matcher' when it constructed MATCHER.
13891 START-LEVEL can be a string with asterisks, reducing the scope to
13892 headlines matching this string."
13893 (require 'org-agenda)
13894 (let* ((re (concat "^"
13895 (if start-level
13896 ;; Get the correct level to match
13897 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13898 org-outline-regexp)
13899 " *\\(\\<\\("
13900 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13901 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13902 (props (list 'face 'default
13903 'done-face 'org-agenda-done
13904 'undone-face 'default
13905 'mouse-face 'highlight
13906 'org-not-done-regexp org-not-done-regexp
13907 'org-todo-regexp org-todo-regexp
13908 'org-complex-heading-regexp org-complex-heading-regexp
13909 'help-echo
13910 (format "mouse-2 or RET jump to org file %s"
13911 (abbreviate-file-name
13912 (or (buffer-file-name (buffer-base-buffer))
13913 (buffer-name (buffer-base-buffer)))))))
13914 (org-map-continue-from nil)
13915 lspos tags tags-list
13916 (tags-alist (list (cons 0 org-file-tags)))
13917 (llast 0) rtn rtn1 level category i txt
13918 todo marker entry priority)
13919 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13920 (setq action (list 'lambda nil action)))
13921 (save-excursion
13922 (goto-char (point-min))
13923 (when (eq action 'sparse-tree)
13924 (org-overview)
13925 (org-remove-occur-highlights))
13926 (while (let (case-fold-search)
13927 (re-search-forward re nil t))
13928 (setq org-map-continue-from nil)
13929 (catch :skip
13930 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13931 tags (if (match-end 4) (org-match-string-no-properties 4)))
13932 (goto-char (setq lspos (match-beginning 0)))
13933 (setq level (org-reduced-level (org-outline-level))
13934 category (org-get-category))
13935 (setq i llast llast level)
13936 ;; remove tag lists from same and sublevels
13937 (while (>= i level)
13938 (when (setq entry (assoc i tags-alist))
13939 (setq tags-alist (delete entry tags-alist)))
13940 (setq i (1- i)))
13941 ;; add the next tags
13942 (when tags
13943 (setq tags (org-split-string tags ":")
13944 tags-alist
13945 (cons (cons level tags) tags-alist)))
13946 ;; compile tags for current headline
13947 (setq tags-list
13948 (if org-use-tag-inheritance
13949 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13950 tags)
13951 org-scanner-tags tags-list)
13952 (when org-use-tag-inheritance
13953 (setcdr (car tags-alist)
13954 (mapcar (lambda (x)
13955 (setq x (copy-sequence x))
13956 (org-add-prop-inherited x))
13957 (cdar tags-alist))))
13958 (when (and tags org-use-tag-inheritance
13959 (or (not (eq t org-use-tag-inheritance))
13960 org-tags-exclude-from-inheritance))
13961 ;; selective inheritance, remove uninherited ones
13962 (setcdr (car tags-alist)
13963 (org-remove-uninherited-tags (cdar tags-alist))))
13964 (when (and
13966 ;; eval matcher only when the todo condition is OK
13967 (and (or (not todo-only) (member todo org-not-done-keywords))
13968 (let ((case-fold-search t) (org-trust-scanner-tags t))
13969 (eval matcher)))
13971 ;; Call the skipper, but return t if it does not skip,
13972 ;; so that the `and' form continues evaluating
13973 (progn
13974 (unless (eq action 'sparse-tree) (org-agenda-skip))
13977 ;; Check if timestamps are deselecting this entry
13978 (or (not todo-only)
13979 (and (member todo org-not-done-keywords)
13980 (or (not org-agenda-tags-todo-honor-ignore-options)
13981 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13983 ;; select this headline
13984 (cond
13985 ((eq action 'sparse-tree)
13986 (and org-highlight-sparse-tree-matches
13987 (org-get-heading) (match-end 0)
13988 (org-highlight-new-match
13989 (match-beginning 1) (match-end 1)))
13990 (org-show-context 'tags-tree))
13991 ((eq action 'agenda)
13992 (setq txt (org-agenda-format-item
13994 (concat
13995 (if (eq org-tags-match-list-sublevels 'indented)
13996 (make-string (1- level) ?.) "")
13997 (org-get-heading))
13998 level category
13999 tags-list)
14000 priority (org-get-priority txt))
14001 (goto-char lspos)
14002 (setq marker (org-agenda-new-marker))
14003 (org-add-props txt props
14004 'org-marker marker 'org-hd-marker marker 'org-category category
14005 'todo-state todo
14006 'priority priority 'type "tagsmatch")
14007 (push txt rtn))
14008 ((functionp action)
14009 (setq org-map-continue-from nil)
14010 (save-excursion
14011 (setq rtn1 (funcall action))
14012 (push rtn1 rtn)))
14013 (t (user-error "Invalid action")))
14015 ;; if we are to skip sublevels, jump to end of subtree
14016 (unless org-tags-match-list-sublevels
14017 (org-end-of-subtree t)
14018 (backward-char 1))))
14019 ;; Get the correct position from where to continue
14020 (if org-map-continue-from
14021 (goto-char org-map-continue-from)
14022 (and (= (point) lspos) (end-of-line 1)))))
14023 (when (and (eq action 'sparse-tree)
14024 (not org-sparse-tree-open-archived-trees))
14025 (org-hide-archived-subtrees (point-min) (point-max)))
14026 (nreverse rtn)))
14028 (defun org-remove-uninherited-tags (tags)
14029 "Remove all tags that are not inherited from the list TAGS."
14030 (cond
14031 ((eq org-use-tag-inheritance t)
14032 (if org-tags-exclude-from-inheritance
14033 (org-delete-all org-tags-exclude-from-inheritance tags)
14034 tags))
14035 ((not org-use-tag-inheritance) nil)
14036 ((stringp org-use-tag-inheritance)
14037 (delq nil (mapcar
14038 (lambda (x)
14039 (if (and (string-match org-use-tag-inheritance x)
14040 (not (member x org-tags-exclude-from-inheritance)))
14041 x nil))
14042 tags)))
14043 ((listp org-use-tag-inheritance)
14044 (delq nil (mapcar
14045 (lambda (x)
14046 (if (member x org-use-tag-inheritance) x nil))
14047 tags)))))
14049 (defun org-match-sparse-tree (&optional todo-only match)
14050 "Create a sparse tree according to tags string MATCH.
14051 MATCH can contain positive and negative selection of tags, like
14052 \"+WORK+URGENT-WITHBOSS\".
14053 If optional argument TODO-ONLY is non-nil, only select lines that are
14054 also TODO lines."
14055 (interactive "P")
14056 (org-agenda-prepare-buffers (list (current-buffer)))
14057 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14059 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14061 (defvar org-cached-props nil)
14062 (defun org-cached-entry-get (pom property)
14063 (if (or (eq t org-use-property-inheritance)
14064 (and (stringp org-use-property-inheritance)
14065 (string-match org-use-property-inheritance property))
14066 (and (listp org-use-property-inheritance)
14067 (member property org-use-property-inheritance)))
14068 ;; Caching is not possible, check it directly
14069 (org-entry-get pom property 'inherit)
14070 ;; Get all properties, so that we can do complicated checks easily
14071 (cdr (assoc property (or org-cached-props
14072 (setq org-cached-props
14073 (org-entry-properties pom)))))))
14075 (defun org-global-tags-completion-table (&optional files)
14076 "Return the list of all tags in all agenda buffer/files.
14077 Optional FILES argument is a list of files which can be used
14078 instead of the agenda files."
14079 (save-excursion
14080 (org-uniquify
14081 (delq nil
14082 (apply 'append
14083 (mapcar
14084 (lambda (file)
14085 (set-buffer (find-file-noselect file))
14086 (append (org-get-buffer-tags)
14087 (mapcar (lambda (x) (if (stringp (car-safe x))
14088 (list (car-safe x)) nil))
14089 org-tag-alist)))
14090 (if (and files (car files))
14091 files
14092 (org-agenda-files))))))))
14094 (defun org-make-tags-matcher (match)
14095 "Create the TAGS/TODO matcher form for the selection string MATCH.
14097 The variable `todo-only' is scoped dynamically into this function.
14098 It will be set to t if the matcher restricts matching to TODO entries,
14099 otherwise will not be touched.
14101 Returns a cons of the selection string MATCH and the constructed
14102 lisp form implementing the matcher. The matcher is to be evaluated
14103 at an Org entry, with point on the headline, and returns t if the
14104 entry matches the selection string MATCH. The returned lisp form
14105 references two variables with information about the entry, which
14106 must be bound around the form's evaluation: todo, the TODO keyword
14107 at the entry (or nil of none); and tags-list, the list of all tags
14108 at the entry including inherited ones. Additionally, the category
14109 of the entry (if any) must be specified as the text property
14110 'org-category on the headline.
14112 See also `org-scan-tags'.
14114 (declare (special todo-only))
14115 (unless (boundp 'todo-only)
14116 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14117 (unless match
14118 ;; Get a new match request, with completion against the global
14119 ;; tags table and the local tags in current buffer
14120 (let ((org-last-tags-completion-table
14121 (org-uniquify
14122 (delq nil (append (org-get-buffer-tags)
14123 (org-global-tags-completion-table))))))
14124 (setq match (org-completing-read-no-i
14125 "Match: " 'org-tags-completion-function nil nil nil
14126 'org-tags-history))))
14128 ;; Parse the string and create a lisp form
14129 (let ((match0 match)
14130 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14131 minus tag mm
14132 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14133 orterms orlist re-p str-p level-p level-op time-p
14134 prop-p pn pv po gv rest (start 0) (ss 0))
14135 ;; Expand group tags
14136 (setq match (org-tags-expand match))
14138 ;; Check if there is a TODO part of this match, which would be the
14139 ;; part after a "/". TO make sure that this slash is not part of
14140 ;; a property value to be matched against, we also check that there
14141 ;; is no " after that slash.
14142 ;; First, find the last slash
14143 (while (string-match "/+" match ss)
14144 (setq start (match-beginning 0) ss (match-end 0)))
14145 (if (and (string-match "/+" match start)
14146 (not (save-match-data (string-match "\"" match start))))
14147 ;; match contains also a todo-matching request
14148 (progn
14149 (setq tagsmatch (substring match 0 (match-beginning 0))
14150 todomatch (substring match (match-end 0)))
14151 (if (string-match "^!" todomatch)
14152 (setq todo-only t todomatch (substring todomatch 1)))
14153 (if (string-match "^\\s-*$" todomatch)
14154 (setq todomatch nil)))
14155 ;; only matching tags
14156 (setq tagsmatch match todomatch nil))
14158 ;; Make the tags matcher
14159 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14160 (setq tagsmatcher t)
14161 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14162 (dolist (term orterms)
14163 (while (and (equal (substring term -1) "\\") orterms)
14164 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14165 (while (string-match re term)
14166 (setq rest (substring term (match-end 0))
14167 minus (and (match-end 1)
14168 (equal (match-string 1 term) "-"))
14169 tag (save-match-data (replace-regexp-in-string
14170 "\\\\-" "-"
14171 (match-string 2 term)))
14172 re-p (equal (string-to-char tag) ?{)
14173 level-p (match-end 4)
14174 prop-p (match-end 5)
14175 mm (cond
14176 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14177 (level-p
14178 (setq level-op (org-op-to-function (match-string 3 term)))
14179 `(,level-op level ,(string-to-number
14180 (match-string 4 term))))
14181 (prop-p
14182 (setq pn (match-string 5 term)
14183 po (match-string 6 term)
14184 pv (match-string 7 term)
14185 re-p (equal (string-to-char pv) ?{)
14186 str-p (equal (string-to-char pv) ?\")
14187 time-p (save-match-data
14188 (string-match "^\"[[<].*[]>]\"$" pv))
14189 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14190 (if time-p (setq pv (org-matcher-time pv)))
14191 (setq po (org-op-to-function po (if time-p 'time str-p)))
14192 (cond
14193 ((equal pn "CATEGORY")
14194 (setq gv '(get-text-property (point) 'org-category)))
14195 ((equal pn "TODO")
14196 (setq gv 'todo))
14198 (setq gv `(org-cached-entry-get nil ,pn))))
14199 (if re-p
14200 (if (eq po 'org<>)
14201 `(not (string-match ,pv (or ,gv "")))
14202 `(string-match ,pv (or ,gv "")))
14203 (if str-p
14204 `(,po (or ,gv "") ,pv)
14205 `(,po (string-to-number (or ,gv ""))
14206 ,(string-to-number pv) ))))
14207 (t `(member ,tag tags-list)))
14208 mm (if minus (list 'not mm) mm)
14209 term rest)
14210 (push mm tagsmatcher))
14211 (push (if (> (length tagsmatcher) 1)
14212 (cons 'and tagsmatcher)
14213 (car tagsmatcher))
14214 orlist)
14215 (setq tagsmatcher nil))
14216 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14217 (setq tagsmatcher
14218 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14219 ;; Make the todo matcher
14220 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14221 (setq todomatcher t)
14222 (setq orterms (org-split-string todomatch "|") orlist nil)
14223 (dolist (term orterms)
14224 (while (string-match re term)
14225 (setq minus (and (match-end 1)
14226 (equal (match-string 1 term) "-"))
14227 kwd (match-string 2 term)
14228 re-p (equal (string-to-char kwd) ?{)
14229 term (substring term (match-end 0))
14230 mm (if re-p
14231 `(string-match ,(substring kwd 1 -1) todo)
14232 (list 'equal 'todo kwd))
14233 mm (if minus (list 'not mm) mm))
14234 (push mm todomatcher))
14235 (push (if (> (length todomatcher) 1)
14236 (cons 'and todomatcher)
14237 (car todomatcher))
14238 orlist)
14239 (setq todomatcher nil))
14240 (setq todomatcher (if (> (length orlist) 1)
14241 (cons 'or orlist) (car orlist))))
14243 ;; Return the string and lisp forms of the matcher
14244 (setq matcher (if todomatcher
14245 (list 'and tagsmatcher todomatcher)
14246 tagsmatcher))
14247 (when todo-only
14248 (setq matcher (list 'and '(member todo org-not-done-keywords)
14249 matcher)))
14250 (cons match0 matcher)))
14252 (defun org-tags-expand (match &optional single-as-list downcased)
14253 "Expand group tags in MATCH.
14255 This replaces every group tag in MATCH with a regexp tag search.
14256 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14257 will be replaced like this:
14259 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14260 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14261 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14263 Replacing by a regexp preserves the structure of the match.
14264 E.g., this expansion
14266 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14268 will match anything tagged with \"Lab\" and \"Home\", or tagged
14269 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14271 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14272 assumed to be a single group tag, and the function will return
14273 the list of tags in this group.
14275 When DOWNCASE is non-nil, expand downcased TAGS."
14276 (if org-group-tags
14277 (let* ((case-fold-search t)
14278 (stable org-mode-syntax-table)
14279 (tal (or org-tag-groups-alist-for-agenda
14280 org-tag-groups-alist))
14281 (tal (if downcased
14282 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14283 (tml (mapcar 'car tal))
14284 (rtnmatch match) rpl)
14285 ;; @ and _ are allowed as word-components in tags
14286 (modify-syntax-entry ?@ "w" stable)
14287 (modify-syntax-entry ?_ "w" stable)
14288 (while (and tml
14289 (with-syntax-table stable
14290 (string-match
14291 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14292 (regexp-opt tml) "\\>\\)")
14293 rtnmatch)))
14294 (let* ((dir (match-string 1 rtnmatch))
14295 (tag (match-string 2 rtnmatch))
14296 (tag (if downcased (downcase tag) tag)))
14297 (setq tml (delete tag tml))
14298 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14299 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14300 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14301 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14302 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14303 (if single-as-list
14304 (or (reverse rpl) (list rtnmatch))
14305 rtnmatch))
14306 (if single-as-list (list (if downcased (downcase match) match))
14307 match)))
14309 (defun org-op-to-function (op &optional stringp)
14310 "Turn an operator into the appropriate function."
14311 (setq op
14312 (cond
14313 ((equal op "<" ) '(< string< org-time<))
14314 ((equal op ">" ) '(> org-string> org-time>))
14315 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14316 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14317 ((member op '("=" "==")) '(= string= org-time=))
14318 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14319 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14321 (defun org<> (a b) (not (= a b)))
14322 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14323 (defun org-string>= (a b) (not (string< a b)))
14324 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14325 (defun org-string<> (a b) (not (string= a b)))
14326 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14327 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14328 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14329 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14330 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14331 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14332 (defun org-2ft (s)
14333 "Convert S to a floating point time.
14334 If S is already a number, just return it. If it is a string, parse
14335 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14336 (cond
14337 ((numberp s) s)
14338 ((stringp s)
14339 (condition-case nil
14340 (float-time (apply 'encode-time (org-parse-time-string s)))
14341 (error 0.)))
14342 (t 0.)))
14344 (defun org-time-today ()
14345 "Time in seconds today at 0:00.
14346 Returns the float number of seconds since the beginning of the
14347 epoch to the beginning of today (00:00)."
14348 (float-time (apply 'encode-time
14349 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14351 (defun org-matcher-time (s)
14352 "Interpret a time comparison value."
14353 (save-match-data
14354 (cond
14355 ((string= s "<now>") (float-time))
14356 ((string= s "<today>") (org-time-today))
14357 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14358 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14359 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14360 (+ (org-time-today)
14361 (* (string-to-number (match-string 1 s))
14362 (cdr (assoc (match-string 2 s)
14363 '(("d" . 86400.0) ("w" . 604800.0)
14364 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14365 (t (org-2ft s)))))
14367 (defun org-match-any-p (re list)
14368 "Does re match any element of list?"
14369 (setq list (mapcar (lambda (x) (string-match re x)) list))
14370 (delq nil list))
14372 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14373 (defvar org-tags-overlay (make-overlay 1 1))
14374 (org-detach-overlay org-tags-overlay)
14376 (defun org-get-local-tags-at (&optional pos)
14377 "Get a list of tags defined in the current headline."
14378 (org-get-tags-at pos 'local))
14380 (defun org-get-local-tags ()
14381 "Get a list of tags defined in the current headline."
14382 (org-get-tags-at nil 'local))
14384 (defun org-get-tags-at (&optional pos local)
14385 "Get a list of all headline tags applicable at POS.
14386 POS defaults to point. If tags are inherited, the list contains
14387 the targets in the same sequence as the headlines appear, i.e.
14388 the tags of the current headline come last.
14389 When LOCAL is non-nil, only return tags from the current headline,
14390 ignore inherited ones."
14391 (interactive)
14392 (if (and org-trust-scanner-tags
14393 (or (not pos) (equal pos (point)))
14394 (not local))
14395 org-scanner-tags
14396 (let (tags ltags lastpos parent)
14397 (save-excursion
14398 (save-restriction
14399 (widen)
14400 (goto-char (or pos (point)))
14401 (save-match-data
14402 (catch 'done
14403 (condition-case nil
14404 (progn
14405 (org-back-to-heading t)
14406 (while (not (equal lastpos (point)))
14407 (setq lastpos (point))
14408 (when (looking-at
14409 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14410 (setq ltags (org-split-string
14411 (org-match-string-no-properties 1) ":"))
14412 (when parent
14413 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14414 (setq tags (append
14415 (if parent
14416 (org-remove-uninherited-tags ltags)
14417 ltags)
14418 tags)))
14419 (or org-use-tag-inheritance (throw 'done t))
14420 (if local (throw 'done t))
14421 (or (org-up-heading-safe) (error nil))
14422 (setq parent t)))
14423 (error nil)))))
14424 (if local
14425 tags
14426 (reverse (delete-dups
14427 (reverse (append
14428 (org-remove-uninherited-tags
14429 org-file-tags)
14430 tags)))))))))
14432 (defun org-add-prop-inherited (s)
14433 (add-text-properties 0 (length s) '(inherited t) s)
14436 (defun org-toggle-tag (tag &optional onoff)
14437 "Toggle the tag TAG for the current line.
14438 If ONOFF is `on' or `off', don't toggle but set to this state."
14439 (let (res current)
14440 (save-excursion
14441 (org-back-to-heading t)
14442 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14443 (point-at-eol) t)
14444 (progn
14445 (setq current (match-string 1))
14446 (replace-match ""))
14447 (setq current ""))
14448 (setq current (nreverse (org-split-string current ":")))
14449 (cond
14450 ((eq onoff 'on)
14451 (setq res t)
14452 (or (member tag current) (push tag current)))
14453 ((eq onoff 'off)
14454 (or (not (member tag current)) (setq current (delete tag current))))
14455 (t (if (member tag current)
14456 (setq current (delete tag current))
14457 (setq res t)
14458 (push tag current))))
14459 (end-of-line 1)
14460 (if current
14461 (progn
14462 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14463 (org-set-tags nil t))
14464 (delete-horizontal-space))
14465 (run-hooks 'org-after-tags-change-hook))
14466 res))
14468 (defun org-align-tags-here (to-col)
14469 ;; Assumes that this is a headline
14470 "Align tags on the current headline to TO-COL."
14471 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14472 (beginning-of-line 1)
14473 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14474 (< pos (match-beginning 2)))
14475 (progn
14476 (setq tags-l (- (match-end 2) (match-beginning 2)))
14477 (goto-char (match-beginning 1))
14478 (insert " ")
14479 (delete-region (point) (1+ (match-beginning 2)))
14480 (setq ncol (max (current-column)
14481 (1+ col)
14482 (if (> to-col 0)
14483 to-col
14484 (- (abs to-col) tags-l))))
14485 (setq p (point))
14486 (insert (make-string (- ncol (current-column)) ?\ ))
14487 (setq ncol (current-column))
14488 (when indent-tabs-mode (tabify p (point-at-eol)))
14489 (org-move-to-column (min ncol col)))
14490 (goto-char pos))))
14492 (defun org-set-tags-command (&optional arg just-align)
14493 "Call the set-tags command for the current entry."
14494 (interactive "P")
14495 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14496 (org-set-tags arg just-align)
14497 (save-excursion
14498 (unless (and (org-region-active-p)
14499 org-loop-over-headlines-in-active-region)
14500 (org-back-to-heading t))
14501 (org-set-tags arg just-align))))
14503 (defun org-set-tags-to (data)
14504 "Set the tags of the current entry to DATA, replacing the current tags.
14505 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14506 If DATA is nil or the empty string, any tags will be removed."
14507 (interactive "sTags: ")
14508 (setq data
14509 (cond
14510 ((eq data nil) "")
14511 ((equal data "") "")
14512 ((stringp data)
14513 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14514 ":"))
14515 ((listp data)
14516 (concat ":" (mapconcat 'identity data ":") ":"))))
14517 (when data
14518 (save-excursion
14519 (org-back-to-heading t)
14520 (when (looking-at org-complex-heading-regexp)
14521 (if (match-end 5)
14522 (progn
14523 (goto-char (match-beginning 5))
14524 (insert data)
14525 (delete-region (point) (point-at-eol))
14526 (org-set-tags nil 'align))
14527 (goto-char (point-at-eol))
14528 (insert " " data)
14529 (org-set-tags nil 'align)))
14530 (beginning-of-line 1)
14531 (if (looking-at ".*?\\([ \t]+\\)$")
14532 (delete-region (match-beginning 1) (match-end 1))))))
14534 (defun org-align-all-tags ()
14535 "Align the tags i all headings."
14536 (interactive)
14537 (save-excursion
14538 (or (ignore-errors (org-back-to-heading t))
14539 (outline-next-heading))
14540 (if (org-at-heading-p)
14541 (org-set-tags t)
14542 (message "No headings"))))
14544 (defvar org-indent-indentation-per-level)
14545 (defun org-set-tags (&optional arg just-align)
14546 "Set the tags for the current headline.
14547 With prefix ARG, realign all tags in headings in the current buffer.
14548 When JUST-ALIGN is non-nil, only align tags."
14549 (interactive "P")
14550 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14551 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14552 'region-start-level 'region))
14553 org-loop-over-headlines-in-active-region)
14554 (org-map-entries
14555 ;; We don't use ARG and JUST-ALIGN here because these args
14556 ;; are not useful when looping over headlines.
14557 `(org-set-tags)
14558 org-loop-over-headlines-in-active-region
14559 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14560 (let* ((re org-outline-regexp-bol)
14561 (current (unless arg (org-get-tags-string)))
14562 (col (current-column))
14563 (org-setting-tags t)
14564 table current-tags inherited-tags ; computed below when needed
14565 tags p0 c0 c1 rpl di tc level)
14566 (if arg
14567 (save-excursion
14568 (goto-char (point-min))
14569 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14570 (while (re-search-forward re nil t)
14571 (org-set-tags nil t)
14572 (end-of-line 1)))
14573 (message "All tags realigned to column %d" org-tags-column))
14574 (if just-align
14575 (setq tags current)
14576 ;; Get a new set of tags from the user
14577 (save-excursion
14578 (setq table (append org-tag-persistent-alist
14579 (or org-tag-alist (org-get-buffer-tags))
14580 (and
14581 org-complete-tags-always-offer-all-agenda-tags
14582 (org-global-tags-completion-table
14583 (org-agenda-files))))
14584 org-last-tags-completion-table table
14585 current-tags (org-split-string current ":")
14586 inherited-tags (nreverse
14587 (nthcdr (length current-tags)
14588 (nreverse (org-get-tags-at))))
14589 tags
14590 (if (or (eq t org-use-fast-tag-selection)
14591 (and org-use-fast-tag-selection
14592 (delq nil (mapcar 'cdr table))))
14593 (org-fast-tag-selection
14594 current-tags inherited-tags table
14595 (if org-fast-tag-selection-include-todo
14596 org-todo-key-alist))
14597 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14598 (org-trim
14599 (org-icompleting-read "Tags: "
14600 'org-tags-completion-function
14601 nil nil current 'org-tags-history))))))
14602 (while (string-match "[-+&]+" tags)
14603 ;; No boolean logic, just a list
14604 (setq tags (replace-match ":" t t tags))))
14606 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14608 (if org-tags-sort-function
14609 (setq tags (mapconcat 'identity
14610 (sort (org-split-string
14611 tags (org-re "[^[:alnum:]_@#%]+"))
14612 org-tags-sort-function) ":")))
14614 (if (string-match "\\`[\t ]*\\'" tags)
14615 (setq tags "")
14616 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14617 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14619 ;; Insert new tags at the correct column
14620 (beginning-of-line 1)
14621 (setq level (or (and (looking-at org-outline-regexp)
14622 (- (match-end 0) (point) 1))
14624 (cond
14625 ((and (equal current "") (equal tags "")))
14626 ((re-search-forward
14627 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14628 (point-at-eol) t)
14629 (if (equal tags "")
14630 (setq rpl "")
14631 (goto-char (match-beginning 0))
14632 (setq c0 (current-column)
14633 ;; compute offset for the case of org-indent-mode active
14634 di (if (org-bound-and-true-p org-indent-mode)
14635 (* (1- org-indent-indentation-per-level) (1- level))
14637 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14638 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14639 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14640 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14641 (replace-match rpl t t)
14642 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14643 tags)
14644 (t (error "Tags alignment failed")))
14645 (org-move-to-column col)
14646 (unless just-align
14647 (run-hooks 'org-after-tags-change-hook))))))
14649 (defun org-change-tag-in-region (beg end tag off)
14650 "Add or remove TAG for each entry in the region.
14651 This works in the agenda, and also in an org-mode buffer."
14652 (interactive
14653 (list (region-beginning) (region-end)
14654 (let ((org-last-tags-completion-table
14655 (if (derived-mode-p 'org-mode)
14656 (org-uniquify
14657 (delq nil (append (org-get-buffer-tags)
14658 (org-global-tags-completion-table))))
14659 (org-global-tags-completion-table))))
14660 (org-icompleting-read
14661 "Tag: " 'org-tags-completion-function nil nil nil
14662 'org-tags-history))
14663 (progn
14664 (message "[s]et or [r]emove? ")
14665 (equal (read-char-exclusive) ?r))))
14666 (if (fboundp 'deactivate-mark) (deactivate-mark))
14667 (let ((agendap (equal major-mode 'org-agenda-mode))
14668 l1 l2 m buf pos newhead (cnt 0))
14669 (goto-char end)
14670 (setq l2 (1- (org-current-line)))
14671 (goto-char beg)
14672 (setq l1 (org-current-line))
14673 (loop for l from l1 to l2 do
14674 (org-goto-line l)
14675 (setq m (get-text-property (point) 'org-hd-marker))
14676 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14677 (and agendap m))
14678 (setq buf (if agendap (marker-buffer m) (current-buffer))
14679 pos (if agendap m (point)))
14680 (with-current-buffer buf
14681 (save-excursion
14682 (save-restriction
14683 (goto-char pos)
14684 (setq cnt (1+ cnt))
14685 (org-toggle-tag tag (if off 'off 'on))
14686 (setq newhead (org-get-heading)))))
14687 (and agendap (org-agenda-change-all-lines newhead m))))
14688 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14690 (defun org-tags-completion-function (string predicate &optional flag)
14691 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14692 (confirm (lambda (x) (stringp (car x)))))
14693 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14694 (setq s1 (match-string 1 string)
14695 s2 (match-string 2 string))
14696 (setq s1 "" s2 string))
14697 (cond
14698 ((eq flag nil)
14699 ;; try completion
14700 (setq rtn (try-completion s2 ctable confirm))
14701 (if (stringp rtn)
14702 (setq rtn
14703 (concat s1 s2 (substring rtn (length s2))
14704 (if (and org-add-colon-after-tag-completion
14705 (assoc rtn ctable))
14706 ":" ""))))
14707 rtn)
14708 ((eq flag t)
14709 ;; all-completions
14710 (all-completions s2 ctable confirm))
14711 ((eq flag 'lambda)
14712 ;; exact match?
14713 (assoc s2 ctable)))))
14715 (defun org-fast-tag-insert (kwd tags face &optional end)
14716 "Insert KDW, and the TAGS, the latter with face FACE.
14717 Also insert END."
14718 (insert (format "%-12s" (concat kwd ":"))
14719 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14720 (or end "")))
14722 (defun org-fast-tag-show-exit (flag)
14723 (save-excursion
14724 (org-goto-line 3)
14725 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14726 (replace-match ""))
14727 (when flag
14728 (end-of-line 1)
14729 (org-move-to-column (- (window-width) 19) t)
14730 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14732 (defun org-set-current-tags-overlay (current prefix)
14733 "Add an overlay to CURRENT tag with PREFIX."
14734 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14735 (if (featurep 'xemacs)
14736 (org-overlay-display org-tags-overlay (concat prefix s)
14737 'secondary-selection)
14738 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14739 (org-overlay-display org-tags-overlay (concat prefix s)))))
14741 (defvar org-last-tag-selection-key nil)
14742 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14743 "Fast tag selection with single keys.
14744 CURRENT is the current list of tags in the headline, INHERITED is the
14745 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14746 possibly with grouping information. TODO-TABLE is a similar table with
14747 TODO keywords, should these have keys assigned to them.
14748 If the keys are nil, a-z are automatically assigned.
14749 Returns the new tags string, or nil to not change the current settings."
14750 (let* ((fulltable (append table todo-table))
14751 (maxlen (apply 'max (mapcar
14752 (lambda (x)
14753 (if (stringp (car x)) (string-width (car x)) 0))
14754 fulltable)))
14755 (buf (current-buffer))
14756 (expert (eq org-fast-tag-selection-single-key 'expert))
14757 (buffer-tags nil)
14758 (fwidth (+ maxlen 3 1 3))
14759 (ncol (/ (- (window-width) 4) fwidth))
14760 (i-face 'org-done)
14761 (c-face 'org-todo)
14762 tg cnt c char c1 c2 ntable tbl rtn
14763 ov-start ov-end ov-prefix
14764 (exit-after-next org-fast-tag-selection-single-key)
14765 (done-keywords org-done-keywords)
14766 groups ingroup)
14767 (save-excursion
14768 (beginning-of-line 1)
14769 (if (looking-at
14770 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14771 (setq ov-start (match-beginning 1)
14772 ov-end (match-end 1)
14773 ov-prefix "")
14774 (setq ov-start (1- (point-at-eol))
14775 ov-end (1+ ov-start))
14776 (skip-chars-forward "^\n\r")
14777 (setq ov-prefix
14778 (concat
14779 (buffer-substring (1- (point)) (point))
14780 (if (> (current-column) org-tags-column)
14782 (make-string (- org-tags-column (current-column)) ?\ ))))))
14783 (move-overlay org-tags-overlay ov-start ov-end)
14784 (save-window-excursion
14785 (if expert
14786 (set-buffer (get-buffer-create " *Org tags*"))
14787 (delete-other-windows)
14788 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14789 (org-switch-to-buffer-other-window " *Org tags*"))
14790 (erase-buffer)
14791 (org-set-local 'org-done-keywords done-keywords)
14792 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14793 (org-fast-tag-insert "Current" current c-face "\n\n")
14794 (org-fast-tag-show-exit exit-after-next)
14795 (org-set-current-tags-overlay current ov-prefix)
14796 (setq tbl fulltable char ?a cnt 0)
14797 (dolist (e tbl)
14798 (cond
14799 ((equal (car e) :startgroup)
14800 (push '() groups) (setq ingroup t)
14801 (when (not (= cnt 0))
14802 (setq cnt 0)
14803 (insert "\n"))
14804 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14805 ((equal (car e) :endgroup)
14806 (setq ingroup nil cnt 0)
14807 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14808 ((equal e '(:newline))
14809 (when (not (= cnt 0))
14810 (setq cnt 0)
14811 (insert "\n")
14812 (setq e (car tbl))
14813 (while (equal (car tbl) '(:newline))
14814 (insert "\n")
14815 (setq tbl (cdr tbl)))))
14816 ((equal e '(:grouptags)) nil)
14818 (setq tg (copy-sequence (car e)) c2 nil)
14819 (if (cdr e)
14820 (setq c (cdr e))
14821 ;; automatically assign a character.
14822 (setq c1 (string-to-char
14823 (downcase (substring
14824 tg (if (= (string-to-char tg) ?@) 1 0)))))
14825 (if (or (rassoc c1 ntable) (rassoc c1 table))
14826 (while (or (rassoc char ntable) (rassoc char table))
14827 (setq char (1+ char)))
14828 (setq c2 c1))
14829 (setq c (or c2 char)))
14830 (if ingroup (push tg (car groups)))
14831 (setq tg (org-add-props tg nil 'face
14832 (cond
14833 ((not (assoc tg table))
14834 (org-get-todo-face tg))
14835 ((member tg current) c-face)
14836 ((member tg inherited) i-face))))
14837 (if (equal (caar tbl) :grouptags)
14838 (org-add-props tg nil 'face 'org-tag-group))
14839 (if (and (= cnt 0) (not ingroup)) (insert " "))
14840 (insert "[" c "] " tg (make-string
14841 (- fwidth 4 (length tg)) ?\ ))
14842 (push (cons tg c) ntable)
14843 (when (= (setq cnt (1+ cnt)) ncol)
14844 (insert "\n")
14845 (if ingroup (insert " "))
14846 (setq cnt 0)))))
14847 (setq ntable (nreverse ntable))
14848 (insert "\n")
14849 (goto-char (point-min))
14850 (if (not expert) (org-fit-window-to-buffer))
14851 (setq rtn
14852 (catch 'exit
14853 (while t
14854 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14855 (if (not groups) "no " "")
14856 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14857 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14858 (setq org-last-tag-selection-key c)
14859 (cond
14860 ((= c ?\r) (throw 'exit t))
14861 ((= c ?!)
14862 (setq groups (not groups))
14863 (goto-char (point-min))
14864 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14865 ((= c ?\C-c)
14866 (if (not expert)
14867 (org-fast-tag-show-exit
14868 (setq exit-after-next (not exit-after-next)))
14869 (setq expert nil)
14870 (delete-other-windows)
14871 (set-window-buffer (split-window-vertically) " *Org tags*")
14872 (org-switch-to-buffer-other-window " *Org tags*")
14873 (org-fit-window-to-buffer)))
14874 ((or (= c ?\C-g)
14875 (and (= c ?q) (not (rassoc c ntable))))
14876 (org-detach-overlay org-tags-overlay)
14877 (setq quit-flag t))
14878 ((= c ?\ )
14879 (setq current nil)
14880 (if exit-after-next (setq exit-after-next 'now)))
14881 ((= c ?\t)
14882 (condition-case nil
14883 (setq tg (org-icompleting-read
14884 "Tag: "
14885 (or buffer-tags
14886 (with-current-buffer buf
14887 (org-get-buffer-tags)))))
14888 (quit (setq tg "")))
14889 (when (string-match "\\S-" tg)
14890 (add-to-list 'buffer-tags (list tg))
14891 (if (member tg current)
14892 (setq current (delete tg current))
14893 (push tg current)))
14894 (if exit-after-next (setq exit-after-next 'now)))
14895 ((setq e (rassoc c todo-table) tg (car e))
14896 (with-current-buffer buf
14897 (save-excursion (org-todo tg)))
14898 (if exit-after-next (setq exit-after-next 'now)))
14899 ((setq e (rassoc c ntable) tg (car e))
14900 (if (member tg current)
14901 (setq current (delete tg current))
14902 (loop for g in groups do
14903 (if (member tg g)
14904 (mapc (lambda (x)
14905 (setq current (delete x current)))
14906 g)))
14907 (push tg current))
14908 (if exit-after-next (setq exit-after-next 'now))))
14910 ;; Create a sorted list
14911 (setq current
14912 (sort current
14913 (lambda (a b)
14914 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14915 (if (eq exit-after-next 'now) (throw 'exit t))
14916 (goto-char (point-min))
14917 (beginning-of-line 2)
14918 (delete-region (point) (point-at-eol))
14919 (org-fast-tag-insert "Current" current c-face)
14920 (org-set-current-tags-overlay current ov-prefix)
14921 (while (re-search-forward
14922 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14923 (setq tg (match-string 1))
14924 (add-text-properties
14925 (match-beginning 1) (match-end 1)
14926 (list 'face
14927 (cond
14928 ((member tg current) c-face)
14929 ((member tg inherited) i-face)
14930 (t (get-text-property (match-beginning 1) 'face))))))
14931 (goto-char (point-min)))))
14932 (org-detach-overlay org-tags-overlay)
14933 (if rtn
14934 (mapconcat 'identity current ":")
14935 nil))))
14937 (defun org-get-tags-string ()
14938 "Get the TAGS string in the current headline."
14939 (unless (org-at-heading-p t)
14940 (user-error "Not on a heading"))
14941 (save-excursion
14942 (beginning-of-line 1)
14943 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14944 (org-match-string-no-properties 1)
14945 "")))
14947 (defun org-get-tags ()
14948 "Get the list of tags specified in the current headline."
14949 (org-split-string (org-get-tags-string) ":"))
14951 (defun org-get-buffer-tags ()
14952 "Get a table of all tags used in the buffer, for completion."
14953 (let (tags)
14954 (save-excursion
14955 (goto-char (point-min))
14956 (while (re-search-forward
14957 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14958 (when (equal (char-after (point-at-bol 0)) ?*)
14959 (mapc (lambda (x) (add-to-list 'tags x))
14960 (org-split-string (org-match-string-no-properties 1) ":")))))
14961 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14962 (mapcar 'list tags)))
14964 ;;;; The mapping API
14966 (defun org-map-entries (func &optional match scope &rest skip)
14967 "Call FUNC at each headline selected by MATCH in SCOPE.
14969 FUNC is a function or a lisp form. The function will be called without
14970 arguments, with the cursor positioned at the beginning of the headline.
14971 The return values of all calls to the function will be collected and
14972 returned as a list.
14974 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14975 does not need to preserve point. After evaluation, the cursor will be
14976 moved to the end of the line (presumably of the headline of the
14977 processed entry) and search continues from there. Under some
14978 circumstances, this may not produce the wanted results. For example,
14979 if you have removed (e.g. archived) the current (sub)tree it could
14980 mean that the next entry will be skipped entirely. In such cases, you
14981 can specify the position from where search should continue by making
14982 FUNC set the variable `org-map-continue-from' to the desired buffer
14983 position.
14985 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14986 Only headlines that are matched by this query will be considered during
14987 the iteration. When MATCH is nil or t, all headlines will be
14988 visited by the iteration.
14990 SCOPE determines the scope of this command. It can be any of:
14992 nil The current buffer, respecting the restriction if any
14993 tree The subtree started with the entry at point
14994 region The entries within the active region, if any
14995 region-start-level
14996 The entries within the active region, but only those at
14997 the same level than the first one.
14998 file The current buffer, without restriction
14999 file-with-archives
15000 The current buffer, and any archives associated with it
15001 agenda All agenda files
15002 agenda-with-archives
15003 All agenda files with any archive files associated with them
15004 \(file1 file2 ...)
15005 If this is a list, all files in the list will be scanned
15007 The remaining args are treated as settings for the skipping facilities of
15008 the scanner. The following items can be given here:
15010 archive skip trees with the archive tag
15011 comment skip trees with the COMMENT keyword
15012 function or Emacs Lisp form:
15013 will be used as value for `org-agenda-skip-function', so
15014 whenever the function returns a position, FUNC will not be
15015 called for that entry and search will continue from the
15016 position returned
15018 If your function needs to retrieve the tags including inherited tags
15019 at the *current* entry, you can use the value of the variable
15020 `org-scanner-tags' which will be much faster than getting the value
15021 with `org-get-tags-at'. If your function gets properties with
15022 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15023 to t around the call to `org-entry-properties' to get the same speedup.
15024 Note that if your function moves around to retrieve tags and properties at
15025 a *different* entry, you cannot use these techniques."
15026 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15027 (not (org-region-active-p)))
15028 (let* ((org-agenda-archives-mode nil) ; just to make sure
15029 (org-agenda-skip-archived-trees (memq 'archive skip))
15030 (org-agenda-skip-comment-trees (memq 'comment skip))
15031 (org-agenda-skip-function
15032 (car (org-delete-all '(comment archive) skip)))
15033 (org-tags-match-list-sublevels t)
15034 (start-level (eq scope 'region-start-level))
15035 matcher file res
15036 org-todo-keywords-for-agenda
15037 org-done-keywords-for-agenda
15038 org-todo-keyword-alist-for-agenda
15039 org-drawers-for-agenda
15040 org-tag-alist-for-agenda
15041 todo-only)
15043 (cond
15044 ((eq match t) (setq matcher t))
15045 ((eq match nil) (setq matcher t))
15046 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15048 (save-excursion
15049 (save-restriction
15050 (cond ((eq scope 'tree)
15051 (org-back-to-heading t)
15052 (org-narrow-to-subtree)
15053 (setq scope nil))
15054 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15055 (org-region-active-p))
15056 ;; If needed, set start-level to a string like "2"
15057 (when start-level
15058 (save-excursion
15059 (goto-char (region-beginning))
15060 (unless (org-at-heading-p) (outline-next-heading))
15061 (setq start-level (org-current-level))))
15062 (narrow-to-region (region-beginning)
15063 (save-excursion
15064 (goto-char (region-end))
15065 (unless (and (bolp) (org-at-heading-p))
15066 (outline-next-heading))
15067 (point)))
15068 (setq scope nil)))
15070 (if (not scope)
15071 (progn
15072 (org-agenda-prepare-buffers
15073 (and buffer-file-name (list buffer-file-name)))
15074 (setq res (org-scan-tags func matcher todo-only start-level)))
15075 ;; Get the right scope
15076 (cond
15077 ((and scope (listp scope) (symbolp (car scope)))
15078 (setq scope (eval scope)))
15079 ((eq scope 'agenda)
15080 (setq scope (org-agenda-files t)))
15081 ((eq scope 'agenda-with-archives)
15082 (setq scope (org-agenda-files t))
15083 (setq scope (org-add-archive-files scope)))
15084 ((eq scope 'file)
15085 (setq scope (and buffer-file-name (list buffer-file-name))))
15086 ((eq scope 'file-with-archives)
15087 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15088 (org-agenda-prepare-buffers scope)
15089 (dolist (file scope)
15090 (with-current-buffer (org-find-base-buffer-visiting file)
15091 (save-excursion
15092 (save-restriction
15093 (widen)
15094 (goto-char (point-min))
15095 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15096 res)))
15098 ;;;; Properties
15100 ;;; Setting and retrieving properties
15102 (defconst org-special-properties
15103 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15104 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15105 "The special properties valid in Org-mode.
15107 These are properties that are not defined in the property drawer,
15108 but in some other way.")
15110 (defconst org-default-properties
15111 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15112 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15113 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15114 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15115 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15116 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15117 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15118 "Some properties that are used by Org-mode for various purposes.
15119 Being in this list makes sure that they are offered for completion.")
15121 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15122 "Regular expression matching the first line of a property drawer.")
15124 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15125 "Regular expression matching the last line of a property drawer.")
15127 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15128 "Regular expression matching the first line of a property drawer.")
15130 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15131 "Regular expression matching the first line of a property drawer.")
15133 (defconst org-property-drawer-re
15134 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15135 org-property-end-re "\\)\n?")
15136 "Matches an entire property drawer.")
15138 (defconst org-clock-drawer-re
15139 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15140 org-property-end-re "\\)\n?")
15141 "Matches an entire clock drawer.")
15143 (defun org-property-action ()
15144 "Do an action on properties."
15145 (interactive)
15146 (let (c)
15147 (org-at-property-p)
15148 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15149 (setq c (read-char-exclusive))
15150 (cond
15151 ((equal c ?s)
15152 (call-interactively 'org-set-property))
15153 ((equal c ?d)
15154 (call-interactively 'org-delete-property))
15155 ((equal c ?D)
15156 (call-interactively 'org-delete-property-globally))
15157 ((equal c ?c)
15158 (call-interactively 'org-compute-property-at-point))
15159 (t (user-error "No such property action %c" c)))))
15161 (defun org-inc-effort ()
15162 "Increment the value of the effort property in the current entry."
15163 (interactive)
15164 (org-set-effort nil t))
15166 (defvar org-clock-effort) ;; Defined in org-clock.el
15167 (defvar org-clock-current-task) ;; Defined in org-clock.el
15168 (defun org-set-effort (&optional value increment)
15169 "Set the effort property of the current entry.
15170 With numerical prefix arg, use the nth allowed value, 0 stands for the
15171 10th allowed value.
15173 When INCREMENT is non-nil, set the property to the next allowed value."
15174 (interactive "P")
15175 (if (equal value 0) (setq value 10))
15176 (let* ((completion-ignore-case t)
15177 (prop org-effort-property)
15178 (cur (org-entry-get nil prop))
15179 (allowed (org-property-get-allowed-values nil prop 'table))
15180 (existing (mapcar 'list (org-property-values prop)))
15181 (heading (nth 4 (org-heading-components)))
15183 (val (cond
15184 ((stringp value) value)
15185 ((and allowed (integerp value))
15186 (or (car (nth (1- value) allowed))
15187 (car (org-last allowed))))
15188 ((and allowed increment)
15189 (or (caadr (member (list cur) allowed))
15190 (user-error "Allowed effort values are not set")))
15191 (allowed
15192 (message "Select 1-9,0, [RET%s]: %s"
15193 (if cur (concat "=" cur) "")
15194 (mapconcat 'car allowed " "))
15195 (setq rpl (read-char-exclusive))
15196 (if (equal rpl ?\r)
15198 (setq rpl (- rpl ?0))
15199 (if (equal rpl 0) (setq rpl 10))
15200 (if (and (> rpl 0) (<= rpl (length allowed)))
15201 (car (nth (1- rpl) allowed))
15202 (org-completing-read "Effort: " allowed nil))))
15204 (let (org-completion-use-ido org-completion-use-iswitchb)
15205 (org-completing-read
15206 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15207 (concat "[" cur "]") "")
15208 ": ")
15209 existing nil nil "" nil cur))))))
15210 (unless (equal (org-entry-get nil prop) val)
15211 (org-entry-put nil prop val))
15212 (save-excursion
15213 (org-back-to-heading t)
15214 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15215 (when (string= heading org-clock-current-task)
15216 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15217 (org-clock-update-mode-line))
15218 (message "%s is now %s" prop val)))
15220 (defun org-at-property-p ()
15221 "Is cursor inside a property drawer?"
15222 (save-excursion
15223 (when (equal 'node-property (car (org-element-at-point)))
15224 (beginning-of-line 1)
15225 (looking-at org-property-re))))
15227 (defun org-get-property-block (&optional beg end force)
15228 "Return the (beg . end) range of the body of the property drawer.
15229 BEG and END are the beginning and end of the current subtree, or of
15230 the part before the first headline. If they are not given, they will
15231 be found. If the drawer does not exist and FORCE is non-nil, create
15232 the drawer."
15233 (catch 'exit
15234 (save-excursion
15235 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15236 (progn (org-back-to-heading t) (point))))
15237 (end (or end (and (not (outline-next-heading)) (point-max))
15238 (point))))
15239 (goto-char beg)
15240 (if (re-search-forward org-property-start-re end t)
15241 (setq beg (1+ (match-end 0)))
15242 (if force
15243 (save-excursion
15244 (org-insert-property-drawer)
15245 (setq end (progn (outline-next-heading) (point))))
15246 (throw 'exit nil))
15247 (goto-char beg)
15248 (if (re-search-forward org-property-start-re end t)
15249 (setq beg (1+ (match-end 0)))))
15250 (if (re-search-forward org-property-end-re end t)
15251 (setq end (match-beginning 0))
15252 (or force (throw 'exit nil))
15253 (goto-char beg)
15254 (setq end beg)
15255 (org-indent-line)
15256 (insert ":END:\n"))
15257 (cons beg end)))))
15259 (defun org-entry-properties (&optional pom which specific)
15260 "Get all properties of the entry at point-or-marker POM.
15261 This includes the TODO keyword, the tags, time strings for deadline,
15262 scheduled, and clocking, and any additional properties defined in the
15263 entry. The return value is an alist, keys may occur multiple times
15264 if the property key was used several times.
15265 POM may also be nil, in which case the current entry is used.
15266 If WHICH is nil or `all', get all properties. If WHICH is
15267 `special' or `standard', only get that subclass. If WHICH
15268 is a string only get exactly this property. SPECIFIC can be a string, the
15269 specific property we are interested in. Specifying it can speed
15270 things up because then unnecessary parsing is avoided."
15271 (setq which (or which 'all))
15272 (org-with-wide-buffer
15273 (org-with-point-at pom
15274 (let ((clockstr (substring org-clock-string 0 -1))
15275 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15276 (case-fold-search nil)
15277 beg end range props sum-props key key1 value string clocksum clocksumt)
15278 (when (and (derived-mode-p 'org-mode)
15279 (ignore-errors (org-back-to-heading t)))
15280 (setq beg (point))
15281 (setq sum-props (get-text-property (point) 'org-summaries))
15282 (setq clocksum (get-text-property (point) :org-clock-minutes)
15283 clocksumt (get-text-property (point) :org-clock-minutes-today))
15284 (outline-next-heading)
15285 (setq end (point))
15286 (when (memq which '(all special))
15287 ;; Get the special properties, like TODO and tags
15288 (goto-char beg)
15289 (when (and (or (not specific) (string= specific "TODO"))
15290 (looking-at org-todo-line-regexp) (match-end 2))
15291 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15292 (when (and (or (not specific) (string= specific "PRIORITY"))
15293 (looking-at org-priority-regexp))
15294 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15295 (when (or (not specific) (string= specific "FILE"))
15296 (push (cons "FILE" buffer-file-name) props))
15297 (when (and (or (not specific) (string= specific "TAGS"))
15298 (setq value (org-get-tags-string))
15299 (string-match "\\S-" value))
15300 (push (cons "TAGS" value) props))
15301 (when (and (or (not specific) (string= specific "ALLTAGS"))
15302 (setq value (org-get-tags-at)))
15303 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15304 ":"))
15305 props))
15306 (when (or (not specific) (string= specific "BLOCKED"))
15307 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15308 (when (or (not specific)
15309 (member specific
15310 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15311 "TIMESTAMP" "TIMESTAMP_IA")))
15312 (catch 'match
15313 (while (and (re-search-forward org-maybe-keyword-time-regexp end t)
15314 (not (text-property-any 0 (length (match-string 0))
15315 'face 'font-lock-comment-face
15316 (match-string 0))))
15317 (setq key (if (match-end 1)
15318 (substring (org-match-string-no-properties 1)
15319 0 -1))
15320 string (if (equal key clockstr)
15321 (org-trim
15322 (buffer-substring-no-properties
15323 (match-beginning 3) (goto-char
15324 (point-at-eol))))
15325 (substring (org-match-string-no-properties 3)
15326 1 -1)))
15327 ;; Get the correct property name from the key. This is
15328 ;; necessary if the user has configured time keywords.
15329 (setq key1 (concat key ":"))
15330 (cond
15331 ((not key)
15332 (setq key
15333 (if (= (char-after (match-beginning 3)) ?\[)
15334 "TIMESTAMP_IA" "TIMESTAMP")))
15335 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15336 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15337 ((equal key1 org-closed-string) (setq key "CLOSED"))
15338 ((equal key1 org-clock-string) (setq key "CLOCK")))
15339 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15340 (progn
15341 (push (cons key string) props)
15342 ;; no need to search further if match is found
15343 (throw 'match t))
15344 (when (or (equal key "CLOCK") (not (assoc key props)))
15345 (push (cons key string) props)))))))
15347 (when (memq which '(all standard))
15348 ;; Get the standard properties, like :PROP: ...
15349 (setq range (org-get-property-block beg end))
15350 (when range
15351 (goto-char (car range))
15352 (while (re-search-forward org-property-re
15353 (cdr range) t)
15354 (setq key (org-match-string-no-properties 2)
15355 value (org-trim (or (org-match-string-no-properties 3) "")))
15356 (unless (member key excluded)
15357 (push (cons key (or value "")) props)))))
15358 (if clocksum
15359 (push (cons "CLOCKSUM"
15360 (org-columns-number-to-string (/ (float clocksum) 60.)
15361 'add_times))
15362 props))
15363 (if clocksumt
15364 (push (cons "CLOCKSUM_T"
15365 (org-columns-number-to-string (/ (float clocksumt) 60.)
15366 'add_times))
15367 props))
15368 (unless (assoc "CATEGORY" props)
15369 (push (cons "CATEGORY" (org-get-category)) props))
15370 (append sum-props (nreverse props)))))))
15372 (defun org-entry-get (pom property &optional inherit literal-nil)
15373 "Get value of PROPERTY for entry or content at point-or-marker POM.
15374 If INHERIT is non-nil and the entry does not have the property,
15375 then also check higher levels of the hierarchy.
15376 If INHERIT is the symbol `selective', use inheritance only if the setting
15377 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15378 If the property is present but empty, the return value is the empty string.
15379 If the property is not present at all, nil is returned.
15381 Return the value as a string.
15383 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15384 do not interpret it as the list atom nil. This is used for inheritance
15385 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15386 (org-with-point-at pom
15387 (if (and inherit (if (eq inherit 'selective)
15388 (org-property-inherit-p property)
15390 (org-entry-get-with-inheritance property literal-nil)
15391 (if (member property org-special-properties)
15392 ;; We need a special property. Use `org-entry-properties'
15393 ;; to retrieve it, but specify the wanted property
15394 (cdr (assoc property (org-entry-properties nil 'special property)))
15395 (org-with-wide-buffer
15396 (let ((range (org-get-property-block)))
15397 (when (and range (not (eq (car range) (cdr range)))
15398 (save-excursion
15399 (goto-char (car range))
15400 (re-search-forward
15401 (concat (org-re-property property) "\\|"
15402 (org-re-property (concat property "+")))
15403 (cdr range) t)))
15404 (let* ((props
15405 (list (or (assoc property org-file-properties)
15406 (assoc property org-global-properties)
15407 (assoc property org-global-properties-fixed))))
15408 (ap (lambda (key)
15409 (when (re-search-forward
15410 (org-re-property key) (cdr range) t)
15411 (setq props
15412 (org-update-property-plist
15414 (if (match-end 3)
15415 (org-match-string-no-properties 3) "")
15416 props)))))
15417 val)
15418 (goto-char (car range))
15419 (funcall ap property)
15420 (goto-char (car range))
15421 (while (funcall ap (concat property "+")))
15422 (setq val (cdr (assoc property props)))
15423 (when val (if literal-nil val (org-not-nil val)))))))))))
15425 (defun org-property-or-variable-value (var &optional inherit)
15426 "Check if there is a property fixing the value of VAR.
15427 If yes, return this value. If not, return the current value of the variable."
15428 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15429 (if (and prop (stringp prop) (string-match "\\S-" prop))
15430 (read prop)
15431 (symbol-value var))))
15433 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15434 "Delete the property PROPERTY from entry at point-or-marker POM.
15435 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15436 an empty drawer to delete."
15437 (org-with-point-at pom
15438 (if (member property org-special-properties)
15439 nil ; cannot delete these properties.
15440 (let ((range (org-get-property-block)))
15441 (if (and range
15442 (goto-char (car range))
15443 (re-search-forward
15444 (org-re-property property nil t)
15445 (cdr range) t))
15446 (progn
15447 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15448 (and delete-empty-drawer
15449 (org-remove-empty-drawer-at
15450 delete-empty-drawer (car range)))
15452 nil)))))
15454 ;; Multi-values properties are properties that contain multiple values
15455 ;; These values are assumed to be single words, separated by whitespace.
15456 (defun org-entry-add-to-multivalued-property (pom property value)
15457 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15458 (let* ((old (org-entry-get pom property))
15459 (values (and old (org-split-string old "[ \t]"))))
15460 (setq value (org-entry-protect-space value))
15461 (unless (member value values)
15462 (setq values (append values (list value)))
15463 (org-entry-put pom property
15464 (mapconcat 'identity values " ")))))
15466 (defun org-entry-remove-from-multivalued-property (pom property value)
15467 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15468 (let* ((old (org-entry-get pom property))
15469 (values (and old (org-split-string old "[ \t]"))))
15470 (setq value (org-entry-protect-space value))
15471 (when (member value values)
15472 (setq values (delete value values))
15473 (org-entry-put pom property
15474 (mapconcat 'identity values " ")))))
15476 (defun org-entry-member-in-multivalued-property (pom property value)
15477 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15478 (let* ((old (org-entry-get pom property))
15479 (values (and old (org-split-string old "[ \t]"))))
15480 (setq value (org-entry-protect-space value))
15481 (member value values)))
15483 (defun org-entry-get-multivalued-property (pom property)
15484 "Return a list of values in a multivalued property."
15485 (let* ((value (org-entry-get pom property))
15486 (values (and value (org-split-string value "[ \t]"))))
15487 (mapcar 'org-entry-restore-space values)))
15489 (defun org-entry-put-multivalued-property (pom property &rest values)
15490 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15491 VALUES should be a list of strings. Spaces will be protected."
15492 (org-entry-put pom property
15493 (mapconcat 'org-entry-protect-space values " "))
15494 (let* ((value (org-entry-get pom property))
15495 (values (and value (org-split-string value "[ \t]"))))
15496 (mapcar 'org-entry-restore-space values)))
15498 (defun org-entry-protect-space (s)
15499 "Protect spaces and newline in string S."
15500 (while (string-match " " s)
15501 (setq s (replace-match "%20" t t s)))
15502 (while (string-match "\n" s)
15503 (setq s (replace-match "%0A" t t s)))
15506 (defun org-entry-restore-space (s)
15507 "Restore spaces and newline in string S."
15508 (while (string-match "%20" s)
15509 (setq s (replace-match " " t t s)))
15510 (while (string-match "%0A" s)
15511 (setq s (replace-match "\n" t t s)))
15514 (defvar org-entry-property-inherited-from (make-marker)
15515 "Marker pointing to the entry from where a property was inherited.
15516 Each call to `org-entry-get-with-inheritance' will set this marker to the
15517 location of the entry where the inheritance search matched. If there was
15518 no match, the marker will point nowhere.
15519 Note that also `org-entry-get' calls this function, if the INHERIT flag
15520 is set.")
15522 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15523 "Get PROPERTY of entry or content at point, search higher levels if needed.
15524 The search will stop at the first ancestor which has the property defined.
15525 If the value found is \"nil\", return nil to show that the property
15526 should be considered as undefined (this is the meaning of nil here).
15527 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15528 (move-marker org-entry-property-inherited-from nil)
15529 (let (tmp)
15530 (save-excursion
15531 (save-restriction
15532 (widen)
15533 (catch 'ex
15534 (while t
15535 (when (setq tmp (org-entry-get nil property nil literal-nil))
15536 (or (ignore-errors (org-back-to-heading t))
15537 (goto-char (point-min)))
15538 (move-marker org-entry-property-inherited-from (point))
15539 (throw 'ex tmp))
15540 (or (ignore-errors (org-up-heading-safe))
15541 (throw 'ex nil))))))
15542 (setq tmp (or tmp
15543 (cdr (assoc property org-file-properties))
15544 (cdr (assoc property org-global-properties))
15545 (cdr (assoc property org-global-properties-fixed))))
15546 (if literal-nil tmp (org-not-nil tmp))))
15548 (defvar org-property-changed-functions nil
15549 "Hook called when the value of a property has changed.
15550 Each hook function should accept two arguments, the name of the property
15551 and the new value.")
15553 (defun org-entry-put (pom property value)
15554 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15555 If the value is nil, it is converted to the empty string.
15556 If it is not a string, an error is raised."
15557 (cond ((null value) (setq value ""))
15558 ((not (stringp value))
15559 (error "Properties values should be strings.")))
15560 (org-with-point-at pom
15561 (org-back-to-heading t)
15562 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15563 range)
15564 (cond
15565 ((equal property "TODO")
15566 (when (and (string-match "\\S-" value)
15567 (not (member value org-todo-keywords-1)))
15568 (user-error "\"%s\" is not a valid TODO state" value))
15569 (if (or (not value)
15570 (not (string-match "\\S-" value)))
15571 (setq value 'none))
15572 (org-todo value)
15573 (org-set-tags nil 'align))
15574 ((equal property "PRIORITY")
15575 (org-priority (if (and value (string-match "\\S-" value))
15576 (string-to-char value) ?\ ))
15577 (org-set-tags nil 'align))
15578 ((equal property "CLOCKSUM")
15579 (if (not (re-search-forward
15580 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15581 (error "Cannot find a clock log")
15582 (goto-char (- (match-end 1) 2))
15583 (cond
15584 ((eq value 'earlier) (org-timestamp-down))
15585 ((eq value 'later) (org-timestamp-up)))
15586 (org-clock-sum-current-item)))
15587 ((equal property "SCHEDULED")
15588 (if (re-search-forward org-scheduled-time-regexp end t)
15589 (cond
15590 ((eq value 'earlier) (org-timestamp-change -1 'day))
15591 ((eq value 'later) (org-timestamp-change 1 'day))
15592 (t (call-interactively 'org-schedule)))
15593 (call-interactively 'org-schedule)))
15594 ((equal property "DEADLINE")
15595 (if (re-search-forward org-deadline-time-regexp end t)
15596 (cond
15597 ((eq value 'earlier) (org-timestamp-change -1 'day))
15598 ((eq value 'later) (org-timestamp-change 1 'day))
15599 (t (call-interactively 'org-deadline)))
15600 (call-interactively 'org-deadline)))
15601 ((member property org-special-properties)
15602 (error "The %s property can not yet be set with `org-entry-put'"
15603 property))
15604 (t ; a non-special property
15605 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15606 (setq range (org-get-property-block beg end 'force))
15607 (goto-char (car range))
15608 (if (re-search-forward
15609 (org-re-property property nil t) (cdr range) t)
15610 (progn
15611 (delete-region (match-beginning 0) (match-end 0))
15612 (goto-char (match-beginning 0)))
15613 (goto-char (cdr range))
15614 (insert "\n")
15615 (backward-char 1)
15616 (org-indent-line))
15617 (insert ":" property ":")
15618 (and value (insert " " value))
15619 (org-indent-line)))))
15620 (run-hook-with-args 'org-property-changed-functions property value)))
15622 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15623 "Get all property keys in the current buffer.
15624 With INCLUDE-SPECIALS, also list the special properties that reflect things
15625 like tags and TODO state.
15626 With INCLUDE-DEFAULTS, also include properties that has special meaning
15627 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15628 and others.
15629 With INCLUDE-COLUMNS, also include property names given in COLUMN
15630 formats in the current buffer."
15631 (let (rtn range cfmt s p)
15632 (save-excursion
15633 (save-restriction
15634 (widen)
15635 (goto-char (point-min))
15636 (while (re-search-forward org-property-start-re nil t)
15637 (setq range (org-get-property-block))
15638 (goto-char (car range))
15639 (while (re-search-forward org-property-re
15640 (cdr range) t)
15641 (add-to-list 'rtn (org-match-string-no-properties 2)))
15642 (outline-next-heading))))
15644 (when include-specials
15645 (setq rtn (append org-special-properties rtn)))
15647 (when include-defaults
15648 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15649 (add-to-list 'rtn org-effort-property))
15651 (when include-columns
15652 (save-excursion
15653 (save-restriction
15654 (widen)
15655 (goto-char (point-min))
15656 (while (re-search-forward
15657 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15658 nil t)
15659 (setq cfmt (match-string 2) s 0)
15660 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15661 cfmt s)
15662 (setq s (match-end 0)
15663 p (match-string 1 cfmt))
15664 (unless (or (equal p "ITEM")
15665 (member p org-special-properties))
15666 (add-to-list 'rtn (match-string 1 cfmt))))))))
15668 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15670 (defun org-property-values (key)
15671 "Return a list of all values of property KEY in the current buffer."
15672 (save-excursion
15673 (save-restriction
15674 (widen)
15675 (goto-char (point-min))
15676 (let ((re (org-re-property key))
15677 values)
15678 (while (re-search-forward re nil t)
15679 (add-to-list 'values (org-trim (match-string 3))))
15680 (delete "" values)))))
15682 (defun org-insert-property-drawer ()
15683 "Insert a property drawer into the current entry."
15684 (org-back-to-heading t)
15685 (looking-at org-outline-regexp)
15686 (let ((indent (if org-adapt-indentation
15687 (- (match-end 0) (match-beginning 0))
15689 (beg (point))
15690 (re (concat "^[ \t]*" org-keyword-time-regexp))
15691 end hiddenp)
15692 (outline-next-heading)
15693 (setq end (point))
15694 (goto-char beg)
15695 (while (re-search-forward re end t))
15696 (setq hiddenp (outline-invisible-p))
15697 (end-of-line 1)
15698 (and (equal (char-after) ?\n) (forward-char 1))
15699 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15700 (if (member (match-string 1) '("CLOCK:" ":END:"))
15701 ;; just skip this line
15702 (beginning-of-line 2)
15703 ;; Drawer start, find the end
15704 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15705 (beginning-of-line 1)))
15706 (org-skip-over-state-notes)
15707 (skip-chars-backward " \t\n\r")
15708 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15709 (forward-char 1))
15710 (goto-char (point-at-eol))
15711 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15712 (beginning-of-line 0)
15713 (org-indent-to-column indent)
15714 (beginning-of-line 2)
15715 (org-indent-to-column indent)
15716 (beginning-of-line 0)
15717 (if hiddenp
15718 (save-excursion
15719 (org-back-to-heading t)
15720 (hide-entry))
15721 (org-flag-drawer t))))
15723 (defun org-insert-drawer (&optional arg drawer)
15724 "Insert a drawer at point.
15726 Optional argument DRAWER, when non-nil, is a string representing
15727 drawer's name. Otherwise, the user is prompted for a name.
15729 If a region is active, insert the drawer around that region
15730 instead.
15732 Point is left between drawer's boundaries."
15733 (interactive "P")
15734 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15735 "LOGBOOK"))
15736 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15737 ;; internally by Org. They are meant to be inserted
15738 ;; automatically.
15739 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15740 ;; Remove system drawers from list. Note: For some reason,
15741 ;; `org-completing-read' ignores the predicate while
15742 ;; `completing-read' handles it fine.
15743 (drawer (if arg "PROPERTIES"
15744 (or drawer
15745 (completing-read
15746 "Drawer: " org-drawers
15747 (lambda (d) (not (member d system-drawers))))))))
15748 (cond
15749 ;; With C-u, fall back on `org-insert-property-drawer'
15750 (arg (org-insert-property-drawer))
15751 ;; With an active region, insert a drawer at point.
15752 ((not (org-region-active-p))
15753 (progn
15754 (unless (bolp) (insert "\n"))
15755 (insert (format ":%s:\n\n:END:\n" drawer))
15756 (forward-line -2)))
15757 ;; Otherwise, insert the drawer at point
15759 (let ((rbeg (region-beginning))
15760 (rend (copy-marker (region-end))))
15761 (unwind-protect
15762 (progn
15763 (goto-char rbeg)
15764 (beginning-of-line)
15765 (when (save-excursion
15766 (re-search-forward org-outline-regexp-bol rend t))
15767 (user-error "Drawers cannot contain headlines"))
15768 ;; Position point at the beginning of the first
15769 ;; non-blank line in region. Insert drawer's opening
15770 ;; there, then indent it.
15771 (org-skip-whitespace)
15772 (beginning-of-line)
15773 (insert ":" drawer ":\n")
15774 (forward-line -1)
15775 (indent-for-tab-command)
15776 ;; Move point to the beginning of the first blank line
15777 ;; after the last non-blank line in region. Insert
15778 ;; drawer's closing, then indent it.
15779 (goto-char rend)
15780 (skip-chars-backward " \r\t\n")
15781 (insert "\n:END:")
15782 (deactivate-mark t)
15783 (indent-for-tab-command)
15784 (unless (eolp) (insert "\n")))
15785 ;; Clear marker, whatever the outcome of insertion is.
15786 (set-marker rend nil)))))))
15788 (defvar org-property-set-functions-alist nil
15789 "Property set function alist.
15790 Each entry should have the following format:
15792 (PROPERTY . READ-FUNCTION)
15794 The read function will be called with the same argument as
15795 `org-completing-read'.")
15797 (defun org-set-property-function (property)
15798 "Get the function that should be used to set PROPERTY.
15799 This is computed according to `org-property-set-functions-alist'."
15800 (or (cdr (assoc property org-property-set-functions-alist))
15801 'org-completing-read))
15803 (defun org-read-property-value (property)
15804 "Read PROPERTY value from user."
15805 (let* ((completion-ignore-case t)
15806 (allowed (org-property-get-allowed-values nil property 'table))
15807 (cur (org-entry-get nil property))
15808 (prompt (concat property " value"
15809 (if (and cur (string-match "\\S-" cur))
15810 (concat " [" cur "]") "") ": "))
15811 (set-function (org-set-property-function property))
15812 (val (if allowed
15813 (funcall set-function prompt allowed nil
15814 (not (get-text-property 0 'org-unrestricted
15815 (caar allowed))))
15816 (let (org-completion-use-ido org-completion-use-iswitchb)
15817 (funcall set-function prompt
15818 (mapcar 'list (org-property-values property))
15819 nil nil "" nil cur)))))
15820 (org-trim val)))
15822 (defvar org-last-set-property nil)
15823 (defvar org-last-set-property-value nil)
15824 (defun org-read-property-name ()
15825 "Read a property name."
15826 (let* ((completion-ignore-case t)
15827 (keys (org-buffer-property-keys nil t t))
15828 (default-prop (or (save-excursion
15829 (save-match-data
15830 (beginning-of-line)
15831 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15832 (null (string= (match-string 1) "END"))
15833 (match-string 1))))
15834 org-last-set-property))
15835 (property (org-icompleting-read
15836 (concat "Property"
15837 (if default-prop (concat " [" default-prop "]") "")
15838 ": ")
15839 (mapcar 'list keys)
15840 nil nil nil nil
15841 default-prop)))
15842 (if (member property keys)
15843 property
15844 (or (cdr (assoc (downcase property)
15845 (mapcar (lambda (x) (cons (downcase x) x))
15846 keys)))
15847 property))))
15849 (defun org-set-property-and-value (use-last)
15850 "Allow to set [PROPERTY]: [value] direction from prompt.
15851 When use-default, don't even ask, just use the last
15852 \"[PROPERTY]: [value]\" string from the history."
15853 (interactive "P")
15854 (let* ((completion-ignore-case t)
15855 (pv (or (and use-last org-last-set-property-value)
15856 (org-completing-read
15857 "Enter a \"[Property]: [value]\" pair: "
15858 nil nil nil nil nil
15859 org-last-set-property-value)))
15860 prop val)
15861 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15862 (setq prop (match-string 1 pv)
15863 val (match-string 2 pv))
15864 (org-set-property prop val))))
15866 (defun org-set-property (property value)
15867 "In the current entry, set PROPERTY to VALUE.
15868 When called interactively, this will prompt for a property name, offering
15869 completion on existing and default properties. And then it will prompt
15870 for a value, offering completion either on allowed values (via an inherited
15871 xxx_ALL property) or on existing values in other instances of this property
15872 in the current file."
15873 (interactive (list nil nil))
15874 (let* ((property (or property (org-read-property-name)))
15875 (value (or value (org-read-property-value property)))
15876 (fn (cdr (assoc property org-properties-postprocess-alist))))
15877 (setq org-last-set-property property)
15878 (setq org-last-set-property-value (concat property ": " value))
15879 ;; Possibly postprocess the inserted value:
15880 (when fn (setq value (funcall fn value)))
15881 (unless (equal (org-entry-get nil property) value)
15882 (org-entry-put nil property value))))
15884 (defun org-delete-property (property &optional delete-empty-drawer)
15885 "In the current entry, delete PROPERTY.
15886 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15887 an empty drawer to delete."
15888 (interactive
15889 (let* ((completion-ignore-case t)
15890 (cat (org-entry-get (point) "CATEGORY"))
15891 (props0 (org-entry-properties nil 'standard))
15892 (props (if cat props0
15893 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15894 (prop (if (< 1 (length props))
15895 (org-icompleting-read "Property: " props nil t)
15896 (caar props))))
15897 (list prop)))
15898 (if (not property)
15899 (message "No property to delete in this entry")
15900 (org-entry-delete nil property delete-empty-drawer)
15901 (message "Property \"%s\" deleted" property)))
15903 (defun org-delete-property-globally (property)
15904 "Remove PROPERTY globally, from all entries."
15905 (interactive
15906 (let* ((completion-ignore-case t)
15907 (prop (org-icompleting-read
15908 "Globally remove property: "
15909 (mapcar 'list (org-buffer-property-keys)))))
15910 (list prop)))
15911 (save-excursion
15912 (save-restriction
15913 (widen)
15914 (goto-char (point-min))
15915 (let ((cnt 0))
15916 (while (re-search-forward
15917 (org-re-property property)
15918 nil t)
15919 (setq cnt (1+ cnt))
15920 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15921 (message "Property \"%s\" removed from %d entries" property cnt)))))
15923 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15925 (defun org-compute-property-at-point ()
15926 "Compute the property at point.
15927 This looks for an enclosing column format, extracts the operator and
15928 then applies it to the property in the column format's scope."
15929 (interactive)
15930 (unless (org-at-property-p)
15931 (user-error "Not at a property"))
15932 (let ((prop (org-match-string-no-properties 2)))
15933 (org-columns-get-format-and-top-level)
15934 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15935 (user-error "No operator defined for property %s" prop))
15936 (org-columns-compute prop)))
15938 (defvar org-property-allowed-value-functions nil
15939 "Hook for functions supplying allowed values for a specific property.
15940 The functions must take a single argument, the name of the property, and
15941 return a flat list of allowed values. If \":ETC\" is one of
15942 the values, this means that these values are intended as defaults for
15943 completion, but that other values should be allowed too.
15944 The functions must return nil if they are not responsible for this
15945 property.")
15947 (defun org-property-get-allowed-values (pom property &optional table)
15948 "Get allowed values for the property PROPERTY.
15949 When TABLE is non-nil, return an alist that can directly be used for
15950 completion."
15951 (let (vals)
15952 (cond
15953 ((equal property "TODO")
15954 (setq vals (org-with-point-at pom
15955 (append org-todo-keywords-1 '("")))))
15956 ((equal property "PRIORITY")
15957 (let ((n org-lowest-priority))
15958 (while (>= n org-highest-priority)
15959 (push (char-to-string n) vals)
15960 (setq n (1- n)))))
15961 ((member property org-special-properties))
15962 ((setq vals (run-hook-with-args-until-success
15963 'org-property-allowed-value-functions property)))
15965 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15966 (when (and vals (string-match "\\S-" vals))
15967 (setq vals (car (read-from-string (concat "(" vals ")"))))
15968 (setq vals (mapcar (lambda (x)
15969 (cond ((stringp x) x)
15970 ((numberp x) (number-to-string x))
15971 ((symbolp x) (symbol-name x))
15972 (t "???")))
15973 vals)))))
15974 (when (member ":ETC" vals)
15975 (setq vals (remove ":ETC" vals))
15976 (org-add-props (car vals) '(org-unrestricted t)))
15977 (if table (mapcar 'list vals) vals)))
15979 (defun org-property-previous-allowed-value (&optional previous)
15980 "Switch to the next allowed value for this property."
15981 (interactive)
15982 (org-property-next-allowed-value t))
15984 (defun org-property-next-allowed-value (&optional previous)
15985 "Switch to the next allowed value for this property."
15986 (interactive)
15987 (unless (org-at-property-p)
15988 (user-error "Not at a property"))
15989 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15990 (key (match-string 2))
15991 (value (match-string 3))
15992 (allowed (or (org-property-get-allowed-values (point) key)
15993 (and (member value '("[ ]" "[-]" "[X]"))
15994 '("[ ]" "[X]"))))
15995 (heading (save-match-data (nth 4 (org-heading-components))))
15996 nval)
15997 (unless allowed
15998 (user-error "Allowed values for this property have not been defined"))
15999 (if previous (setq allowed (reverse allowed)))
16000 (if (member value allowed)
16001 (setq nval (car (cdr (member value allowed)))))
16002 (setq nval (or nval (car allowed)))
16003 (if (equal nval value)
16004 (user-error "Only one allowed value for this property"))
16005 (org-at-property-p)
16006 (replace-match (concat " :" key ": " nval) t t)
16007 (org-indent-line)
16008 (beginning-of-line 1)
16009 (skip-chars-forward " \t")
16010 (when (equal prop org-effort-property)
16011 (save-excursion
16012 (org-back-to-heading t)
16013 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
16014 (when (string= org-clock-current-task heading)
16015 (setq org-clock-effort nval)
16016 (org-clock-update-mode-line)))
16017 (run-hook-with-args 'org-property-changed-functions key nval)))
16019 (defun org-find-olp (path &optional this-buffer)
16020 "Return a marker pointing to the entry at outline path OLP.
16021 If anything goes wrong, throw an error.
16022 You can wrap this call to catch the error like this:
16024 (condition-case msg
16025 (org-mobile-locate-entry (match-string 4))
16026 (error (nth 1 msg)))
16028 The return value will then be either a string with the error message,
16029 or a marker if everything is OK.
16031 If THIS-BUFFER is set, the outline path does not contain a file,
16032 only headings."
16033 (let* ((file (if this-buffer buffer-file-name (pop path)))
16034 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16035 (level 1)
16036 (lmin 1)
16037 (lmax 1)
16038 limit re end found pos heading cnt flevel)
16039 (unless buffer (error "File not found :%s" file))
16040 (with-current-buffer buffer
16041 (save-excursion
16042 (save-restriction
16043 (widen)
16044 (setq limit (point-max))
16045 (goto-char (point-min))
16046 (dolist (heading path)
16047 (setq re (format org-complex-heading-regexp-format
16048 (regexp-quote heading)))
16049 (setq cnt 0 pos (point))
16050 (while (re-search-forward re end t)
16051 (setq level (- (match-end 1) (match-beginning 1)))
16052 (if (and (>= level lmin) (<= level lmax))
16053 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16054 (when (= cnt 0) (error "Heading not found on level %d: %s"
16055 lmax heading))
16056 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16057 lmax heading))
16058 (goto-char found)
16059 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16060 (setq end (save-excursion (org-end-of-subtree t t))))
16061 (when (org-at-heading-p)
16062 (point-marker)))))))
16064 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16065 "Find node HEADING in BUFFER.
16066 Return a marker to the heading if it was found, or nil if not.
16067 If POS-ONLY is set, return just the position instead of a marker.
16069 The heading text must match exact, but it may have a TODO keyword,
16070 a priority cookie and tags in the standard locations."
16071 (with-current-buffer (or buffer (current-buffer))
16072 (save-excursion
16073 (save-restriction
16074 (widen)
16075 (goto-char (point-min))
16076 (let (case-fold-search)
16077 (if (re-search-forward
16078 (format org-complex-heading-regexp-format
16079 (regexp-quote heading)) nil t)
16080 (if pos-only
16081 (match-beginning 0)
16082 (move-marker (make-marker) (match-beginning 0)))))))))
16084 (defun org-find-exact-heading-in-directory (heading &optional dir)
16085 "Find Org node headline HEADING in all .org files in directory DIR.
16086 When the target headline is found, return a marker to this location."
16087 (let ((files (directory-files (or dir default-directory)
16088 nil "\\`[^.#].*\\.org\\'"))
16089 file visiting m buffer)
16090 (catch 'found
16091 (dolist (file files)
16092 (message "trying %s" file)
16093 (setq visiting (org-find-base-buffer-visiting file))
16094 (setq buffer (or visiting (find-file-noselect file)))
16095 (setq m (org-find-exact-headline-in-buffer
16096 heading buffer))
16097 (when (and (not m) (not visiting)) (kill-buffer buffer))
16098 (and m (throw 'found m))))))
16100 (defun org-find-entry-with-id (ident)
16101 "Locate the entry that contains the ID property with exact value IDENT.
16102 IDENT can be a string, a symbol or a number, this function will search for
16103 the string representation of it.
16104 Return the position where this entry starts, or nil if there is no such entry."
16105 (interactive "sID: ")
16106 (let ((id (cond
16107 ((stringp ident) ident)
16108 ((symbol-name ident) (symbol-name ident))
16109 ((numberp ident) (number-to-string ident))
16110 (t (error "IDENT %s must be a string, symbol or number" ident))))
16111 (case-fold-search nil))
16112 (save-excursion
16113 (save-restriction
16114 (widen)
16115 (goto-char (point-min))
16116 (when (re-search-forward
16117 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16118 nil t)
16119 (org-back-to-heading t)
16120 (point))))))
16122 ;;;; Timestamps
16124 (defvar org-last-changed-timestamp nil)
16125 (defvar org-last-inserted-timestamp nil
16126 "The last time stamp inserted with `org-insert-time-stamp'.")
16127 (defvar org-ts-what) ; dynamically scoped parameter
16129 (defun org-time-stamp (arg &optional inactive)
16130 "Prompt for a date/time and insert a time stamp.
16131 If the user specifies a time like HH:MM or if this command is
16132 called with at least one prefix argument, the time stamp contains
16133 the date and the time. Otherwise, only the date is be included.
16135 All parts of a date not specified by the user is filled in from
16136 the current date/time. So if you just press return without
16137 typing anything, the time stamp will represent the current
16138 date/time.
16140 If there is already a timestamp at the cursor, it will be
16141 modified.
16143 With two universal prefix arguments, insert an active timestamp
16144 with the current time without prompting the user.
16146 When called from lisp, the timestamp is inactive if INACTIVE is
16147 non-nil."
16148 (interactive "P")
16149 (let* ((ts nil)
16150 (default-time
16151 ;; Default time is either today, or, when entering a range,
16152 ;; the range start.
16153 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16154 (save-excursion
16155 (re-search-backward
16156 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16157 (- (point) 20) t)))
16158 (apply 'encode-time (org-parse-time-string (match-string 1)))
16159 (current-time)))
16160 (default-input (and ts (org-get-compact-tod ts)))
16161 (repeater (save-excursion
16162 (save-match-data
16163 (beginning-of-line)
16164 (when (re-search-forward
16165 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16166 (save-excursion (progn (end-of-line) (point))) t)
16167 (match-string 0)))))
16168 org-time-was-given org-end-time-was-given time)
16169 (cond
16170 ((and (org-at-timestamp-p t)
16171 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16172 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16173 (insert "--")
16174 (setq time (let ((this-command this-command))
16175 (org-read-date arg 'totime nil nil
16176 default-time default-input inactive)))
16177 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16178 ((org-at-timestamp-p t)
16179 (setq time (let ((this-command this-command))
16180 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16181 (when (org-at-timestamp-p t) ; just to get the match data
16182 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16183 (replace-match "")
16184 (setq org-last-changed-timestamp
16185 (org-insert-time-stamp
16186 time (or org-time-was-given arg)
16187 inactive nil nil (list org-end-time-was-given)))
16188 (when repeater (goto-char (1- (point))) (insert " " repeater)
16189 (setq org-last-changed-timestamp
16190 (concat (substring org-last-inserted-timestamp 0 -1)
16191 " " repeater ">"))))
16192 (message "Timestamp updated"))
16193 ((equal arg '(16))
16194 (org-insert-time-stamp (current-time) t inactive))
16196 (setq time (let ((this-command this-command))
16197 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16198 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16199 nil nil (list org-end-time-was-given))))))
16201 ;; FIXME: can we use this for something else, like computing time differences?
16202 (defun org-get-compact-tod (s)
16203 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16204 (let* ((t1 (match-string 1 s))
16205 (h1 (string-to-number (match-string 2 s)))
16206 (m1 (string-to-number (match-string 3 s)))
16207 (t2 (and (match-end 4) (match-string 5 s)))
16208 (h2 (and t2 (string-to-number (match-string 6 s))))
16209 (m2 (and t2 (string-to-number (match-string 7 s))))
16210 dh dm)
16211 (if (not t2)
16213 (setq dh (- h2 h1) dm (- m2 m1))
16214 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16215 (concat t1 "+" (number-to-string dh)
16216 (and (/= 0 dm) (format ":%02d" dm)))))))
16218 (defun org-time-stamp-inactive (&optional arg)
16219 "Insert an inactive time stamp.
16220 An inactive time stamp is enclosed in square brackets instead of angle
16221 brackets. It is inactive in the sense that it does not trigger agenda entries,
16222 does not link to the calendar and cannot be changed with the S-cursor keys.
16223 So these are more for recording a certain time/date."
16224 (interactive "P")
16225 (org-time-stamp arg 'inactive))
16227 (defvar org-date-ovl (make-overlay 1 1))
16228 (overlay-put org-date-ovl 'face 'org-date-selected)
16229 (org-detach-overlay org-date-ovl)
16231 (defvar org-ans1) ; dynamically scoped parameter
16232 (defvar org-ans2) ; dynamically scoped parameter
16234 (defvar org-plain-time-of-day-regexp) ; defined below
16236 (defvar org-overriding-default-time nil) ; dynamically scoped
16237 (defvar org-read-date-overlay nil)
16238 (defvar org-dcst nil) ; dynamically scoped
16239 (defvar org-read-date-history nil)
16240 (defvar org-read-date-final-answer nil)
16241 (defvar org-read-date-analyze-futurep nil)
16242 (defvar org-read-date-analyze-forced-year nil)
16243 (defvar org-read-date-inactive)
16245 (defvar org-read-date-minibuffer-local-map
16246 (let* ((org-replace-disputed-keys nil)
16247 (map (make-sparse-keymap)))
16248 (set-keymap-parent map minibuffer-local-map)
16249 (org-defkey map (kbd ".")
16250 (lambda () (interactive)
16251 ;; Are we at the beginning of the prompt?
16252 (if (looking-back "^[^:]+: ")
16253 (org-eval-in-calendar '(calendar-goto-today))
16254 (insert "."))))
16255 (org-defkey map (kbd "C-.")
16256 (lambda () (interactive)
16257 (org-eval-in-calendar '(calendar-goto-today))))
16258 (org-defkey map [(meta shift left)]
16259 (lambda () (interactive)
16260 (org-eval-in-calendar '(calendar-backward-month 1))))
16261 (org-defkey map [(meta shift right)]
16262 (lambda () (interactive)
16263 (org-eval-in-calendar '(calendar-forward-month 1))))
16264 (org-defkey map [(meta shift up)]
16265 (lambda () (interactive)
16266 (org-eval-in-calendar '(calendar-backward-year 1))))
16267 (org-defkey map [(meta shift down)]
16268 (lambda () (interactive)
16269 (org-eval-in-calendar '(calendar-forward-year 1))))
16270 (org-defkey map [?\e (shift left)]
16271 (lambda () (interactive)
16272 (org-eval-in-calendar '(calendar-backward-month 1))))
16273 (org-defkey map [?\e (shift right)]
16274 (lambda () (interactive)
16275 (org-eval-in-calendar '(calendar-forward-month 1))))
16276 (org-defkey map [?\e (shift up)]
16277 (lambda () (interactive)
16278 (org-eval-in-calendar '(calendar-backward-year 1))))
16279 (org-defkey map [?\e (shift down)]
16280 (lambda () (interactive)
16281 (org-eval-in-calendar '(calendar-forward-year 1))))
16282 (org-defkey map [(shift up)]
16283 (lambda () (interactive)
16284 (org-eval-in-calendar '(calendar-backward-week 1))))
16285 (org-defkey map [(shift down)]
16286 (lambda () (interactive)
16287 (org-eval-in-calendar '(calendar-forward-week 1))))
16288 (org-defkey map [(shift left)]
16289 (lambda () (interactive)
16290 (org-eval-in-calendar '(calendar-backward-day 1))))
16291 (org-defkey map [(shift right)]
16292 (lambda () (interactive)
16293 (org-eval-in-calendar '(calendar-forward-day 1))))
16294 (org-defkey map "!"
16295 (lambda () (interactive)
16296 (org-eval-in-calendar '(diary-view-entries))
16297 (message "")))
16298 (org-defkey map ">"
16299 (lambda () (interactive)
16300 (org-eval-in-calendar '(calendar-scroll-left 1))))
16301 (org-defkey map "<"
16302 (lambda () (interactive)
16303 (org-eval-in-calendar '(calendar-scroll-right 1))))
16304 (org-defkey map "\C-v"
16305 (lambda () (interactive)
16306 (org-eval-in-calendar
16307 '(calendar-scroll-left-three-months 1))))
16308 (org-defkey map "\M-v"
16309 (lambda () (interactive)
16310 (org-eval-in-calendar
16311 '(calendar-scroll-right-three-months 1))))
16312 map)
16313 "Keymap for minibuffer commands when using `org-read-date'.")
16315 (defvar org-def)
16316 (defvar org-defdecode)
16317 (defvar org-with-time)
16319 (defun org-read-date (&optional org-with-time to-time from-string prompt
16320 default-time default-input inactive)
16321 "Read a date, possibly a time, and make things smooth for the user.
16322 The prompt will suggest to enter an ISO date, but you can also enter anything
16323 which will at least partially be understood by `parse-time-string'.
16324 Unrecognized parts of the date will default to the current day, month, year,
16325 hour and minute. If this command is called to replace a timestamp at point,
16326 or to enter the second timestamp of a range, the default time is taken
16327 from the existing stamp. Furthermore, the command prefers the future,
16328 so if you are giving a date where the year is not given, and the day-month
16329 combination is already past in the current year, it will assume you
16330 mean next year. For details, see the manual. A few examples:
16332 3-2-5 --> 2003-02-05
16333 feb 15 --> currentyear-02-15
16334 2/15 --> currentyear-02-15
16335 sep 12 9 --> 2009-09-12
16336 12:45 --> today 12:45
16337 22 sept 0:34 --> currentyear-09-22 0:34
16338 12 --> currentyear-currentmonth-12
16339 Fri --> nearest Friday after today
16340 -Tue --> last Tuesday
16341 etc.
16343 Furthermore you can specify a relative date by giving, as the *first* thing
16344 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16345 change in days weeks, months, years.
16346 With a single plus or minus, the date is relative to today. With a double
16347 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16348 +4d --> four days from today
16349 +4 --> same as above
16350 +2w --> two weeks from today
16351 ++5 --> five days from default date
16353 The function understands only English month and weekday abbreviations.
16355 While prompting, a calendar is popped up - you can also select the
16356 date with the mouse (button 1). The calendar shows a period of three
16357 months. To scroll it to other months, use the keys `>' and `<'.
16358 If you don't like the calendar, turn it off with
16359 (setq org-read-date-popup-calendar nil)
16361 With optional argument TO-TIME, the date will immediately be converted
16362 to an internal time.
16363 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16364 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16365 still enter a time, and this function will inform the calling routine
16366 about this change. The calling routine may then choose to change the
16367 format used to insert the time stamp into the buffer to include the time.
16368 With optional argument FROM-STRING, read from this string instead from
16369 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16370 the time/date that is used for everything that is not specified by the
16371 user."
16372 (require 'parse-time)
16373 (let* ((org-time-stamp-rounding-minutes
16374 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16375 (org-dcst org-display-custom-times)
16376 (ct (org-current-time))
16377 (org-def (or org-overriding-default-time default-time ct))
16378 (org-defdecode (decode-time org-def))
16379 (dummy (progn
16380 (when (< (nth 2 org-defdecode) org-extend-today-until)
16381 (setcar (nthcdr 2 org-defdecode) -1)
16382 (setcar (nthcdr 1 org-defdecode) 59)
16383 (setq org-def (apply 'encode-time org-defdecode)
16384 org-defdecode (decode-time org-def)))))
16385 (mouse-autoselect-window nil) ; Don't let the mouse jump
16386 (calendar-frame-setup nil)
16387 (calendar-setup nil)
16388 (calendar-move-hook nil)
16389 (calendar-view-diary-initially-flag nil)
16390 (calendar-view-holidays-initially-flag nil)
16391 (timestr (format-time-string
16392 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16393 (prompt (concat (if prompt (concat prompt " ") "")
16394 (format "Date+time [%s]: " timestr)))
16395 ans (org-ans0 "") org-ans1 org-ans2 final)
16397 (cond
16398 (from-string (setq ans from-string))
16399 (org-read-date-popup-calendar
16400 (save-excursion
16401 (save-window-excursion
16402 (calendar)
16403 (org-eval-in-calendar '(setq cursor-type nil) t)
16404 (unwind-protect
16405 (progn
16406 (calendar-forward-day (- (time-to-days org-def)
16407 (calendar-absolute-from-gregorian
16408 (calendar-current-date))))
16409 (org-eval-in-calendar nil t)
16410 (let* ((old-map (current-local-map))
16411 (map (copy-keymap calendar-mode-map))
16412 (minibuffer-local-map
16413 (copy-keymap org-read-date-minibuffer-local-map)))
16414 (org-defkey map (kbd "RET") 'org-calendar-select)
16415 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16416 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16417 (unwind-protect
16418 (progn
16419 (use-local-map map)
16420 (setq org-read-date-inactive inactive)
16421 (add-hook 'post-command-hook 'org-read-date-display)
16422 (setq org-ans0 (read-string prompt default-input
16423 'org-read-date-history nil))
16424 ;; org-ans0: from prompt
16425 ;; org-ans1: from mouse click
16426 ;; org-ans2: from calendar motion
16427 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16428 (remove-hook 'post-command-hook 'org-read-date-display)
16429 (use-local-map old-map)
16430 (when org-read-date-overlay
16431 (delete-overlay org-read-date-overlay)
16432 (setq org-read-date-overlay nil)))))
16433 (bury-buffer "*Calendar*")))))
16435 (t ; Naked prompt only
16436 (unwind-protect
16437 (setq ans (read-string prompt default-input
16438 'org-read-date-history timestr))
16439 (when org-read-date-overlay
16440 (delete-overlay org-read-date-overlay)
16441 (setq org-read-date-overlay nil)))))
16443 (setq final (org-read-date-analyze ans org-def org-defdecode))
16445 (when org-read-date-analyze-forced-year
16446 (message "Year was forced into %s"
16447 (if org-read-date-force-compatible-dates
16448 "compatible range (1970-2037)"
16449 "range representable on this machine"))
16450 (ding))
16452 ;; One round trip to get rid of 34th of August and stuff like that....
16453 (setq final (decode-time (apply 'encode-time final)))
16455 (setq org-read-date-final-answer ans)
16457 (if to-time
16458 (apply 'encode-time final)
16459 (if (and (boundp 'org-time-was-given) org-time-was-given)
16460 (format "%04d-%02d-%02d %02d:%02d"
16461 (nth 5 final) (nth 4 final) (nth 3 final)
16462 (nth 2 final) (nth 1 final))
16463 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16465 (defun org-read-date-display ()
16466 "Display the current date prompt interpretation in the minibuffer."
16467 (when org-read-date-display-live
16468 (when org-read-date-overlay
16469 (delete-overlay org-read-date-overlay))
16470 (when (minibufferp (current-buffer))
16471 (save-excursion
16472 (end-of-line 1)
16473 (while (not (equal (buffer-substring
16474 (max (point-min) (- (point) 4)) (point))
16475 " "))
16476 (insert " ")))
16477 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16478 " " (or org-ans1 org-ans2)))
16479 (org-end-time-was-given nil)
16480 (f (org-read-date-analyze ans org-def org-defdecode))
16481 (fmts (if org-dcst
16482 org-time-stamp-custom-formats
16483 org-time-stamp-formats))
16484 (fmt (if (or org-with-time
16485 (and (boundp 'org-time-was-given) org-time-was-given))
16486 (cdr fmts)
16487 (car fmts)))
16488 (txt (format-time-string fmt (apply 'encode-time f)))
16489 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16490 (txt (concat "=> " txt)))
16491 (when (and org-end-time-was-given
16492 (string-match org-plain-time-of-day-regexp txt))
16493 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16494 org-end-time-was-given
16495 (substring txt (match-end 0)))))
16496 (when org-read-date-analyze-futurep
16497 (setq txt (concat txt " (=>F)")))
16498 (setq org-read-date-overlay
16499 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16500 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16502 (defun org-read-date-analyze (ans org-def org-defdecode)
16503 "Analyze the combined answer of the date prompt."
16504 ;; FIXME: cleanup and comment
16505 (let ((nowdecode (decode-time))
16506 delta deltan deltaw deltadef year month day
16507 hour minute second wday pm h2 m2 tl wday1
16508 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16509 (setq org-read-date-analyze-futurep nil
16510 org-read-date-analyze-forced-year nil)
16511 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16512 (setq ans "+0"))
16514 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16515 (setq ans (replace-match "" t t ans)
16516 deltan (car delta)
16517 deltaw (nth 1 delta)
16518 deltadef (nth 2 delta)))
16520 ;; Check if there is an iso week date in there. If yes, store the
16521 ;; info and postpone interpreting it until the rest of the parsing
16522 ;; is done.
16523 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16524 (setq iso-year (if (match-end 1)
16525 (org-small-year-to-year
16526 (string-to-number (match-string 1 ans))))
16527 iso-weekday (if (match-end 3)
16528 (string-to-number (match-string 3 ans)))
16529 iso-week (string-to-number (match-string 2 ans)))
16530 (setq ans (replace-match "" t t ans)))
16532 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16533 (when (string-match
16534 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16535 (setq year (if (match-end 2)
16536 (string-to-number (match-string 2 ans))
16537 (progn (setq kill-year t)
16538 (string-to-number (format-time-string "%Y"))))
16539 month (string-to-number (match-string 3 ans))
16540 day (string-to-number (match-string 4 ans)))
16541 (if (< year 100) (setq year (+ 2000 year)))
16542 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16543 t nil ans)))
16545 ;; Help matching dotted european dates
16546 (when (string-match
16547 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16548 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16549 (setq kill-year t)
16550 (string-to-number (format-time-string "%Y")))
16551 day (string-to-number (match-string 1 ans))
16552 month (string-to-number (match-string 2 ans))
16553 ans (replace-match (format "%04d-%02d-%02d" year month day)
16554 t nil ans)))
16556 ;; Help matching american dates, like 5/30 or 5/30/7
16557 (when (string-match
16558 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16559 (setq year (if (match-end 4)
16560 (string-to-number (match-string 4 ans))
16561 (progn (setq kill-year t)
16562 (string-to-number (format-time-string "%Y"))))
16563 month (string-to-number (match-string 1 ans))
16564 day (string-to-number (match-string 2 ans)))
16565 (if (< year 100) (setq year (+ 2000 year)))
16566 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16567 t nil ans)))
16568 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16569 ;; If there is a time with am/pm, and *no* time without it, we convert
16570 ;; so that matching will be successful.
16571 (loop for i from 1 to 2 do ; twice, for end time as well
16572 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16573 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16574 (setq hour (string-to-number (match-string 1 ans))
16575 minute (if (match-end 3)
16576 (string-to-number (match-string 3 ans))
16578 pm (equal ?p
16579 (string-to-char (downcase (match-string 4 ans)))))
16580 (if (and (= hour 12) (not pm))
16581 (setq hour 0)
16582 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16583 (setq ans (replace-match (format "%02d:%02d" hour minute)
16584 t t ans))))
16586 ;; Check if a time range is given as a duration
16587 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16588 (setq hour (string-to-number (match-string 1 ans))
16589 h2 (+ hour (string-to-number (match-string 3 ans)))
16590 minute (string-to-number (match-string 2 ans))
16591 m2 (+ minute (if (match-end 5) (string-to-number
16592 (match-string 5 ans))0)))
16593 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16594 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16595 t t ans)))
16597 ;; Check if there is a time range
16598 (when (boundp 'org-end-time-was-given)
16599 (setq org-time-was-given nil)
16600 (when (and (string-match org-plain-time-of-day-regexp ans)
16601 (match-end 8))
16602 (setq org-end-time-was-given (match-string 8 ans))
16603 (setq ans (concat (substring ans 0 (match-beginning 7))
16604 (substring ans (match-end 7))))))
16606 (setq tl (parse-time-string ans)
16607 day (or (nth 3 tl) (nth 3 org-defdecode))
16608 month (or (nth 4 tl)
16609 (if (and org-read-date-prefer-future
16610 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16611 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16612 (nth 4 org-defdecode)))
16613 year (or (and (not kill-year) (nth 5 tl))
16614 (if (and org-read-date-prefer-future
16615 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16616 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16617 (nth 5 org-defdecode)))
16618 hour (or (nth 2 tl) (nth 2 org-defdecode))
16619 minute (or (nth 1 tl) (nth 1 org-defdecode))
16620 second (or (nth 0 tl) 0)
16621 wday (nth 6 tl))
16623 (when (and (eq org-read-date-prefer-future 'time)
16624 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16625 (equal day (nth 3 nowdecode))
16626 (equal month (nth 4 nowdecode))
16627 (equal year (nth 5 nowdecode))
16628 (nth 2 tl)
16629 (or (< (nth 2 tl) (nth 2 nowdecode))
16630 (and (= (nth 2 tl) (nth 2 nowdecode))
16631 (nth 1 tl)
16632 (< (nth 1 tl) (nth 1 nowdecode)))))
16633 (setq day (1+ day)
16634 futurep t))
16636 ;; Special date definitions below
16637 (cond
16638 (iso-week
16639 ;; There was an iso week
16640 (require 'cal-iso)
16641 (setq futurep nil)
16642 (setq year (or iso-year year)
16643 day (or iso-weekday wday 1)
16644 wday nil ; to make sure that the trigger below does not match
16645 iso-date (calendar-gregorian-from-absolute
16646 (calendar-absolute-from-iso
16647 (list iso-week day year))))
16648 ; FIXME: Should we also push ISO weeks into the future?
16649 ; (when (and org-read-date-prefer-future
16650 ; (not iso-year)
16651 ; (< (calendar-absolute-from-gregorian iso-date)
16652 ; (time-to-days (current-time))))
16653 ; (setq year (1+ year)
16654 ; iso-date (calendar-gregorian-from-absolute
16655 ; (calendar-absolute-from-iso
16656 ; (list iso-week day year)))))
16657 (setq month (car iso-date)
16658 year (nth 2 iso-date)
16659 day (nth 1 iso-date)))
16660 (deltan
16661 (setq futurep nil)
16662 (unless deltadef
16663 (let ((now (decode-time)))
16664 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16665 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16666 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16667 ((equal deltaw "m") (setq month (+ month deltan)))
16668 ((equal deltaw "y") (setq year (+ year deltan)))))
16669 ((and wday (not (nth 3 tl)))
16670 ;; Weekday was given, but no day, so pick that day in the week
16671 ;; on or after the derived date.
16672 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16673 (unless (equal wday wday1)
16674 (setq day (+ day (% (- wday wday1 -7) 7))))))
16675 (if (and (boundp 'org-time-was-given)
16676 (nth 2 tl))
16677 (setq org-time-was-given t))
16678 (if (< year 100) (setq year (+ 2000 year)))
16679 ;; Check of the date is representable
16680 (if org-read-date-force-compatible-dates
16681 (progn
16682 (if (< year 1970)
16683 (setq year 1970 org-read-date-analyze-forced-year t))
16684 (if (> year 2037)
16685 (setq year 2037 org-read-date-analyze-forced-year t)))
16686 (condition-case nil
16687 (ignore (encode-time second minute hour day month year))
16688 (error
16689 (setq year (nth 5 org-defdecode))
16690 (setq org-read-date-analyze-forced-year t))))
16691 (setq org-read-date-analyze-futurep futurep)
16692 (list second minute hour day month year)))
16694 (defvar parse-time-weekdays)
16695 (defun org-read-date-get-relative (s today default)
16696 "Check string S for special relative date string.
16697 TODAY and DEFAULT are internal times, for today and for a default.
16698 Return shift list (N what def-flag)
16699 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16700 N is the number of WHATs to shift.
16701 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16702 the DEFAULT date rather than TODAY."
16703 (require 'parse-time)
16704 (when (and
16705 (string-match
16706 (concat
16707 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16708 "\\([0-9]+\\)?"
16709 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16710 "\\([ \t]\\|$\\)") s)
16711 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16712 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16713 (string-to-char (substring (match-string 1 s) -1))
16714 ?+))
16715 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16716 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16717 (what (if (match-end 3) (match-string 3 s) "d"))
16718 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16719 (date (if rel default today))
16720 (wday (nth 6 (decode-time date)))
16721 delta)
16722 (if wday1
16723 (progn
16724 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16725 (if (= delta 0) (setq delta 7))
16726 (if (= dir ?-)
16727 (progn
16728 (setq delta (- delta 7))
16729 (if (= delta 0) (setq delta -7))))
16730 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16731 (list delta "d" rel))
16732 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16734 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16735 "Turn a user-specified date into the internal representation.
16736 The internal representation needed by the calendar is (month day year).
16737 This is a wrapper to handle the brain-dead convention in calendar that
16738 user function argument order change dependent on argument order."
16739 (if (boundp 'calendar-date-style)
16740 (cond
16741 ((eq calendar-date-style 'american)
16742 (list arg1 arg2 arg3))
16743 ((eq calendar-date-style 'european)
16744 (list arg2 arg1 arg3))
16745 ((eq calendar-date-style 'iso)
16746 (list arg2 arg3 arg1)))
16747 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16748 (if (org-bound-and-true-p european-calendar-style)
16749 (list arg2 arg1 arg3)
16750 (list arg1 arg2 arg3)))))
16752 (defun org-eval-in-calendar (form &optional keepdate)
16753 "Eval FORM in the calendar window and return to current window.
16754 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16755 otherwise stick to the current value of `org-ans2'."
16756 (let ((sf (selected-frame))
16757 (sw (selected-window)))
16758 (select-window (get-buffer-window "*Calendar*" t))
16759 (eval form)
16760 (when (and (not keepdate) (calendar-cursor-to-date))
16761 (let* ((date (calendar-cursor-to-date))
16762 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16763 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16764 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16765 (select-window sw)
16766 (org-select-frame-set-input-focus sf)))
16768 (defun org-calendar-select ()
16769 "Return to `org-read-date' with the date currently selected.
16770 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16771 (interactive)
16772 (when (calendar-cursor-to-date)
16773 (let* ((date (calendar-cursor-to-date))
16774 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16775 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16776 (if (active-minibuffer-window) (exit-minibuffer))))
16778 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16779 "Insert a date stamp for the date given by the internal TIME.
16780 WITH-HM means use the stamp format that includes the time of the day.
16781 INACTIVE means use square brackets instead of angular ones, so that the
16782 stamp will not contribute to the agenda.
16783 PRE and POST are optional strings to be inserted before and after the
16784 stamp.
16785 The command returns the inserted time stamp."
16786 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16787 stamp)
16788 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16789 (insert-before-markers (or pre ""))
16790 (when (listp extra)
16791 (setq extra (car extra))
16792 (if (and (stringp extra)
16793 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16794 (setq extra (format "-%02d:%02d"
16795 (string-to-number (match-string 1 extra))
16796 (string-to-number (match-string 2 extra))))
16797 (setq extra nil)))
16798 (when extra
16799 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16800 (insert-before-markers (setq stamp (format-time-string fmt time)))
16801 (insert-before-markers (or post ""))
16802 (setq org-last-inserted-timestamp stamp)))
16804 (defun org-toggle-time-stamp-overlays ()
16805 "Toggle the use of custom time stamp formats."
16806 (interactive)
16807 (setq org-display-custom-times (not org-display-custom-times))
16808 (unless org-display-custom-times
16809 (let ((p (point-min)) (bmp (buffer-modified-p)))
16810 (while (setq p (next-single-property-change p 'display))
16811 (if (and (get-text-property p 'display)
16812 (eq (get-text-property p 'face) 'org-date))
16813 (remove-text-properties
16814 p (setq p (next-single-property-change p 'display))
16815 '(display t))))
16816 (set-buffer-modified-p bmp)))
16817 (if (featurep 'xemacs)
16818 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16819 (org-restart-font-lock)
16820 (setq org-table-may-need-update t)
16821 (if org-display-custom-times
16822 (message "Time stamps are overlaid with custom format")
16823 (message "Time stamp overlays removed")))
16825 (defun org-display-custom-time (beg end)
16826 "Overlay modified time stamp format over timestamp between BEG and END."
16827 (let* ((ts (buffer-substring beg end))
16828 t1 w1 with-hm tf time str w2 (off 0))
16829 (save-match-data
16830 (setq t1 (org-parse-time-string ts t))
16831 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16832 (setq off (- (match-end 0) (match-beginning 0)))))
16833 (setq end (- end off))
16834 (setq w1 (- end beg)
16835 with-hm (and (nth 1 t1) (nth 2 t1))
16836 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16837 time (org-fix-decoded-time t1)
16838 str (org-add-props
16839 (format-time-string
16840 (substring tf 1 -1) (apply 'encode-time time))
16841 nil 'mouse-face 'highlight)
16842 w2 (length str))
16843 (if (not (= w2 w1))
16844 (add-text-properties (1+ beg) (+ 2 beg)
16845 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16846 (if (featurep 'xemacs)
16847 (progn
16848 (put-text-property beg end 'invisible t)
16849 (put-text-property beg end 'end-glyph (make-glyph str)))
16850 (put-text-property beg end 'display str))))
16852 (defun org-translate-time (string)
16853 "Translate all timestamps in STRING to custom format.
16854 But do this only if the variable `org-display-custom-times' is set."
16855 (when org-display-custom-times
16856 (save-match-data
16857 (let* ((start 0)
16858 (re org-ts-regexp-both)
16859 t1 with-hm inactive tf time str beg end)
16860 (while (setq start (string-match re string start))
16861 (setq beg (match-beginning 0)
16862 end (match-end 0)
16863 t1 (save-match-data
16864 (org-parse-time-string (substring string beg end) t))
16865 with-hm (and (nth 1 t1) (nth 2 t1))
16866 inactive (equal (substring string beg (1+ beg)) "[")
16867 tf (funcall (if with-hm 'cdr 'car)
16868 org-time-stamp-custom-formats)
16869 time (org-fix-decoded-time t1)
16870 str (format-time-string
16871 (concat
16872 (if inactive "[" "<") (substring tf 1 -1)
16873 (if inactive "]" ">"))
16874 (apply 'encode-time time))
16875 string (replace-match str t t string)
16876 start (+ start (length str)))))))
16877 string)
16879 (defun org-fix-decoded-time (time)
16880 "Set 0 instead of nil for the first 6 elements of time.
16881 Don't touch the rest."
16882 (let ((n 0))
16883 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16885 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16887 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16888 "Difference between TIMESTAMP-STRING and now in days.
16889 If SECONDS is non-nil, return the difference in seconds."
16890 (let ((fdiff (if seconds 'float-time 'time-to-days)))
16891 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16892 (funcall fdiff (current-time)))))
16894 (defun org-deadline-close (timestamp-string &optional ndays)
16895 "Is the time in TIMESTAMP-STRING close to the current date?"
16896 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16897 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16898 (not (org-entry-is-done-p))))
16900 (defun org-get-wdays (ts &optional delay zero-delay)
16901 "Get the deadline lead time appropriate for timestring TS.
16902 When DELAY is non-nil, get the delay time for scheduled items
16903 instead of the deadline lead time. When ZERO-DELAY is non-nil
16904 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16905 don't try to find the delay cookie in the scheduled timestamp."
16906 (let ((tv (if delay org-scheduled-delay-days
16907 org-deadline-warning-days)))
16908 (cond
16909 ((or (and delay (< tv 0))
16910 (and delay zero-delay (<= tv 0))
16911 (and (not delay) (<= tv 0)))
16912 ;; Enforce this value no matter what
16913 (- tv))
16914 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16915 ;; lead time is specified.
16916 (floor (* (string-to-number (match-string 1 ts))
16917 (cdr (assoc (match-string 2 ts)
16918 '(("d" . 1) ("w" . 7)
16919 ("m" . 30.4) ("y" . 365.25)
16920 ("h" . 0.041667)))))))
16921 ;; go for the default.
16922 (t tv))))
16924 (defun org-calendar-select-mouse (ev)
16925 "Return to `org-read-date' with the date currently selected.
16926 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16927 (interactive "e")
16928 (mouse-set-point ev)
16929 (when (calendar-cursor-to-date)
16930 (let* ((date (calendar-cursor-to-date))
16931 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16932 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16933 (if (active-minibuffer-window) (exit-minibuffer))))
16935 (defun org-check-deadlines (ndays)
16936 "Check if there are any deadlines due or past due.
16937 A deadline is considered due if it happens within `org-deadline-warning-days'
16938 days from today's date. If the deadline appears in an entry marked DONE,
16939 it is not shown. The prefix arg NDAYS can be used to test that many
16940 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16941 (interactive "P")
16942 (let* ((org-warn-days
16943 (cond
16944 ((equal ndays '(4)) 100000)
16945 (ndays (prefix-numeric-value ndays))
16946 (t (abs org-deadline-warning-days))))
16947 (case-fold-search nil)
16948 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16949 (callback
16950 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16952 (message "%d deadlines past-due or due within %d days"
16953 (org-occur regexp nil callback)
16954 org-warn-days)))
16956 (defsubst org-re-timestamp (type)
16957 "Return a regexp for timestamp TYPE.
16958 Allowed values for TYPE are:
16960 all: all timestamps
16961 active: only active timestamps (<...>)
16962 inactive: only inactive timestamps ([...])
16963 scheduled: only scheduled timestamps
16964 deadline: only deadline timestamps
16965 closed: only closed time-stamps
16967 When TYPE is nil, fall back on returning a regexp that matches
16968 both scheduled and deadline timestamps."
16969 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9>\r\n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16970 ((eq type 'active) org-ts-regexp)
16971 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]")
16972 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16973 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16974 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"))
16975 ((eq type 'scheduled-or-deadline)
16976 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16978 (defun org-check-before-date (date)
16979 "Check if there are deadlines or scheduled entries before DATE."
16980 (interactive (list (org-read-date)))
16981 (let ((case-fold-search nil)
16982 (regexp (org-re-timestamp org-ts-type))
16983 (callback
16984 (lambda () (time-less-p
16985 (org-time-string-to-time (match-string 1))
16986 (org-time-string-to-time date)))))
16987 (message "%d entries before %s"
16988 (org-occur regexp nil callback) date)))
16990 (defun org-check-after-date (date)
16991 "Check if there are deadlines or scheduled entries after DATE."
16992 (interactive (list (org-read-date)))
16993 (let ((case-fold-search nil)
16994 (regexp (org-re-timestamp org-ts-type))
16995 (callback
16996 (lambda () (not
16997 (time-less-p
16998 (org-time-string-to-time (match-string 1))
16999 (org-time-string-to-time date))))))
17000 (message "%d entries after %s"
17001 (org-occur regexp nil callback) date)))
17003 (defun org-check-dates-range (start-date end-date)
17004 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17005 (interactive (list (org-read-date nil nil nil "Range starts")
17006 (org-read-date nil nil nil "Range end")))
17007 (let ((case-fold-search nil)
17008 (regexp (org-re-timestamp org-ts-type))
17009 (callback
17010 (lambda ()
17011 (let ((match (match-string 1)))
17012 (and
17013 (not (time-less-p
17014 (org-time-string-to-time match)
17015 (org-time-string-to-time start-date)))
17016 (time-less-p
17017 (org-time-string-to-time match)
17018 (org-time-string-to-time end-date)))))))
17019 (message "%d entries between %s and %s"
17020 (org-occur regexp nil callback) start-date end-date)))
17022 (defun org-evaluate-time-range (&optional to-buffer)
17023 "Evaluate a time range by computing the difference between start and end.
17024 Normally the result is just printed in the echo area, but with prefix arg
17025 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17026 If the time range is actually in a table, the result is inserted into the
17027 next column.
17028 For time difference computation, a year is assumed to be exactly 365
17029 days in order to avoid rounding problems."
17030 (interactive "P")
17032 (org-clock-update-time-maybe)
17033 (save-excursion
17034 (unless (org-at-date-range-p t)
17035 (goto-char (point-at-bol))
17036 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17037 (if (not (org-at-date-range-p t))
17038 (user-error "Not at a time-stamp range, and none found in current line")))
17039 (let* ((ts1 (match-string 1))
17040 (ts2 (match-string 2))
17041 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17042 (match-end (match-end 0))
17043 (time1 (org-time-string-to-time ts1))
17044 (time2 (org-time-string-to-time ts2))
17045 (t1 (float-time time1))
17046 (t2 (float-time time2))
17047 (diff (abs (- t2 t1)))
17048 (negative (< (- t2 t1) 0))
17049 ;; (ys (floor (* 365 24 60 60)))
17050 (ds (* 24 60 60))
17051 (hs (* 60 60))
17052 (fy "%dy %dd %02d:%02d")
17053 (fy1 "%dy %dd")
17054 (fd "%dd %02d:%02d")
17055 (fd1 "%dd")
17056 (fh "%02d:%02d")
17057 y d h m align)
17058 (if havetime
17059 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17061 d (floor (/ diff ds)) diff (mod diff ds)
17062 h (floor (/ diff hs)) diff (mod diff hs)
17063 m (floor (/ diff 60)))
17064 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17066 d (floor (+ (/ diff ds) 0.5))
17067 h 0 m 0))
17068 (if (not to-buffer)
17069 (message "%s" (org-make-tdiff-string y d h m))
17070 (if (org-at-table-p)
17071 (progn
17072 (goto-char match-end)
17073 (setq align t)
17074 (and (looking-at " *|") (goto-char (match-end 0))))
17075 (goto-char match-end))
17076 (if (looking-at
17077 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17078 (replace-match ""))
17079 (if negative (insert " -"))
17080 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17081 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17082 (insert " " (format fh h m))))
17083 (if align (org-table-align))
17084 (message "Time difference inserted")))))
17086 (defun org-make-tdiff-string (y d h m)
17087 (let ((fmt "")
17088 (l nil))
17089 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17090 l (push y l)))
17091 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17092 l (push d l)))
17093 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17094 l (push h l)))
17095 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17096 l (push m l)))
17097 (apply 'format fmt (nreverse l))))
17099 (defun org-time-string-to-time (s &optional buffer pos)
17100 "Convert a timestamp string into internal time."
17101 (condition-case errdata
17102 (apply 'encode-time (org-parse-time-string s))
17103 (error (error "Bad timestamp `%s'%s\nError was: %s"
17104 s (if (not (and buffer pos))
17106 (format-message " at %d in buffer `%s'" pos buffer))
17107 (cdr errdata)))))
17109 (defun org-time-string-to-seconds (s)
17110 "Convert a timestamp string to a number of seconds."
17111 (float-time (org-time-string-to-time s)))
17113 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17114 "Convert a time stamp to an absolute day number.
17115 If there is a specifier for a cyclic time stamp, get the closest
17116 date to DAYNR.
17117 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17118 The variable `date' is bound by the calendar when this is called."
17119 (cond
17120 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17121 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17122 daynr
17123 (+ daynr 1000)))
17124 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17125 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17126 (time-to-days (current-time))) (match-string 0 s)
17127 prefer show-all))
17128 (t (time-to-days
17129 (condition-case errdata
17130 (apply 'encode-time (org-parse-time-string s))
17131 (error (error "Bad timestamp `%s'%s\nError was: %s"
17132 s (if (not (and buffer pos))
17134 (format-message " at %d in buffer `%s'" pos buffer))
17135 (cdr errdata))))))))
17137 (defun org-days-to-iso-week (days)
17138 "Return the iso week number."
17139 (require 'cal-iso)
17140 (car (calendar-iso-from-absolute days)))
17142 (defun org-small-year-to-year (year)
17143 "Convert 2-digit years into 4-digit years.
17144 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17145 The year 2000 cannot be abbreviated. Any year larger than 99
17146 is returned unchanged."
17147 (if (< year 38)
17148 (setq year (+ 2000 year))
17149 (if (< year 100)
17150 (setq year (+ 1900 year))))
17151 year)
17153 (defun org-time-from-absolute (d)
17154 "Return the time corresponding to date D.
17155 D may be an absolute day number, or a calendar-type list (month day year)."
17156 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17157 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17159 (defun org-calendar-holiday ()
17160 "List of holidays, for Diary display in Org-mode."
17161 (require 'holidays)
17162 (let ((hl (funcall
17163 (if (fboundp 'calendar-check-holidays)
17164 'calendar-check-holidays 'check-calendar-holidays) date)))
17165 (if hl (mapconcat 'identity hl "; "))))
17167 (defun org-diary-sexp-entry (sexp entry date)
17168 "Process a SEXP diary ENTRY for DATE."
17169 (require 'diary-lib)
17170 (let ((result (if calendar-debug-sexp
17171 (let ((stack-trace-on-error t))
17172 (eval (car (read-from-string sexp))))
17173 (condition-case nil
17174 (eval (car (read-from-string sexp)))
17175 (error
17176 (beep)
17177 (message "Bad sexp at line %d in %s: %s"
17178 (org-current-line)
17179 (buffer-file-name) sexp)
17180 (sleep-for 2))))))
17181 (cond ((stringp result) (split-string result "; "))
17182 ((and (consp result)
17183 (not (consp (cdr result)))
17184 (stringp (cdr result))) (cdr result))
17185 ((and (consp result)
17186 (stringp (car result))) result)
17187 (result entry))))
17189 (defun org-diary-to-ical-string (frombuf)
17190 "Get iCalendar entries from diary entries in buffer FROMBUF.
17191 This uses the icalendar.el library."
17192 (let* ((tmpdir (if (featurep 'xemacs)
17193 (temp-directory)
17194 temporary-file-directory))
17195 (tmpfile (make-temp-name
17196 (expand-file-name "orgics" tmpdir)))
17197 buf rtn b e)
17198 (with-current-buffer frombuf
17199 (icalendar-export-region (point-min) (point-max) tmpfile)
17200 (setq buf (find-buffer-visiting tmpfile))
17201 (set-buffer buf)
17202 (goto-char (point-min))
17203 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17204 (setq b (match-beginning 0)))
17205 (goto-char (point-max))
17206 (if (re-search-backward "^END:VEVENT" nil t)
17207 (setq e (match-end 0)))
17208 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17209 (kill-buffer buf)
17210 (delete-file tmpfile)
17211 rtn))
17213 (defun org-closest-date (start current change prefer show-all)
17214 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17215 When PREFER is `past', return a date that is either CURRENT or past.
17216 When PREFER is `future', return a date that is either CURRENT or future.
17217 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17218 ;; Make the proper lists from the dates
17219 (catch 'exit
17220 (let ((a1 '(("h" . hour)
17221 ("d" . day)
17222 ("w" . week)
17223 ("m" . month)
17224 ("y" . year)))
17225 (shour (nth 2 (org-parse-time-string start)))
17226 dn dw sday cday n1 n2 n0
17227 d m y y1 y2 date1 date2 nmonths nm ny m2)
17229 (setq start (org-date-to-gregorian start)
17230 current (org-date-to-gregorian
17231 (if show-all
17232 current
17233 (time-to-days (current-time))))
17234 sday (calendar-absolute-from-gregorian start)
17235 cday (calendar-absolute-from-gregorian current))
17237 (if (<= cday sday) (throw 'exit sday))
17239 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17240 (setq dn (string-to-number (match-string 1 change))
17241 dw (cdr (assoc (match-string 2 change) a1)))
17242 (user-error "Invalid change specifier: %s" change))
17243 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17244 (cond
17245 ((eq dw 'hour)
17246 (let ((missing-hours
17247 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17248 dn)))
17249 (setq n1 (if (zerop missing-hours) cday
17250 (- cday (1+ (floor (/ missing-hours 24)))))
17251 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17252 ((eq dw 'day)
17253 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17254 n2 (+ n1 dn)))
17255 ((eq dw 'year)
17256 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17257 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17258 (setq date1 (list m d y1)
17259 n1 (calendar-absolute-from-gregorian date1)
17260 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17261 n2 (calendar-absolute-from-gregorian date2)))
17262 ((eq dw 'month)
17263 ;; approx number of month between the two dates
17264 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17265 ;; How often does dn fit in there?
17266 (setq d (nth 1 start) m (car start) y (nth 2 start)
17267 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17268 m (+ m nm)
17269 ny (floor (/ m 12))
17270 y (+ y ny)
17271 m (- m (* ny 12)))
17272 (while (> m 12) (setq m (- m 12) y (1+ y)))
17273 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17274 (setq m2 (+ m dn) y2 y)
17275 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17276 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17277 (while (<= n2 cday)
17278 (setq n1 n2 m m2 y y2)
17279 (setq m2 (+ m dn) y2 y)
17280 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17281 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17282 ;; Make sure n1 is the earlier date
17283 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17284 (if show-all
17285 (cond
17286 ((eq prefer 'past) (if (= cday n2) n2 n1))
17287 ((eq prefer 'future) (if (= cday n1) n1 n2))
17288 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17289 (cond
17290 ((eq prefer 'past) (if (= cday n2) n2 n1))
17291 ((eq prefer 'future) (if (= cday n1) n1 n2))
17292 (t (if (= cday n1) n1 n2)))))))
17294 (defun org-date-to-gregorian (date)
17295 "Turn any specification of DATE into a Gregorian date for the calendar."
17296 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17297 ((and (listp date) (= (length date) 3)) date)
17298 ((stringp date)
17299 (setq date (org-parse-time-string date))
17300 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17301 ((listp date)
17302 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17304 (defun org-parse-time-string (s &optional nodefault)
17305 "Parse the standard Org-mode time string.
17306 This should be a lot faster than the normal `parse-time-string'.
17307 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17308 hour and minute fields will be nil if not given."
17309 (cond ((string-match org-ts-regexp0 s)
17310 (list 0
17311 (if (or (match-beginning 8) (not nodefault))
17312 (string-to-number (or (match-string 8 s) "0")))
17313 (if (or (match-beginning 7) (not nodefault))
17314 (string-to-number (or (match-string 7 s) "0")))
17315 (string-to-number (match-string 4 s))
17316 (string-to-number (match-string 3 s))
17317 (string-to-number (match-string 2 s))
17318 nil nil nil))
17319 ((string-match "^<[^>]+>$" s)
17320 (decode-time (seconds-to-time (org-matcher-time s))))
17321 (t (error "Not a standard Org-mode time string: %s" s))))
17323 (defun org-timestamp-up (&optional arg)
17324 "Increase the date item at the cursor by one.
17325 If the cursor is on the year, change the year. If it is on the month,
17326 the day or the time, change that.
17327 With prefix ARG, change by that many units."
17328 (interactive "p")
17329 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17331 (defun org-timestamp-down (&optional arg)
17332 "Decrease the date item at the cursor by one.
17333 If the cursor is on the year, change the year. If it is on the month,
17334 the day or the time, change that.
17335 With prefix ARG, change by that many units."
17336 (interactive "p")
17337 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17339 (defun org-timestamp-up-day (&optional arg)
17340 "Increase the date in the time stamp by one day.
17341 With prefix ARG, change that many days."
17342 (interactive "p")
17343 (if (and (not (org-at-timestamp-p t))
17344 (org-at-heading-p))
17345 (org-todo 'up)
17346 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17348 (defun org-timestamp-down-day (&optional arg)
17349 "Decrease the date in the time stamp by one day.
17350 With prefix ARG, change that many days."
17351 (interactive "p")
17352 (if (and (not (org-at-timestamp-p t))
17353 (org-at-heading-p))
17354 (org-todo 'down)
17355 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17357 (defun org-at-timestamp-p (&optional inactive-ok)
17358 "Determine if the cursor is in or at a timestamp."
17359 (interactive)
17360 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17361 (pos (point))
17362 (ans (or (looking-at tsr)
17363 (save-excursion
17364 (skip-chars-backward "^[<\n\r\t")
17365 (if (> (point) (point-min)) (backward-char 1))
17366 (and (looking-at tsr)
17367 (> (- (match-end 0) pos) -1))))))
17368 (and ans
17369 (boundp 'org-ts-what)
17370 (setq org-ts-what
17371 (cond
17372 ((= pos (match-beginning 0)) 'bracket)
17373 ;; Point is considered to be "on the bracket" whether
17374 ;; it's really on it or right after it.
17375 ((= pos (1- (match-end 0))) 'bracket)
17376 ((= pos (match-end 0)) 'after)
17377 ((org-pos-in-match-range pos 2) 'year)
17378 ((org-pos-in-match-range pos 3) 'month)
17379 ((org-pos-in-match-range pos 7) 'hour)
17380 ((org-pos-in-match-range pos 8) 'minute)
17381 ((or (org-pos-in-match-range pos 4)
17382 (org-pos-in-match-range pos 5)) 'day)
17383 ((and (> pos (or (match-end 8) (match-end 5)))
17384 (< pos (match-end 0)))
17385 (- pos (or (match-end 8) (match-end 5))))
17386 (t 'day))))
17387 ans))
17389 (defun org-toggle-timestamp-type ()
17390 "Toggle the type (<active> or [inactive]) of a time stamp."
17391 (interactive)
17392 (when (org-at-timestamp-p t)
17393 (let ((beg (match-beginning 0)) (end (match-end 0))
17394 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17395 (save-excursion
17396 (goto-char beg)
17397 (while (re-search-forward "[][<>]" end t)
17398 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17399 t t)))
17400 (message "Timestamp is now %sactive"
17401 (if (equal (char-after beg) ?<) "" "in")))))
17403 (defun org-at-clock-log-p nil
17404 "Is the cursor on the clock log line?"
17405 (save-excursion
17406 (move-beginning-of-line 1)
17407 (looking-at "^[ \t]*CLOCK:")))
17409 (defvar org-clock-history) ; defined in org-clock.el
17410 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17411 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17412 "Change the date in the time stamp at point.
17413 The date will be changed by N times WHAT. WHAT can be `day', `month',
17414 `year', `minute', `second'. If WHAT is not given, the cursor position
17415 in the timestamp determines what will be changed.
17416 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17417 (let ((origin (point)) origin-cat
17418 with-hm inactive
17419 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17420 org-ts-what
17421 extra rem
17422 ts time time0 fixnext clrgx)
17423 (if (not (org-at-timestamp-p t))
17424 (user-error "Not at a timestamp"))
17425 (if (and (not what) (eq org-ts-what 'bracket))
17426 (org-toggle-timestamp-type)
17427 ;; Point isn't on brackets. Remember the part of the time-stamp
17428 ;; the point was in. Indeed, size of time-stamps may change,
17429 ;; but point must be kept in the same category nonetheless.
17430 (setq origin-cat org-ts-what)
17431 (if (and (not what) (not (eq org-ts-what 'day))
17432 org-display-custom-times
17433 (get-text-property (point) 'display)
17434 (not (get-text-property (1- (point)) 'display)))
17435 (setq org-ts-what 'day))
17436 (setq org-ts-what (or what org-ts-what)
17437 inactive (= (char-after (match-beginning 0)) ?\[)
17438 ts (match-string 0))
17439 (replace-match "")
17440 (when (string-match
17441 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17443 (setq extra (match-string 1 ts))
17444 (if suppress-tmp-delay
17445 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17446 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17447 (setq with-hm t))
17448 (setq time0 (org-parse-time-string ts))
17449 (when (and updown
17450 (eq org-ts-what 'minute)
17451 (not current-prefix-arg))
17452 ;; This looks like s-up and s-down. Change by one rounding step.
17453 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17454 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17455 (setcar (cdr time0) (+ (nth 1 time0)
17456 (if (> n 0) (- rem) (- dm rem))))))
17457 (setq time
17458 (encode-time (or (car time0) 0)
17459 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17460 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17461 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17462 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17463 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))))
17464 (when (and (member org-ts-what '(hour minute))
17465 extra
17466 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17467 (setq extra (org-modify-ts-extra
17468 extra
17469 (if (eq org-ts-what 'hour) 2 5)
17470 n dm)))
17471 (when (integerp org-ts-what)
17472 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17473 (if (eq what 'calendar)
17474 (let ((cal-date (org-get-date-from-calendar)))
17475 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17476 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17477 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17478 (setcar time0 (or (car time0) 0))
17479 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17480 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17481 (setq time (apply 'encode-time time0))))
17482 ;; Insert the new time-stamp, and ensure point stays in the same
17483 ;; category as before (i.e. not after the last position in that
17484 ;; category).
17485 (let ((pos (point)))
17486 ;; Stay before inserted string. `save-excursion' is of no use.
17487 (setq org-last-changed-timestamp
17488 (org-insert-time-stamp time with-hm inactive nil nil extra))
17489 (goto-char pos))
17490 (save-match-data
17491 (looking-at org-ts-regexp3)
17492 (goto-char (cond
17493 ;; `day' category ends before `hour' if any, or at
17494 ;; the end of the day name.
17495 ((eq origin-cat 'day)
17496 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17497 ((eq origin-cat 'hour) (min (match-end 7) origin))
17498 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17499 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17500 ;; `year' and `month' have both fixed size: point
17501 ;; couldn't have moved into another part.
17502 (t origin))))
17503 ;; Update clock if on a CLOCK line.
17504 (org-clock-update-time-maybe)
17505 ;; Maybe adjust the closest clock in `org-clock-history'
17506 (when org-clock-adjust-closest
17507 (if (not (and (org-at-clock-log-p)
17508 (< 1 (length (delq nil (mapcar 'marker-position
17509 org-clock-history))))))
17510 (message "No clock to adjust")
17511 (cond ((save-excursion ; fix previous clock?
17512 (re-search-backward org-ts-regexp0 nil t)
17513 (org-looking-back (concat org-clock-string " \\[")))
17514 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17515 ((save-excursion ; fix next clock?
17516 (re-search-backward org-ts-regexp0 nil t)
17517 (looking-at (concat org-ts-regexp0 "\\] =>")))
17518 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17519 (save-window-excursion
17520 ;; Find closest clock to point, adjust the previous/next one in history
17521 (let* ((p (save-excursion (org-back-to-heading t)))
17522 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17523 (clfixnth
17524 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17525 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17526 (if (not clfixpos)
17527 (message "No clock to adjust")
17528 (save-excursion
17529 (org-goto-marker-or-bmk clfixpos)
17530 (org-show-subtree)
17531 (when (re-search-forward clrgx nil t)
17532 (goto-char (match-beginning 1))
17533 (let (org-clock-adjust-closest)
17534 (org-timestamp-change n org-ts-what updown))
17535 (message "Clock adjusted in %s for heading: %s"
17536 (file-name-nondirectory (buffer-file-name))
17537 (org-get-heading t t)))))))))
17538 ;; Try to recenter the calendar window, if any.
17539 (if (and org-calendar-follow-timestamp-change
17540 (get-buffer-window "*Calendar*" t)
17541 (memq org-ts-what '(day month year)))
17542 (org-recenter-calendar (time-to-days time))))))
17544 (defun org-modify-ts-extra (s pos n dm)
17545 "Change the different parts of the lead-time and repeat fields in timestamp."
17546 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17547 ng h m new rem)
17548 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17549 (cond
17550 ((or (org-pos-in-match-range pos 2)
17551 (org-pos-in-match-range pos 3))
17552 (setq m (string-to-number (match-string 3 s))
17553 h (string-to-number (match-string 2 s)))
17554 (if (org-pos-in-match-range pos 2)
17555 (setq h (+ h n))
17556 (setq n (* dm (org-no-warnings (signum n))))
17557 (when (not (= 0 (setq rem (% m dm))))
17558 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17559 (setq m (+ m n)))
17560 (if (< m 0) (setq m (+ m 60) h (1- h)))
17561 (if (> m 59) (setq m (- m 60) h (1+ h)))
17562 (setq h (min 24 (max 0 h)))
17563 (setq ng 1 new (format "-%02d:%02d" h m)))
17564 ((org-pos-in-match-range pos 6)
17565 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17566 ((org-pos-in-match-range pos 5)
17567 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17569 ((org-pos-in-match-range pos 9)
17570 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17571 ((org-pos-in-match-range pos 8)
17572 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17574 (when ng
17575 (setq s (concat
17576 (substring s 0 (match-beginning ng))
17578 (substring s (match-end ng))))))
17581 (defun org-recenter-calendar (date)
17582 "If the calendar is visible, recenter it to DATE."
17583 (let ((cwin (get-buffer-window "*Calendar*" t)))
17584 (when cwin
17585 (let ((calendar-move-hook nil))
17586 (with-selected-window cwin
17587 (calendar-goto-date (if (listp date) date
17588 (calendar-gregorian-from-absolute date))))))))
17590 (defun org-goto-calendar (&optional arg)
17591 "Go to the Emacs calendar at the current date.
17592 If there is a time stamp in the current line, go to that date.
17593 A prefix ARG can be used to force the current date."
17594 (interactive "P")
17595 (let ((tsr org-ts-regexp) diff
17596 (calendar-move-hook nil)
17597 (calendar-view-holidays-initially-flag nil)
17598 (calendar-view-diary-initially-flag nil))
17599 (if (or (org-at-timestamp-p)
17600 (save-excursion
17601 (beginning-of-line 1)
17602 (looking-at (concat ".*" tsr))))
17603 (let ((d1 (time-to-days (current-time)))
17604 (d2 (time-to-days
17605 (org-time-string-to-time (match-string 1)))))
17606 (setq diff (- d2 d1))))
17607 (calendar)
17608 (calendar-goto-today)
17609 (if (and diff (not arg)) (calendar-forward-day diff))))
17611 (defun org-get-date-from-calendar ()
17612 "Return a list (month day year) of date at point in calendar."
17613 (with-current-buffer "*Calendar*"
17614 (save-match-data
17615 (calendar-cursor-to-date))))
17617 (defun org-date-from-calendar ()
17618 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17619 If there is already a time stamp at the cursor position, update it."
17620 (interactive)
17621 (if (org-at-timestamp-p t)
17622 (org-timestamp-change 0 'calendar)
17623 (let ((cal-date (org-get-date-from-calendar)))
17624 (org-insert-time-stamp
17625 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17627 (defcustom org-effort-durations
17628 `(("h" . 60)
17629 ("d" . ,(* 60 8))
17630 ("w" . ,(* 60 8 5))
17631 ("m" . ,(* 60 8 5 4))
17632 ("y" . ,(* 60 8 5 40)))
17633 "Conversion factor to minutes for an effort modifier.
17635 Each entry has the form (MODIFIER . MINUTES).
17637 In an effort string, a number followed by MODIFIER is multiplied
17638 by the specified number of MINUTES to obtain an effort in
17639 minutes.
17641 For example, if the value of this variable is ((\"hours\" . 60)), then an
17642 effort string \"2hours\" is equivalent to 120 minutes."
17643 :group 'org-agenda
17644 :version "24.1"
17645 :type '(alist :key-type (string :tag "Modifier")
17646 :value-type (number :tag "Minutes")))
17648 (defun org-minutes-to-clocksum-string (m)
17649 "Format number of minutes as a clocksum string.
17650 The format is determined by `org-time-clocksum-format',
17651 `org-time-clocksum-use-fractional' and
17652 `org-time-clocksum-fractional-format' and
17653 `org-time-clocksum-use-effort-durations'."
17654 (let ((clocksum "")
17655 (m (round m)) ; Don't allow fractions of minutes
17656 h d w mo y fmt n)
17657 (setq h (if org-time-clocksum-use-effort-durations
17658 (cdr (assoc "h" org-effort-durations)) 60)
17659 d (if org-time-clocksum-use-effort-durations
17660 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17661 w (if org-time-clocksum-use-effort-durations
17662 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17663 mo (if org-time-clocksum-use-effort-durations
17664 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17665 y (if org-time-clocksum-use-effort-durations
17666 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17667 ;; fractional format
17668 (if org-time-clocksum-use-fractional
17669 (cond
17670 ;; single format string
17671 ((stringp org-time-clocksum-fractional-format)
17672 (format org-time-clocksum-fractional-format (/ m (float h))))
17673 ;; choice of fractional formats for different time units
17674 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17675 (> (/ (truncate m) (* y d h)) 0))
17676 (format fmt (/ m (* y d (float h)))))
17677 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17678 (> (/ (truncate m) (* mo d h)) 0))
17679 (format fmt (/ m (* mo d (float h)))))
17680 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17681 (> (/ (truncate m) (* w d h)) 0))
17682 (format fmt (/ m (* w d (float h)))))
17683 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17684 (> (/ (truncate m) (* d h)) 0))
17685 (format fmt (/ m (* d (float h)))))
17686 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17687 (> (/ (truncate m) h) 0))
17688 (format fmt (/ m (float h))))
17689 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17690 (format fmt m))
17691 ;; fall back to smallest time unit with a format
17692 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17693 (format fmt (/ m (float h))))
17694 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17695 (format fmt (/ m (* d (float h)))))
17696 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17697 (format fmt (/ m (* w d (float h)))))
17698 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17699 (format fmt (/ m (* mo d (float h)))))
17700 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17701 (format fmt (/ m (* y d (float h))))))
17702 ;; standard (non-fractional) format, with single format string
17703 (if (stringp org-time-clocksum-format)
17704 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17705 ;; separate formats components
17706 (and (setq fmt (plist-get org-time-clocksum-format :years))
17707 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17708 (plist-get org-time-clocksum-format :require-years))
17709 (setq clocksum (concat clocksum (format fmt n))
17710 m (- m (* n y d h))))
17711 (and (setq fmt (plist-get org-time-clocksum-format :months))
17712 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17713 (plist-get org-time-clocksum-format :require-months))
17714 (setq clocksum (concat clocksum (format fmt n))
17715 m (- m (* n mo d h))))
17716 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17717 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17718 (plist-get org-time-clocksum-format :require-weeks))
17719 (setq clocksum (concat clocksum (format fmt n))
17720 m (- m (* n w d h))))
17721 (and (setq fmt (plist-get org-time-clocksum-format :days))
17722 (or (> (setq n (/ (truncate m) (* d h))) 0)
17723 (plist-get org-time-clocksum-format :require-days))
17724 (setq clocksum (concat clocksum (format fmt n))
17725 m (- m (* n d h))))
17726 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17727 (or (> (setq n (/ (truncate m) h)) 0)
17728 (plist-get org-time-clocksum-format :require-hours))
17729 (setq clocksum (concat clocksum (format fmt n))
17730 m (- m (* n h))))
17731 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17732 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17733 (setq clocksum (concat clocksum (format fmt m))))
17734 ;; return formatted time duration
17735 clocksum))))
17737 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17738 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17739 "Org mode version 8.0")
17741 (defun org-hours-to-clocksum-string (n)
17742 (org-minutes-to-clocksum-string (* n 60)))
17744 (defun org-hh:mm-string-to-minutes (s)
17745 "Convert a string H:MM to a number of minutes.
17746 If the string is just a number, interpret it as minutes.
17747 In fact, the first hh:mm or number in the string will be taken,
17748 there can be extra stuff in the string.
17749 If no number is found, the return value is 0."
17750 (cond
17751 ((integerp s) s)
17752 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17753 (+ (* (string-to-number (match-string 1 s)) 60)
17754 (string-to-number (match-string 2 s))))
17755 ((string-match "\\([0-9]+\\)" s)
17756 (string-to-number (match-string 1 s)))
17757 (t 0)))
17759 (defcustom org-image-actual-width t
17760 "Should we use the actual width of images when inlining them?
17762 When set to t, always use the image width.
17764 When set to a number, use imagemagick (when available) to set
17765 the image's width to this value.
17767 When set to a number in a list, try to get the width from any
17768 #+ATTR.* keyword if it matches a width specification like
17770 #+ATTR_HTML: :width 300px
17772 and fall back on that number if none is found.
17774 When set to nil, try to get the width from an #+ATTR.* keyword
17775 and fall back on the original width if none is found.
17777 This requires Emacs >= 24.1, build with imagemagick support."
17778 :group 'org-appearance
17779 :version "24.4"
17780 :package-version '(Org . "8.0")
17781 :type '(choice
17782 (const :tag "Use the image width" t)
17783 (integer :tag "Use a number of pixels")
17784 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17785 (const :tag "Use #+ATTR* or don't resize" nil)))
17787 (defcustom org-agenda-inhibit-startup nil
17788 "Inhibit startup when preparing agenda buffers.
17789 When this variable is t, the initialization of the Org agenda
17790 buffers is inhibited: e.g. the visibility state is not set, the
17791 tables are not re-aligned, etc."
17792 :type 'boolean
17793 :version "24.3"
17794 :group 'org-agenda)
17796 (defcustom org-agenda-ignore-drawer-properties nil
17797 "Avoid updating text properties when building the agenda.
17798 Properties are used to prepare buffers for effort estimates, appointments,
17799 and subtree-local categories.
17800 If you don't use these in the agenda, you can add them to this list and
17801 agenda building will be a bit faster.
17802 The value is a list, with zero or more of the symbols `effort', `appt',
17803 or `category'."
17804 :type '(set :greedy t
17805 (const effort)
17806 (const appt)
17807 (const category))
17808 :version "24.3"
17809 :group 'org-agenda)
17811 (defun org-duration-string-to-minutes (s &optional output-to-string)
17812 "Convert a duration string S to minutes.
17814 A bare number is interpreted as minutes, modifiers can be set by
17815 customizing `org-effort-durations' (which see).
17817 Entries containing a colon are interpreted as H:MM by
17818 `org-hh:mm-string-to-minutes'."
17819 (let ((result 0)
17820 (re (concat "\\([0-9.]+\\) *\\("
17821 (regexp-opt (mapcar 'car org-effort-durations))
17822 "\\)")))
17823 (while (string-match re s)
17824 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17825 (string-to-number (match-string 1 s))))
17826 (setq s (replace-match "" nil t s)))
17827 (setq result (floor result))
17828 (incf result (org-hh:mm-string-to-minutes s))
17829 (if output-to-string (number-to-string result) result)))
17831 ;;;; Files
17833 (defun org-save-all-org-buffers ()
17834 "Save all Org-mode buffers without user confirmation."
17835 (interactive)
17836 (message "Saving all Org-mode buffers...")
17837 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17838 (when (featurep 'org-id) (org-id-locations-save))
17839 (message "Saving all Org-mode buffers... done"))
17841 (defun org-revert-all-org-buffers ()
17842 "Revert all Org-mode buffers.
17843 Prompt for confirmation when there are unsaved changes.
17844 Be sure you know what you are doing before letting this function
17845 overwrite your changes.
17847 This function is useful in a setup where one tracks org files
17848 with a version control system, to revert on one machine after pulling
17849 changes from another. I believe the procedure must be like this:
17851 1. M-x org-save-all-org-buffers
17852 2. Pull changes from the other machine, resolve conflicts
17853 3. M-x org-revert-all-org-buffers"
17854 (interactive)
17855 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17856 (user-error "Abort"))
17857 (save-excursion
17858 (save-window-excursion
17859 (mapc
17860 (lambda (b)
17861 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17862 (with-current-buffer b buffer-file-name))
17863 (org-pop-to-buffer-same-window b)
17864 (revert-buffer t 'no-confirm)))
17865 (buffer-list))
17866 (when (and (featurep 'org-id) org-id-track-globally)
17867 (org-id-locations-load)))))
17869 ;;;; Agenda files
17871 ;;;###autoload
17872 (defun org-switchb (&optional arg)
17873 "Switch between Org buffers.
17874 With one prefix argument, restrict available buffers to files.
17875 With two prefix arguments, restrict available buffers to agenda files.
17877 Defaults to `iswitchb' for buffer name completion.
17878 Set `org-completion-use-ido' to make it use ido instead."
17879 (interactive "P")
17880 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17881 ((equal arg '(16)) (org-buffer-list 'agenda))
17882 (t (org-buffer-list))))
17883 (org-completion-use-iswitchb org-completion-use-iswitchb)
17884 (org-completion-use-ido org-completion-use-ido))
17885 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17886 (setq org-completion-use-iswitchb t))
17887 (org-pop-to-buffer-same-window
17888 (org-icompleting-read "Org buffer: "
17889 (mapcar 'list (mapcar 'buffer-name blist))
17890 nil t))))
17892 ;;; Define some older names previously used for this functionality
17893 ;;;###autoload
17894 (defalias 'org-ido-switchb 'org-switchb)
17895 ;;;###autoload
17896 (defalias 'org-iswitchb 'org-switchb)
17898 (defun org-buffer-list (&optional predicate exclude-tmp)
17899 "Return a list of Org buffers.
17900 PREDICATE can be `export', `files' or `agenda'.
17902 export restrict the list to Export buffers.
17903 files restrict the list to buffers visiting Org files.
17904 agenda restrict the list to buffers visiting agenda files.
17906 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17907 (let* ((bfn nil)
17908 (agenda-files (and (eq predicate 'agenda)
17909 (mapcar 'file-truename (org-agenda-files t))))
17910 (filter
17911 (cond
17912 ((eq predicate 'files)
17913 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17914 ((eq predicate 'export)
17915 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17916 ((eq predicate 'agenda)
17917 (lambda (b)
17918 (with-current-buffer b
17919 (and (derived-mode-p 'org-mode)
17920 (setq bfn (buffer-file-name b))
17921 (member (file-truename bfn) agenda-files)))))
17922 (t (lambda (b) (with-current-buffer b
17923 (or (derived-mode-p 'org-mode)
17924 (string-match "\\*Org .*Export"
17925 (buffer-name b)))))))))
17926 (delq nil
17927 (mapcar
17928 (lambda(b)
17929 (if (and (funcall filter b)
17930 (or (not exclude-tmp)
17931 (not (string-match "tmp" (buffer-name b)))))
17933 nil))
17934 (buffer-list)))))
17936 (defun org-agenda-files (&optional unrestricted archives)
17937 "Get the list of agenda files.
17938 Optional UNRESTRICTED means return the full list even if a restriction
17939 is currently in place.
17940 When ARCHIVES is t, include all archive files that are really being
17941 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17942 `org-agenda-archives-mode' is t."
17943 (let ((files
17944 (cond
17945 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17946 ((stringp org-agenda-files) (org-read-agenda-file-list))
17947 ((listp org-agenda-files) org-agenda-files)
17948 (t (error "Invalid value of `org-agenda-files'")))))
17949 (setq files (apply 'append
17950 (mapcar (lambda (f)
17951 (if (file-directory-p f)
17952 (directory-files
17953 f t org-agenda-file-regexp)
17954 (list f)))
17955 files)))
17956 (when org-agenda-skip-unavailable-files
17957 (setq files (delq nil
17958 (mapcar (function
17959 (lambda (file)
17960 (and (file-readable-p file) file)))
17961 files))))
17962 (when (or (eq archives t)
17963 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17964 (setq files (org-add-archive-files files)))
17965 files))
17967 (defun org-agenda-file-p (&optional file)
17968 "Return non-nil, if FILE is an agenda file.
17969 If FILE is omitted, use the file associated with the current
17970 buffer."
17971 (member (or file (buffer-file-name))
17972 (org-agenda-files t)))
17974 (defun org-edit-agenda-file-list ()
17975 "Edit the list of agenda files.
17976 Depending on setup, this either uses customize to edit the variable
17977 `org-agenda-files', or it visits the file that is holding the list. In the
17978 latter case, the buffer is set up in a way that saving it automatically kills
17979 the buffer and restores the previous window configuration."
17980 (interactive)
17981 (if (stringp org-agenda-files)
17982 (let ((cw (current-window-configuration)))
17983 (find-file org-agenda-files)
17984 (org-set-local 'org-window-configuration cw)
17985 (org-add-hook 'after-save-hook
17986 (lambda ()
17987 (set-window-configuration
17988 (prog1 org-window-configuration
17989 (kill-buffer (current-buffer))))
17990 (org-install-agenda-files-menu)
17991 (message "New agenda file list installed"))
17992 nil 'local)
17993 (message "%s" (substitute-command-keys
17994 "Edit list and finish with \\[save-buffer]")))
17995 (customize-variable 'org-agenda-files)))
17997 (defun org-store-new-agenda-file-list (list)
17998 "Set new value for the agenda file list and save it correctly."
17999 (if (stringp org-agenda-files)
18000 (let ((fe (org-read-agenda-file-list t)) b u)
18001 (while (setq b (find-buffer-visiting org-agenda-files))
18002 (kill-buffer b))
18003 (with-temp-file org-agenda-files
18004 (insert
18005 (mapconcat
18006 (lambda (f) ;; Keep un-expanded entries.
18007 (if (setq u (assoc f fe))
18008 (cdr u)
18010 list "\n")
18011 "\n")))
18012 (let ((org-mode-hook nil) (org-inhibit-startup t)
18013 (org-insert-mode-line-in-empty-file nil))
18014 (setq org-agenda-files list)
18015 (customize-save-variable 'org-agenda-files org-agenda-files))))
18017 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18018 "Read the list of agenda files from a file.
18019 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18020 filenames, used by `org-store-new-agenda-file-list' to write back
18021 un-expanded file names."
18022 (when (file-directory-p org-agenda-files)
18023 (error "`org-agenda-files' cannot be a single directory"))
18024 (when (stringp org-agenda-files)
18025 (with-temp-buffer
18026 (insert-file-contents org-agenda-files)
18027 (mapcar
18028 (lambda (f)
18029 (let ((e (expand-file-name (substitute-in-file-name f)
18030 org-directory)))
18031 (if pair-with-expansion
18032 (cons e f)
18033 e)))
18034 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18036 ;;;###autoload
18037 (defun org-cycle-agenda-files ()
18038 "Cycle through the files in `org-agenda-files'.
18039 If the current buffer visits an agenda file, find the next one in the list.
18040 If the current buffer does not, find the first agenda file."
18041 (interactive)
18042 (let* ((fs (org-agenda-files t))
18043 (files (append fs (list (car fs))))
18044 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18045 file)
18046 (unless files (user-error "No agenda files"))
18047 (catch 'exit
18048 (dolist (file files)
18049 (if (equal (file-truename file) tcf)
18050 (when (car files)
18051 (find-file (car files))
18052 (throw 'exit t))))
18053 (find-file (car fs)))
18054 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18056 (defun org-agenda-file-to-front (&optional to-end)
18057 "Move/add the current file to the top of the agenda file list.
18058 If the file is not present in the list, it is added to the front. If it is
18059 present, it is moved there. With optional argument TO-END, add/move to the
18060 end of the list."
18061 (interactive "P")
18062 (let ((org-agenda-skip-unavailable-files nil)
18063 (file-alist (mapcar (lambda (x)
18064 (cons (file-truename x) x))
18065 (org-agenda-files t)))
18066 (ctf (file-truename
18067 (or buffer-file-name
18068 (user-error "Please save the current buffer to a file"))))
18069 x had)
18070 (setq x (assoc ctf file-alist) had x)
18072 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18073 (if to-end
18074 (setq file-alist (append (delq x file-alist) (list x)))
18075 (setq file-alist (cons x (delq x file-alist))))
18076 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18077 (org-install-agenda-files-menu)
18078 (message "File %s to %s of agenda file list"
18079 (if had "moved" "added") (if to-end "end" "front"))))
18081 (defun org-remove-file (&optional file)
18082 "Remove current file from the list of files in variable `org-agenda-files'.
18083 These are the files which are being checked for agenda entries.
18084 Optional argument FILE means use this file instead of the current."
18085 (interactive)
18086 (let* ((org-agenda-skip-unavailable-files nil)
18087 (file (or file buffer-file-name
18088 (user-error "Current buffer does not visit a file")))
18089 (true-file (file-truename file))
18090 (afile (abbreviate-file-name file))
18091 (files (delq nil (mapcar
18092 (lambda (x)
18093 (if (equal true-file
18094 (file-truename x))
18095 nil x))
18096 (org-agenda-files t)))))
18097 (if (not (= (length files) (length (org-agenda-files t))))
18098 (progn
18099 (org-store-new-agenda-file-list files)
18100 (org-install-agenda-files-menu)
18101 (message "Removed file: %s" afile))
18102 (message "File was not in list: %s (not removed)" afile))))
18104 (defun org-file-menu-entry (file)
18105 (vector file (list 'find-file file) t))
18107 (defun org-check-agenda-file (file)
18108 "Make sure FILE exists. If not, ask user what to do."
18109 (when (not (file-exists-p file))
18110 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18111 (abbreviate-file-name file))
18112 (let ((r (downcase (read-char-exclusive))))
18113 (cond
18114 ((equal r ?r)
18115 (org-remove-file file)
18116 (throw 'nextfile t))
18117 (t (error "Abort"))))))
18119 (defun org-get-agenda-file-buffer (file)
18120 "Get a buffer visiting FILE. If the buffer needs to be created, add
18121 it to the list of buffers which might be released later."
18122 (let ((buf (org-find-base-buffer-visiting file)))
18123 (if buf
18124 buf ; just return it
18125 ;; Make a new buffer and remember it
18126 (setq buf (find-file-noselect file))
18127 (if buf (push buf org-agenda-new-buffers))
18128 buf)))
18130 (defun org-release-buffers (blist)
18131 "Release all buffers in list, asking the user for confirmation when needed.
18132 When a buffer is unmodified, it is just killed. When modified, it is saved
18133 \(if the user agrees) and then killed."
18134 (let (file)
18135 (dolist (buf blist)
18136 (setq file (buffer-file-name buf))
18137 (when (and (buffer-modified-p buf)
18138 file
18139 (y-or-n-p (format "Save file %s? " file)))
18140 (with-current-buffer buf (save-buffer)))
18141 (kill-buffer buf))))
18143 (defun org-agenda-prepare-buffers (files)
18144 "Create buffers for all agenda files, protect archived trees and comments."
18145 (interactive)
18146 (let ((pa '(:org-archived t))
18147 (pc '(:org-comment t))
18148 (pall '(:org-archived t :org-comment t))
18149 (inhibit-read-only t)
18150 (org-inhibit-startup org-agenda-inhibit-startup)
18151 (rea (concat ":" org-archive-tag ":"))
18152 file re pos)
18153 (setq org-tag-alist-for-agenda nil
18154 org-tag-groups-alist-for-agenda nil)
18155 (save-excursion
18156 (save-restriction
18157 (dolist (file files)
18158 (catch 'nextfile
18159 (if (bufferp file)
18160 (set-buffer file)
18161 (org-check-agenda-file file)
18162 (set-buffer (org-get-agenda-file-buffer file)))
18163 (widen)
18164 (org-set-regexps-and-options-for-tags)
18165 (setq pos (point))
18166 (goto-char (point-min))
18167 (let ((case-fold-search t))
18168 (when (search-forward "#+setupfile" nil t)
18169 ;; Don't set all regexps and options systematically as
18170 ;; this is only run for setting agenda tags from setup
18171 ;; file
18172 (org-set-regexps-and-options)))
18173 (or (memq 'category org-agenda-ignore-drawer-properties)
18174 (org-refresh-category-properties))
18175 (or (memq 'effort org-agenda-ignore-drawer-properties)
18176 (org-refresh-properties org-effort-property 'org-effort))
18177 (or (memq 'appt org-agenda-ignore-drawer-properties)
18178 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18179 (setq org-todo-keywords-for-agenda
18180 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18181 (setq org-done-keywords-for-agenda
18182 (append org-done-keywords-for-agenda org-done-keywords))
18183 (setq org-todo-keyword-alist-for-agenda
18184 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18185 (setq org-drawers-for-agenda
18186 (append org-drawers-for-agenda org-drawers))
18187 (setq org-tag-alist-for-agenda
18188 (org-uniquify
18189 (append org-tag-alist-for-agenda
18190 org-tag-alist
18191 org-tag-persistent-alist)))
18192 (if org-group-tags
18193 (setq org-tag-groups-alist-for-agenda
18194 (org-uniquify-alist
18195 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18196 (org-with-silent-modifications
18197 (save-excursion
18198 (remove-text-properties (point-min) (point-max) pall)
18199 (when org-agenda-skip-archived-trees
18200 (goto-char (point-min))
18201 (while (re-search-forward rea nil t)
18202 (if (org-at-heading-p t)
18203 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18204 (goto-char (point-min))
18205 (setq re (format org-heading-keyword-regexp-format
18206 org-comment-string))
18207 (while (re-search-forward re nil t)
18208 (add-text-properties
18209 (match-beginning 0) (org-end-of-subtree t) pc))))
18210 (goto-char pos)))))
18211 (setq org-todo-keywords-for-agenda
18212 (org-uniquify org-todo-keywords-for-agenda))
18213 (setq org-todo-keyword-alist-for-agenda
18214 (org-uniquify org-todo-keyword-alist-for-agenda))))
18217 ;;;; CDLaTeX minor mode
18219 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18220 "Keymap for the minor `org-cdlatex-mode'.")
18222 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18223 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18224 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18225 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18226 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18228 (defvar org-cdlatex-texmathp-advice-is-done nil
18229 "Flag remembering if we have applied the advice to texmathp already.")
18231 (define-minor-mode org-cdlatex-mode
18232 "Toggle the minor `org-cdlatex-mode'.
18233 This mode supports entering LaTeX environment and math in LaTeX fragments
18234 in Org-mode.
18235 \\{org-cdlatex-mode-map}"
18236 nil " OCDL" nil
18237 (when org-cdlatex-mode
18238 (require 'cdlatex)
18239 (run-hooks 'cdlatex-mode-hook)
18240 (cdlatex-compute-tables))
18241 (unless org-cdlatex-texmathp-advice-is-done
18242 (setq org-cdlatex-texmathp-advice-is-done t)
18243 (defadvice texmathp (around org-math-always-on activate)
18244 "Always return t in org-mode buffers.
18245 This is because we want to insert math symbols without dollars even outside
18246 the LaTeX math segments. If Orgmode thinks that point is actually inside
18247 an embedded LaTeX fragment, let texmathp do its job.
18248 \\[org-cdlatex-mode-map]"
18249 (interactive)
18250 (let (p)
18251 (cond
18252 ((not (derived-mode-p 'org-mode)) ad-do-it)
18253 ((eq this-command 'cdlatex-math-symbol)
18254 (setq ad-return-value t
18255 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18257 (let ((p (org-inside-LaTeX-fragment-p)))
18258 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18259 (setq ad-return-value t
18260 texmathp-why '("Org-mode embedded math" . 0))
18261 (if p ad-do-it)))))))))
18263 (defun turn-on-org-cdlatex ()
18264 "Unconditionally turn on `org-cdlatex-mode'."
18265 (org-cdlatex-mode 1))
18267 (defun org-try-cdlatex-tab ()
18268 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18269 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18270 - inside a LaTeX fragment, or
18271 - after the first word in a line, where an abbreviation expansion could
18272 insert a LaTeX environment."
18273 (when org-cdlatex-mode
18274 (cond
18275 ;; Before any word on the line: No expansion possible.
18276 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18277 ;; Just after first word on the line: Expand it. Make sure it
18278 ;; cannot happen on headlines, though.
18279 ((save-excursion
18280 (skip-chars-backward "a-zA-Z0-9*")
18281 (skip-chars-backward " \t")
18282 (and (bolp) (not (org-at-heading-p))))
18283 (cdlatex-tab) t)
18284 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18286 (defun org-cdlatex-underscore-caret (&optional arg)
18287 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18288 Revert to the normal definition outside of these fragments."
18289 (interactive "P")
18290 (if (org-inside-LaTeX-fragment-p)
18291 (call-interactively 'cdlatex-sub-superscript)
18292 (let (org-cdlatex-mode)
18293 (call-interactively (key-binding (vector last-input-event))))))
18295 (defun org-cdlatex-math-modify (&optional arg)
18296 "Execute `cdlatex-math-modify' in LaTeX fragments.
18297 Revert to the normal definition outside of these fragments."
18298 (interactive "P")
18299 (if (org-inside-LaTeX-fragment-p)
18300 (call-interactively 'cdlatex-math-modify)
18301 (let (org-cdlatex-mode)
18302 (call-interactively (key-binding (vector last-input-event))))))
18306 ;;;; LaTeX fragments
18308 (defvar org-latex-regexps
18309 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18310 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18311 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18312 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18313 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18314 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18315 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18316 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18317 "Regular expressions for matching embedded LaTeX.")
18319 (defun org-inside-LaTeX-fragment-p ()
18320 "Test if point is inside a LaTeX fragment.
18321 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18322 sequence appearing also before point.
18323 Even though the matchers for math are configurable, this function assumes
18324 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18325 delimiters are skipped when they have been removed by customization.
18326 The return value is nil, or a cons cell with the delimiter and the
18327 position of this delimiter.
18329 This function does a reasonably good job, but can locally be fooled by
18330 for example currency specifications. For example it will assume being in
18331 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18332 fragments that are properly closed, but during editing, we have to live
18333 with the uncertainty caused by missing closing delimiters. This function
18334 looks only before point, not after."
18335 (catch 'exit
18336 (let ((pos (point))
18337 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18338 (lim (progn
18339 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18340 (point)))
18341 dd-on str (start 0) m re)
18342 (goto-char pos)
18343 (when dodollar
18344 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18345 re (nth 1 (assoc "$" org-latex-regexps)))
18346 (while (string-match re str start)
18347 (cond
18348 ((= (match-end 0) (length str))
18349 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18350 ((= (match-end 0) (- (length str) 5))
18351 (throw 'exit nil))
18352 (t (setq start (match-end 0))))))
18353 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18354 (goto-char pos)
18355 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18356 (and (match-beginning 2) (throw 'exit nil))
18357 ;; count $$
18358 (while (re-search-backward "\\$\\$" lim t)
18359 (setq dd-on (not dd-on)))
18360 (goto-char pos)
18361 (if dd-on (cons "$$" m))))))
18363 (defun org-inside-latex-macro-p ()
18364 "Is point inside a LaTeX macro or its arguments?"
18365 (save-match-data
18366 (org-in-regexp
18367 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18369 (defvar org-latex-fragment-image-overlays nil
18370 "List of overlays carrying the images of latex fragments.")
18371 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18373 (defun org-remove-latex-fragment-image-overlays ()
18374 "Remove all overlays with LaTeX fragment images in current buffer."
18375 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18376 (setq org-latex-fragment-image-overlays nil))
18378 (defun org-preview-latex-fragment (&optional subtree)
18379 "Preview the LaTeX fragment at point, or all locally or globally.
18380 If the cursor is in a LaTeX fragment, create the image and overlay
18381 it over the source code. If there is no fragment at point, display
18382 all fragments in the current text, from one headline to the next. With
18383 prefix SUBTREE, display all fragments in the current subtree. With a
18384 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18385 the cursor is before the first headline,
18386 display all fragments in the buffer.
18387 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18388 (interactive "P")
18389 (unless buffer-file-name
18390 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18391 (when (display-graphic-p)
18392 (org-remove-latex-fragment-image-overlays)
18393 (save-excursion
18394 (save-restriction
18395 (let (beg end at msg)
18396 (cond
18397 ((or (equal subtree '(16))
18398 (not (save-excursion
18399 (re-search-backward org-outline-regexp-bol nil t))))
18400 (setq beg (point-min) end (point-max)
18401 msg "Creating images for buffer...%s"))
18402 ((equal subtree '(4))
18403 (org-back-to-heading)
18404 (setq beg (point) end (org-end-of-subtree t)
18405 msg "Creating images for subtree...%s"))
18407 (if (setq at (org-inside-LaTeX-fragment-p))
18408 (goto-char (max (point-min) (- (cdr at) 2)))
18409 (org-back-to-heading))
18410 (setq beg (point) end (progn (outline-next-heading) (point))
18411 msg (if at "Creating image...%s"
18412 "Creating images for entry...%s"))))
18413 (message msg "")
18414 (narrow-to-region beg end)
18415 (goto-char beg)
18416 (org-format-latex
18417 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18418 (file-name-nondirectory
18419 buffer-file-name)))
18420 default-directory 'overlays msg at 'forbuffer
18421 org-latex-create-formula-image-program)
18422 (message msg "done. Use `C-c C-c' to remove images."))))))
18424 (defun org-format-latex (prefix &optional dir overlays msg at
18425 forbuffer processing-type)
18426 "Replace LaTeX fragments with links to an image, and produce images.
18427 Some of the options can be changed using the variable
18428 `org-format-latex-options'."
18429 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18430 (let* ((prefixnodir (file-name-nondirectory prefix))
18431 (absprefix (expand-file-name prefix dir))
18432 (todir (file-name-directory absprefix))
18433 (opt org-format-latex-options)
18434 (optnew org-format-latex-options)
18435 (matchers (plist-get opt :matchers))
18436 (re-list org-latex-regexps)
18437 (cnt 0) txt hash link beg end re checkdir
18438 string
18439 m n block-type block linkfile movefile ov)
18440 ;; Check the different regular expressions
18441 (dolist (e re-list)
18442 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18443 block (if block-type "\n\n" ""))
18444 (when (member m matchers)
18445 (goto-char (point-min))
18446 (while (re-search-forward re nil t)
18447 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18448 (or (not overlays)
18449 (not (eq (get-char-property (match-beginning n)
18450 'org-overlay-type)
18451 'org-latex-overlay))))
18452 (cond
18453 ((eq processing-type 'verbatim))
18454 ((eq processing-type 'mathjax)
18455 ;; Prepare for MathJax processing.
18456 (setq string (match-string n))
18457 (when (member m '("$" "$1"))
18458 (save-excursion
18459 (delete-region (match-beginning n) (match-end n))
18460 (goto-char (match-beginning n))
18461 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18462 ((or (eq processing-type 'dvipng)
18463 (eq processing-type 'imagemagick))
18464 ;; Process to an image.
18465 (setq txt (match-string n)
18466 beg (match-beginning n) end (match-end n)
18467 cnt (1+ cnt))
18468 (let ((face (face-at-point))
18469 (fg (plist-get opt :foreground))
18470 (bg (plist-get opt :background))
18471 ;; Ensure full list is printed.
18472 print-length print-level)
18473 (when forbuffer
18474 ;; Get the colors from the face at point.
18475 (goto-char beg)
18476 (when (eq fg 'auto)
18477 (setq fg (face-attribute face :foreground nil 'default)))
18478 (when (eq bg 'auto)
18479 (setq bg (face-attribute face :background nil 'default)))
18480 (setq optnew (copy-sequence opt))
18481 (plist-put optnew :foreground fg)
18482 (plist-put optnew :background bg))
18483 (setq hash (sha1 (prin1-to-string
18484 (list org-format-latex-header
18485 org-latex-default-packages-alist
18486 org-latex-packages-alist
18487 org-format-latex-options
18488 forbuffer txt fg bg)))
18489 linkfile (format "%s_%s.png" prefix hash)
18490 movefile (format "%s_%s.png" absprefix hash)))
18491 (setq link (concat block "[[file:" linkfile "]]" block))
18492 (if msg (message msg cnt))
18493 (goto-char beg)
18494 (unless checkdir ; Ensure the directory exists.
18495 (setq checkdir t)
18496 (or (file-directory-p todir) (make-directory todir t)))
18497 (unless (file-exists-p movefile)
18498 (org-create-formula-image
18499 txt movefile optnew forbuffer processing-type))
18500 (if overlays
18501 (progn
18502 (mapc (lambda (o)
18503 (if (eq (overlay-get o 'org-overlay-type)
18504 'org-latex-overlay)
18505 (delete-overlay o)))
18506 (overlays-in beg end))
18507 (setq ov (make-overlay beg end))
18508 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18509 (if (featurep 'xemacs)
18510 (progn
18511 (overlay-put ov 'invisible t)
18512 (overlay-put
18513 ov 'end-glyph
18514 (make-glyph (vector 'png :file movefile))))
18515 (overlay-put
18516 ov 'display
18517 (list 'image :type 'png :file movefile :ascent 'center)))
18518 (push ov org-latex-fragment-image-overlays)
18519 (goto-char end))
18520 (delete-region beg end)
18521 (insert (org-add-props link
18522 (list 'org-latex-src
18523 (replace-regexp-in-string
18524 "\"" "" txt)
18525 'org-latex-src-embed-type
18526 (if block-type 'paragraph 'character))))))
18527 ((eq processing-type 'mathml)
18528 ;; Process to MathML
18529 (unless (save-match-data (org-format-latex-mathml-available-p))
18530 (user-error "LaTeX to MathML converter not configured"))
18531 (setq txt (match-string n)
18532 beg (match-beginning n) end (match-end n)
18533 cnt (1+ cnt))
18534 (if msg (message msg cnt))
18535 (goto-char beg)
18536 (delete-region beg end)
18537 (insert (org-format-latex-as-mathml
18538 txt block-type prefix dir)))
18540 (error "Unknown conversion type %s for LaTeX fragments"
18541 processing-type)))))))))
18543 (defun org-create-math-formula (latex-frag &optional mathml-file)
18544 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18545 Use `org-latex-to-mathml-convert-command'. If the conversion is
18546 sucessful, return the portion between \"<math...> </math>\"
18547 elements otherwise return nil. When MATHML-FILE is specified,
18548 write the results in to that file. When invoked as an
18549 interactive command, prompt for LATEX-FRAG, with initial value
18550 set to the current active region and echo the results for user
18551 inspection."
18552 (interactive (list (let ((frag (when (org-region-active-p)
18553 (buffer-substring-no-properties
18554 (region-beginning) (region-end)))))
18555 (read-string "LaTeX Fragment: " frag nil frag))))
18556 (unless latex-frag (error "Invalid LaTeX fragment"))
18557 (let* ((tmp-in-file (file-relative-name
18558 (make-temp-name (expand-file-name "ltxmathml-in"))))
18559 (ignore (write-region latex-frag nil tmp-in-file))
18560 (tmp-out-file (file-relative-name
18561 (make-temp-name (expand-file-name "ltxmathml-out"))))
18562 (cmd (format-spec
18563 org-latex-to-mathml-convert-command
18564 `((?j . ,(shell-quote-argument
18565 (expand-file-name org-latex-to-mathml-jar-file)))
18566 (?I . ,(shell-quote-argument tmp-in-file))
18567 (?o . ,(shell-quote-argument tmp-out-file)))))
18568 mathml shell-command-output)
18569 (when (org-called-interactively-p 'any)
18570 (unless (org-format-latex-mathml-available-p)
18571 (user-error "LaTeX to MathML converter not configured")))
18572 (message "Running %s" cmd)
18573 (setq shell-command-output (shell-command-to-string cmd))
18574 (setq mathml
18575 (when (file-readable-p tmp-out-file)
18576 (with-current-buffer (find-file-noselect tmp-out-file t)
18577 (goto-char (point-min))
18578 (when (re-search-forward
18579 (concat
18580 (regexp-quote
18581 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18582 "\\(.\\|\n\\)*"
18583 (regexp-quote "</math>")) nil t)
18584 (prog1 (match-string 0) (kill-buffer))))))
18585 (cond
18586 (mathml
18587 (setq mathml
18588 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18589 (when mathml-file
18590 (write-region mathml nil mathml-file))
18591 (when (org-called-interactively-p 'any)
18592 (message mathml)))
18593 ((message "LaTeX to MathML conversion failed")
18594 (message shell-command-output)))
18595 (delete-file tmp-in-file)
18596 (when (file-exists-p tmp-out-file)
18597 (delete-file tmp-out-file))
18598 mathml))
18600 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18601 prefix &optional dir)
18602 "Use `org-create-math-formula' but check local cache first."
18603 (let* ((absprefix (expand-file-name prefix dir))
18604 (print-length nil) (print-level nil)
18605 (formula-id (concat
18606 "formula-"
18607 (sha1
18608 (prin1-to-string
18609 (list latex-frag
18610 org-latex-to-mathml-convert-command)))))
18611 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18612 (formula-cache-dir (file-name-directory formula-cache)))
18614 (unless (file-directory-p formula-cache-dir)
18615 (make-directory formula-cache-dir t))
18617 (unless (file-exists-p formula-cache)
18618 (org-create-math-formula latex-frag formula-cache))
18620 (if (file-exists-p formula-cache)
18621 ;; Successful conversion. Return the link to MathML file.
18622 (org-add-props
18623 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18624 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18625 'org-latex-src-embed-type (if latex-frag-type
18626 'paragraph 'character)))
18627 ;; Failed conversion. Return the LaTeX fragment verbatim
18628 latex-frag)))
18630 (defun org-create-formula-image (string tofile options buffer &optional type)
18631 "Create an image from LaTeX source using dvipng or convert.
18632 This function calls either `org-create-formula-image-with-dvipng'
18633 or `org-create-formula-image-with-imagemagick' depending on the
18634 value of `org-latex-create-formula-image-program' or on the value
18635 of the optional TYPE variable.
18637 Note: ultimately these two function should be combined as they
18638 share a good deal of logic."
18639 (org-check-external-command
18640 "latex" "needed to convert LaTeX fragments to images")
18641 (funcall
18642 (case (or type org-latex-create-formula-image-program)
18643 ('dvipng
18644 (org-check-external-command
18645 "dvipng" "needed to convert LaTeX fragments to images")
18646 #'org-create-formula-image-with-dvipng)
18647 ('imagemagick
18648 (org-check-external-command
18649 "convert" "you need to install imagemagick")
18650 #'org-create-formula-image-with-imagemagick)
18651 (t (error
18652 "Invalid value of `org-latex-create-formula-image-program'")))
18653 string tofile options buffer))
18655 (declare-function org-export-get-backend "ox" (name))
18656 (declare-function org-export--get-global-options "ox" (&optional backend))
18657 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18658 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18659 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18660 (defun org-create-formula--latex-header ()
18661 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18662 (let ((info (org-combine-plists (org-export--get-global-options
18663 (org-export-get-backend 'latex))
18664 (org-export--get-inbuffer-options
18665 (org-export-get-backend 'latex)))))
18666 (org-latex-guess-babel-language
18667 (org-latex-guess-inputenc
18668 (org-splice-latex-header
18669 org-format-latex-header
18670 org-latex-default-packages-alist
18671 org-latex-packages-alist t
18672 (plist-get info :latex-header)))
18673 info)))
18675 ;; This function borrows from Ganesh Swami's latex2png.el
18676 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18677 "This calls dvipng."
18678 (require 'ox-latex)
18679 (let* ((tmpdir (if (featurep 'xemacs)
18680 (temp-directory)
18681 temporary-file-directory))
18682 (texfilebase (make-temp-name
18683 (expand-file-name "orgtex" tmpdir)))
18684 (texfile (concat texfilebase ".tex"))
18685 (dvifile (concat texfilebase ".dvi"))
18686 (pngfile (concat texfilebase ".png"))
18687 (fnh (if (featurep 'xemacs)
18688 (font-height (face-font 'default))
18689 (face-attribute 'default :height nil)))
18690 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18691 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18692 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18693 "Black"))
18694 (bg (or (plist-get options (if buffer :background :html-background))
18695 "Transparent")))
18696 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18697 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18698 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18699 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18700 (let ((latex-header (org-create-formula--latex-header)))
18701 (with-temp-file texfile
18702 (insert latex-header)
18703 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18704 (let ((dir default-directory))
18705 (condition-case nil
18706 (progn
18707 (cd tmpdir)
18708 (call-process "latex" nil nil nil texfile))
18709 (error nil))
18710 (cd dir))
18711 (if (not (file-exists-p dvifile))
18712 (progn (message "Failed to create dvi file from %s" texfile) nil)
18713 (condition-case nil
18714 (if (featurep 'xemacs)
18715 (call-process "dvipng" nil nil nil
18716 "-fg" fg "-bg" bg
18717 "-T" "tight"
18718 "-o" pngfile
18719 dvifile)
18720 (call-process "dvipng" nil nil nil
18721 "-fg" fg "-bg" bg
18722 "-D" dpi
18723 ;;"-x" scale "-y" scale
18724 "-T" "tight"
18725 "-o" pngfile
18726 dvifile))
18727 (error nil))
18728 (if (not (file-exists-p pngfile))
18729 (if org-format-latex-signal-error
18730 (error "Failed to create png file from %s" texfile)
18731 (message "Failed to create png file from %s" texfile)
18732 nil)
18733 ;; Use the requested file name and clean up
18734 (copy-file pngfile tofile 'replace)
18735 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18736 (if (file-exists-p (concat texfilebase e))
18737 (delete-file (concat texfilebase e))))
18738 pngfile))))
18740 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18741 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18742 "This calls convert, which is included into imagemagick."
18743 (require 'ox-latex)
18744 (let* ((tmpdir (if (featurep 'xemacs)
18745 (temp-directory)
18746 temporary-file-directory))
18747 (texfilebase (make-temp-name
18748 (expand-file-name "orgtex" tmpdir)))
18749 (texfile (concat texfilebase ".tex"))
18750 (pdffile (concat texfilebase ".pdf"))
18751 (pngfile (concat texfilebase ".png"))
18752 (fnh (if (featurep 'xemacs)
18753 (font-height (face-font 'default))
18754 (face-attribute 'default :height nil)))
18755 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18756 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18757 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18758 "black"))
18759 (bg (or (plist-get options (if buffer :background :html-background))
18760 "white")))
18761 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18762 (setq fg (org-latex-color-format fg)))
18763 (if (eq bg 'default) (setq bg (org-latex-color :background))
18764 (setq bg (org-latex-color-format
18765 (if (string= bg "Transparent") "white" bg))))
18766 (let ((latex-header (org-create-formula--latex-header)))
18767 (with-temp-file texfile
18768 (insert latex-header)
18769 (insert "\n\\begin{document}\n"
18770 "\\definecolor{fg}{rgb}{" fg "}\n"
18771 "\\definecolor{bg}{rgb}{" bg "}\n"
18772 "\n\\pagecolor{bg}\n"
18773 "\n{\\color{fg}\n"
18774 string
18775 "\n}\n"
18776 "\n\\end{document}\n")))
18777 (org-latex-compile texfile t)
18778 (if (not (file-exists-p pdffile))
18779 (progn (message "Failed to create pdf file from %s" texfile) nil)
18780 (condition-case nil
18781 (if (featurep 'xemacs)
18782 (call-process "convert" nil nil nil
18783 "-density" "96"
18784 "-trim"
18785 "-antialias"
18786 pdffile
18787 "-quality" "100"
18788 ;; "-sharpen" "0x1.0"
18789 pngfile)
18790 (call-process "convert" nil nil nil
18791 "-density" dpi
18792 "-trim"
18793 "-antialias"
18794 pdffile
18795 "-quality" "100"
18796 ;; "-sharpen" "0x1.0"
18797 pngfile))
18798 (error nil))
18799 (if (not (file-exists-p pngfile))
18800 (if org-format-latex-signal-error
18801 (error "Failed to create png file from %s" texfile)
18802 (message "Failed to create png file from %s" texfile)
18803 nil)
18804 ;; Use the requested file name and clean up
18805 (copy-file pngfile tofile 'replace)
18806 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18807 (if (file-exists-p (concat texfilebase e))
18808 (delete-file (concat texfilebase e))))
18809 pngfile))))
18811 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18812 "Fill a LaTeX header template TPL.
18813 In the template, the following place holders will be recognized:
18815 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18816 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18817 [PACKAGES] \\usepackage statements for PKG
18818 [NO-PACKAGES] do not include PKG
18819 [EXTRA] the string EXTRA
18820 [NO-EXTRA] do not include EXTRA
18822 For backward compatibility, if both the positive and the negative place
18823 holder is missing, the positive one (without the \"NO-\") will be
18824 assumed to be present at the end of the template.
18825 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18826 EXTRA is a string.
18827 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18828 (let (rpl (end ""))
18829 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18830 (setq rpl (if (or (match-end 1) (not def-pkg))
18831 "" (org-latex-packages-to-string def-pkg snippets-p t))
18832 tpl (replace-match rpl t t tpl))
18833 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18835 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18836 (setq rpl (if (or (match-end 1) (not pkg))
18837 "" (org-latex-packages-to-string pkg snippets-p t))
18838 tpl (replace-match rpl t t tpl))
18839 (if pkg (setq end
18840 (concat end "\n"
18841 (org-latex-packages-to-string pkg snippets-p)))))
18843 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18844 (setq rpl (if (or (match-end 1) (not extra))
18845 "" (concat extra "\n"))
18846 tpl (replace-match rpl t t tpl))
18847 (if (and extra (string-match "\\S-" extra))
18848 (setq end (concat end "\n" extra))))
18850 (if (string-match "\\S-" end)
18851 (concat tpl "\n" end)
18852 tpl)))
18854 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18855 "Turn an alist of packages into a string with the \\usepackage macros."
18856 (setq pkg (mapconcat (lambda(p)
18857 (cond
18858 ((stringp p) p)
18859 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18860 (format "%% Package %s omitted" (cadr p)))
18861 ((equal "" (car p))
18862 (format "\\usepackage{%s}" (cadr p)))
18864 (format "\\usepackage[%s]{%s}"
18865 (car p) (cadr p)))))
18867 "\n"))
18868 (if newline (concat pkg "\n") pkg))
18870 (defun org-dvipng-color (attr)
18871 "Return a RGB color specification for dvipng."
18872 (apply 'format "rgb %s %s %s"
18873 (mapcar 'org-normalize-color
18874 (if (featurep 'xemacs)
18875 (color-rgb-components
18876 (face-property 'default
18877 (cond ((eq attr :foreground) 'foreground)
18878 ((eq attr :background) 'background))))
18879 (color-values (face-attribute 'default attr nil))))))
18881 (defun org-dvipng-color-format (color-name)
18882 "Convert COLOR-NAME to a RGB color value for dvipng."
18883 (apply 'format "rgb %s %s %s"
18884 (mapcar 'org-normalize-color
18885 (color-values color-name))))
18887 (defun org-latex-color (attr)
18888 "Return a RGB color for the LaTeX color package."
18889 (apply 'format "%s,%s,%s"
18890 (mapcar 'org-normalize-color
18891 (if (featurep 'xemacs)
18892 (color-rgb-components
18893 (face-property 'default
18894 (cond ((eq attr :foreground) 'foreground)
18895 ((eq attr :background) 'background))))
18896 (color-values (face-attribute 'default attr nil))))))
18898 (defun org-latex-color-format (color-name)
18899 "Convert COLOR-NAME to a RGB color value."
18900 (apply 'format "%s,%s,%s"
18901 (mapcar 'org-normalize-color
18902 (color-values color-name))))
18904 (defun org-normalize-color (value)
18905 "Return string to be used as color value for an RGB component."
18906 (format "%g" (/ value 65535.0)))
18910 ;; Image display
18912 (defvar org-inline-image-overlays nil)
18913 (make-variable-buffer-local 'org-inline-image-overlays)
18915 (defun org-toggle-inline-images (&optional include-linked)
18916 "Toggle the display of inline images.
18917 INCLUDE-LINKED is passed to `org-display-inline-images'."
18918 (interactive "P")
18919 (if org-inline-image-overlays
18920 (progn
18921 (org-remove-inline-images)
18922 (message "Inline image display turned off"))
18923 (org-display-inline-images include-linked)
18924 (if (and (org-called-interactively-p)
18925 org-inline-image-overlays)
18926 (message "%d images displayed inline"
18927 (length org-inline-image-overlays))
18928 (message "No images to display inline"))))
18930 (defun org-redisplay-inline-images ()
18931 "Refresh the display of inline images."
18932 (interactive)
18933 (if (not org-inline-image-overlays)
18934 (org-toggle-inline-images)
18935 (org-toggle-inline-images)
18936 (org-toggle-inline-images)))
18938 (defun org-display-inline-images (&optional include-linked refresh beg end)
18939 "Display inline images.
18940 Normally only links without a description part are inlined, because this
18941 is how it will work for export. When INCLUDE-LINKED is set, also links
18942 with a description part will be inlined. This can be nice for a quick
18943 look at those images, but it does not reflect what exported files will look
18944 like.
18945 When REFRESH is set, refresh existing images between BEG and END.
18946 This will create new image displays only if necessary.
18947 BEG and END default to the buffer boundaries."
18948 (interactive "P")
18949 (when (display-graphic-p)
18950 (unless refresh
18951 (org-remove-inline-images)
18952 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18953 (save-excursion
18954 (save-restriction
18955 (widen)
18956 (setq beg (or beg (point-min)) end (or end (point-max)))
18957 (goto-char beg)
18958 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18959 (substring (org-image-file-name-regexp) 0 -2)
18960 "\\)\\]" (if include-linked "" "\\]")))
18961 (case-fold-search t)
18962 old file ov img type attrwidth width)
18963 (while (re-search-forward re end t)
18964 (setq old (get-char-property-and-overlay (match-beginning 1)
18965 'org-image-overlay)
18966 file (expand-file-name
18967 (concat (or (match-string 3) "") (match-string 4))))
18968 (when (image-type-available-p 'imagemagick)
18969 (setq attrwidth (if (or (listp org-image-actual-width)
18970 (null org-image-actual-width))
18971 (save-excursion
18972 (save-match-data
18973 (when (re-search-backward
18974 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18975 (save-excursion
18976 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18977 (string-to-number (match-string 1))))))
18978 width (cond ((eq org-image-actual-width t) nil)
18979 ((null org-image-actual-width) attrwidth)
18980 ((numberp org-image-actual-width)
18981 org-image-actual-width)
18982 ((listp org-image-actual-width)
18983 (or attrwidth (car org-image-actual-width))))
18984 type (if width 'imagemagick)))
18985 (when (file-exists-p file)
18986 (if (and (car-safe old) refresh)
18987 (image-refresh (overlay-get (cdr old) 'display))
18988 (setq img (save-match-data (create-image file type nil :width width)))
18989 (when img
18990 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18991 (overlay-put ov 'display img)
18992 (overlay-put ov 'face 'default)
18993 (overlay-put ov 'org-image-overlay t)
18994 (overlay-put ov 'modification-hooks
18995 (list 'org-display-inline-remove-overlay))
18996 (push ov org-inline-image-overlays))))))))))
18998 (define-obsolete-function-alias
18999 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19001 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19002 "Remove inline-display overlay if a corresponding region is modified."
19003 (let ((inhibit-modification-hooks t))
19004 (when (and ov after)
19005 (delete ov org-inline-image-overlays)
19006 (delete-overlay ov))))
19008 (defun org-remove-inline-images ()
19009 "Remove inline display of images."
19010 (interactive)
19011 (mapc 'delete-overlay org-inline-image-overlays)
19012 (setq org-inline-image-overlays nil))
19014 ;;;; Key bindings
19016 ;; Outline functions from `outline-mode-prefix-map'
19017 ;; that can be remapped in Org:
19018 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19019 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19020 (define-key org-mode-map [remap outline-forward-same-level]
19021 'org-forward-heading-same-level)
19022 (define-key org-mode-map [remap outline-backward-same-level]
19023 'org-backward-heading-same-level)
19024 (define-key org-mode-map [remap show-branches]
19025 'org-kill-note-or-show-branches)
19026 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19027 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19028 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19030 ;; Outline functions from `outline-mode-prefix-map' that can not
19031 ;; be remapped in Org:
19033 ;; - the column "key binding" shows whether the Outline function is still
19034 ;; available in Org mode on the same key that it has been bound to in
19035 ;; Outline mode:
19036 ;; - "overridden": key used for a different functionality in Org mode
19037 ;; - else: key still bound to the same Outline function in Org mode
19039 ;; | Outline function | key binding | Org replacement |
19040 ;; |------------------------------------+-------------+-----------------------|
19041 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19042 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19043 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19044 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19045 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19046 ;; | `show-entry' | overridden | no replacement |
19047 ;; | `show-children' | `C-c C-i' | visibility cycling |
19048 ;; | `show-branches' | `C-c C-k' | still same function |
19049 ;; | `show-subtree' | overridden | visibility cycling |
19050 ;; | `show-all' | overridden | no replacement |
19051 ;; | `hide-subtree' | overridden | visibility cycling |
19052 ;; | `hide-body' | overridden | no replacement |
19053 ;; | `hide-entry' | overridden | visibility cycling |
19054 ;; | `hide-leaves' | overridden | no replacement |
19055 ;; | `hide-sublevels' | overridden | no replacement |
19056 ;; | `hide-other' | overridden | no replacement |
19058 ;; Make `C-c C-x' a prefix key
19059 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19061 ;; TAB key with modifiers
19062 (org-defkey org-mode-map "\C-i" 'org-cycle)
19063 (org-defkey org-mode-map [(tab)] 'org-cycle)
19064 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19065 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19066 ;; The following line is necessary under Suse GNU/Linux
19067 (unless (featurep 'xemacs)
19068 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19069 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19070 (define-key org-mode-map [backtab] 'org-shifttab)
19072 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19073 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19074 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19076 ;; Cursor keys with modifiers
19077 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19078 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19079 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19080 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19082 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19083 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19084 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19085 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19087 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19088 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19089 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19090 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19092 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19093 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19094 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19095 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19097 ;; Babel keys
19098 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19099 (mapc (lambda (pair)
19100 (define-key org-babel-map (car pair) (cdr pair)))
19101 org-babel-key-bindings)
19103 ;;; Extra keys for tty access.
19104 ;; We only set them when really needed because otherwise the
19105 ;; menus don't show the simple keys
19107 (when (or org-use-extra-keys
19108 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19109 (not window-system))
19110 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19111 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19112 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19113 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19114 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19115 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19116 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19117 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19118 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19119 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19120 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19121 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19122 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19123 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19124 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19125 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19126 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19127 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19128 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19129 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19130 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19131 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19132 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19133 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19134 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19135 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19136 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19137 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19139 ;; All the other keys
19141 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19142 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19143 (if (boundp 'narrow-map)
19144 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19145 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19146 (if (boundp 'narrow-map)
19147 (org-defkey narrow-map "b" 'org-narrow-to-block)
19148 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19149 (if (boundp 'narrow-map)
19150 (org-defkey narrow-map "e" 'org-narrow-to-element)
19151 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19152 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19153 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19154 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19155 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19156 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19157 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19158 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19159 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19160 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19161 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19162 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19163 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19164 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19165 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19166 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19167 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19168 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19169 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19170 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19171 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19172 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19173 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19174 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19175 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19176 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19177 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19178 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19179 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19180 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19181 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19182 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19183 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19184 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19185 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19186 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19187 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19188 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19189 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19190 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19191 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19192 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19193 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19194 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19195 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19196 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19197 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19198 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19199 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19200 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19201 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19202 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19203 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19204 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19205 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19206 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19207 (org-defkey org-mode-map "\C-c^" 'org-sort)
19208 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19209 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19210 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19211 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19212 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19213 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19214 (org-defkey org-mode-map "\C-m" 'org-return)
19215 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19216 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19217 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19218 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19219 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19220 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19221 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19222 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19223 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19224 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19225 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19226 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19227 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19228 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19229 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19230 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19231 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19232 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19233 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19234 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19235 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19236 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19237 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19239 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19240 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19241 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19243 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19244 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19245 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19246 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19247 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19248 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19249 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19250 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19251 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19252 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19253 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19254 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19255 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19256 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19257 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19258 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19259 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19260 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19261 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19262 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19263 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19264 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19265 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19267 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19268 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19269 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19270 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19271 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19273 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19275 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19277 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19278 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19280 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19283 (when (featurep 'xemacs)
19284 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19287 (defconst org-speed-commands-default
19289 ("Outline Navigation")
19290 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19291 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19292 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19293 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19294 ("F" . org-next-block)
19295 ("B" . org-previous-block)
19296 ("u" . (org-speed-move-safe 'outline-up-heading))
19297 ("j" . org-goto)
19298 ("g" . (org-refile t))
19299 ("Outline Visibility")
19300 ("c" . org-cycle)
19301 ("C" . org-shifttab)
19302 (" " . org-display-outline-path)
19303 ("s" . org-narrow-to-subtree)
19304 ("=" . org-columns)
19305 ("Outline Structure Editing")
19306 ("U" . org-shiftmetaup)
19307 ("D" . org-shiftmetadown)
19308 ("r" . org-metaright)
19309 ("l" . org-metaleft)
19310 ("R" . org-shiftmetaright)
19311 ("L" . org-shiftmetaleft)
19312 ("i" . (progn (forward-char 1) (call-interactively
19313 'org-insert-heading-respect-content)))
19314 ("^" . org-sort)
19315 ("w" . org-refile)
19316 ("a" . org-archive-subtree-default-with-confirmation)
19317 ("@" . org-mark-subtree)
19318 ("#" . org-toggle-comment)
19319 ("Clock Commands")
19320 ("I" . org-clock-in)
19321 ("O" . org-clock-out)
19322 ("Meta Data Editing")
19323 ("t" . org-todo)
19324 ("," . (org-priority))
19325 ("0" . (org-priority ?\ ))
19326 ("1" . (org-priority ?A))
19327 ("2" . (org-priority ?B))
19328 ("3" . (org-priority ?C))
19329 (":" . org-set-tags-command)
19330 ("e" . org-set-effort)
19331 ("E" . org-inc-effort)
19332 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19333 (org-entry-put (point) "APPT_WARNTIME" m)))
19334 ("Agenda Views etc")
19335 ("v" . org-agenda)
19336 ("/" . org-sparse-tree)
19337 ("Misc")
19338 ("o" . org-open-at-point)
19339 ("?" . org-speed-command-help)
19340 ("<" . (org-agenda-set-restriction-lock 'subtree))
19341 (">" . (org-agenda-remove-restriction-lock))
19343 "The default speed commands.")
19345 (defun org-print-speed-command (e)
19346 (if (> (length (car e)) 1)
19347 (progn
19348 (princ "\n")
19349 (princ (car e))
19350 (princ "\n")
19351 (princ (make-string (length (car e)) ?-))
19352 (princ "\n"))
19353 (princ (car e))
19354 (princ " ")
19355 (if (symbolp (cdr e))
19356 (princ (symbol-name (cdr e)))
19357 (prin1 (cdr e)))
19358 (princ "\n")))
19360 (defun org-speed-command-help ()
19361 "Show the available speed commands."
19362 (interactive)
19363 (if (not org-use-speed-commands)
19364 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19365 (with-output-to-temp-buffer "*Help*"
19366 (princ "User-defined Speed commands\n===========================\n")
19367 (mapc 'org-print-speed-command org-speed-commands-user)
19368 (princ "\n")
19369 (princ "Built-in Speed commands\n=======================\n")
19370 (mapc 'org-print-speed-command org-speed-commands-default))
19371 (with-current-buffer "*Help*"
19372 (setq truncate-lines t))))
19374 (defun org-speed-move-safe (cmd)
19375 "Execute CMD, but make sure that the cursor always ends up in a headline.
19376 If not, return to the original position and throw an error."
19377 (interactive)
19378 (let ((pos (point)))
19379 (call-interactively cmd)
19380 (unless (and (bolp) (org-at-heading-p))
19381 (goto-char pos)
19382 (error "Boundary reached while executing %s" cmd))))
19384 (defvar org-self-insert-command-undo-counter 0)
19386 (defvar org-table-auto-blank-field) ; defined in org-table.el
19387 (defvar org-speed-command nil)
19389 (define-obsolete-function-alias
19390 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19392 (defun org-speed-command-activate (keys)
19393 "Hook for activating single-letter speed commands.
19394 `org-speed-commands-default' specifies a minimal command set.
19395 Use `org-speed-commands-user' for further customization."
19396 (when (or (and (bolp) (looking-at org-outline-regexp))
19397 (and (functionp org-use-speed-commands)
19398 (funcall org-use-speed-commands)))
19399 (cdr (assoc keys (append org-speed-commands-user
19400 org-speed-commands-default)))))
19402 (define-obsolete-function-alias
19403 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19405 (defun org-babel-speed-command-activate (keys)
19406 "Hook for activating single-letter code block commands."
19407 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19408 (cdr (assoc keys org-babel-key-bindings))))
19410 (defcustom org-speed-command-hook
19411 '(org-speed-command-default-hook org-babel-speed-command-hook)
19412 "Hook for activating speed commands at strategic locations.
19413 Hook functions are called in sequence until a valid handler is
19414 found.
19416 Each hook takes a single argument, a user-pressed command key
19417 which is also a `self-insert-command' from the global map.
19419 Within the hook, examine the cursor position and the command key
19420 and return nil or a valid handler as appropriate. Handler could
19421 be one of an interactive command, a function, or a form.
19423 Set `org-use-speed-commands' to non-nil value to enable this
19424 hook. The default setting is `org-speed-command-activate'."
19425 :group 'org-structure
19426 :version "24.1"
19427 :type 'hook)
19429 (defun org-self-insert-command (N)
19430 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19431 If the cursor is in a table looking at whitespace, the whitespace is
19432 overwritten, and the table is not marked as requiring realignment."
19433 (interactive "p")
19434 (org-check-before-invisible-edit 'insert)
19435 (cond
19436 ((and org-use-speed-commands
19437 (setq org-speed-command
19438 (run-hook-with-args-until-success
19439 'org-speed-command-hook (this-command-keys))))
19440 (cond
19441 ((commandp org-speed-command)
19442 (setq this-command org-speed-command)
19443 (call-interactively org-speed-command))
19444 ((functionp org-speed-command)
19445 (funcall org-speed-command))
19446 ((and org-speed-command (listp org-speed-command))
19447 (eval org-speed-command))
19448 (t (let (org-use-speed-commands)
19449 (call-interactively 'org-self-insert-command)))))
19450 ((and
19451 (org-table-p)
19452 (progn
19453 ;; check if we blank the field, and if that triggers align
19454 (and (featurep 'org-table) org-table-auto-blank-field
19455 (member last-command
19456 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19457 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19458 ;; got extra space, this field does not determine column width
19459 (let (org-table-may-need-update) (org-table-blank-field))
19460 ;; no extra space, this field may determine column width
19461 (org-table-blank-field)))
19463 (eq N 1)
19464 (looking-at "[^|\n]* |"))
19465 (let (org-table-may-need-update)
19466 (goto-char (1- (match-end 0)))
19467 (backward-delete-char 1)
19468 (goto-char (match-beginning 0))
19469 (self-insert-command N)))
19471 (setq org-table-may-need-update t)
19472 (self-insert-command N)
19473 (org-fix-tags-on-the-fly)
19474 (if org-self-insert-cluster-for-undo
19475 (if (not (eq last-command 'org-self-insert-command))
19476 (setq org-self-insert-command-undo-counter 1)
19477 (if (>= org-self-insert-command-undo-counter 20)
19478 (setq org-self-insert-command-undo-counter 1)
19479 (and (> org-self-insert-command-undo-counter 0)
19480 buffer-undo-list (listp buffer-undo-list)
19481 (not (cadr buffer-undo-list)) ; remove nil entry
19482 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19483 (setq org-self-insert-command-undo-counter
19484 (1+ org-self-insert-command-undo-counter))))))))
19486 (defun org-check-before-invisible-edit (kind)
19487 "Check is editing if kind KIND would be dangerous with invisible text around.
19488 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19489 ;; First, try to get out of here as quickly as possible, to reduce overhead
19490 (if (and org-catch-invisible-edits
19491 (or (not (boundp 'visible-mode)) (not visible-mode))
19492 (or (get-char-property (point) 'invisible)
19493 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19494 ;; OK, we need to take a closer look
19495 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19496 (invisible-before-point (if (bobp) nil (get-char-property
19497 (1- (point)) 'invisible)))
19498 (border-and-ok-direction
19500 ;; Check if we are acting predictably before invisible text
19501 (and invisible-at-point (not invisible-before-point)
19502 (memq kind '(insert delete-backward)))
19503 ;; Check if we are acting predictably after invisible text
19504 ;; This works not well, and I have turned it off. It seems
19505 ;; better to always show and stop after invisible text.
19506 ;; (and (not invisible-at-point) invisible-before-point
19507 ;; (memq kind '(insert delete)))
19509 (when (or (memq invisible-at-point '(outline org-hide-block t))
19510 (memq invisible-before-point '(outline org-hide-block t)))
19511 (if (eq org-catch-invisible-edits 'error)
19512 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19513 (if (and org-custom-properties-overlays
19514 (y-or-n-p "Display invisible properties in this buffer? "))
19515 (org-toggle-custom-properties-visibility)
19516 ;; Make the area visible
19517 (save-excursion
19518 (if invisible-before-point
19519 (goto-char (previous-single-char-property-change
19520 (point) 'invisible)))
19521 (show-subtree))
19522 (cond
19523 ((eq org-catch-invisible-edits 'show)
19524 ;; That's it, we do the edit after showing
19525 (message
19526 "Unfolding invisible region around point before editing")
19527 (sit-for 1))
19528 ((and (eq org-catch-invisible-edits 'smart)
19529 border-and-ok-direction)
19530 (message "Unfolding invisible region around point before editing"))
19532 ;; Don't do the edit, make the user repeat it in full visibility
19533 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19535 (defun org-fix-tags-on-the-fly ()
19536 (when (and (equal (char-after (point-at-bol)) ?*)
19537 (org-at-heading-p))
19538 (org-align-tags-here org-tags-column)))
19540 (defun org-delete-backward-char (N)
19541 "Like `delete-backward-char', insert whitespace at field end in tables.
19542 When deleting backwards, in tables this function will insert whitespace in
19543 front of the next \"|\" separator, to keep the table aligned. The table will
19544 still be marked for re-alignment if the field did fill the entire column,
19545 because, in this case the deletion might narrow the column."
19546 (interactive "p")
19547 (save-match-data
19548 (org-check-before-invisible-edit 'delete-backward)
19549 (if (and (org-table-p)
19550 (eq N 1)
19551 (string-match "|" (buffer-substring (point-at-bol) (point)))
19552 (looking-at ".*?|"))
19553 (let ((pos (point))
19554 (noalign (looking-at "[^|\n\r]* |"))
19555 (c org-table-may-need-update))
19556 (backward-delete-char N)
19557 (if (not overwrite-mode)
19558 (progn
19559 (skip-chars-forward "^|")
19560 (insert " ")
19561 (goto-char (1- pos))))
19562 ;; noalign: if there were two spaces at the end, this field
19563 ;; does not determine the width of the column.
19564 (if noalign (setq org-table-may-need-update c)))
19565 (backward-delete-char N)
19566 (org-fix-tags-on-the-fly))))
19568 (defun org-delete-char (N)
19569 "Like `delete-char', but insert whitespace at field end in tables.
19570 When deleting characters, in tables this function will insert whitespace in
19571 front of the next \"|\" separator, to keep the table aligned. The table will
19572 still be marked for re-alignment if the field did fill the entire column,
19573 because, in this case the deletion might narrow the column."
19574 (interactive "p")
19575 (save-match-data
19576 (org-check-before-invisible-edit 'delete)
19577 (if (and (org-table-p)
19578 (not (bolp))
19579 (not (= (char-after) ?|))
19580 (eq N 1))
19581 (if (looking-at ".*?|")
19582 (let ((pos (point))
19583 (noalign (looking-at "[^|\n\r]* |"))
19584 (c org-table-may-need-update))
19585 (replace-match
19586 (concat (substring (match-string 0) 1 -1) " |") nil t)
19587 (goto-char pos)
19588 ;; noalign: if there were two spaces at the end, this field
19589 ;; does not determine the width of the column.
19590 (if noalign (setq org-table-may-need-update c)))
19591 (delete-char N))
19592 (delete-char N)
19593 (org-fix-tags-on-the-fly))))
19595 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19596 (put 'org-self-insert-command 'delete-selection
19597 (lambda ()
19598 (not (run-hook-with-args-until-success
19599 'self-insert-uses-region-functions))))
19600 (put 'orgtbl-self-insert-command 'delete-selection
19601 (lambda ()
19602 (not (run-hook-with-args-until-success
19603 'self-insert-uses-region-functions))))
19604 (put 'org-delete-char 'delete-selection 'supersede)
19605 (put 'org-delete-backward-char 'delete-selection 'supersede)
19606 (put 'org-yank 'delete-selection 'yank)
19608 ;; Make `flyspell-mode' delay after some commands
19609 (put 'org-self-insert-command 'flyspell-delayed t)
19610 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19611 (put 'org-delete-char 'flyspell-delayed t)
19612 (put 'org-delete-backward-char 'flyspell-delayed t)
19614 ;; Make pabbrev-mode expand after org-mode commands
19615 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19616 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19618 (defun org-remap (map &rest commands)
19619 "In MAP, remap the functions given in COMMANDS.
19620 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19621 (let (new old)
19622 (while commands
19623 (setq old (pop commands) new (pop commands))
19624 (if (fboundp 'command-remapping)
19625 (org-defkey map (vector 'remap old) new)
19626 (substitute-key-definition old new map global-map)))))
19628 (defun org-transpose-words ()
19629 "Transpose words for Org.
19630 This uses the `org-mode-transpose-word-syntax-table' syntax
19631 table, which interprets characters in `org-emphasis-alist' as
19632 word constituents."
19633 (interactive)
19634 (with-syntax-table org-mode-transpose-word-syntax-table
19635 (call-interactively 'transpose-words)))
19636 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19638 (when (eq org-enable-table-editor 'optimized)
19639 ;; If the user wants maximum table support, we need to hijack
19640 ;; some standard editing functions
19641 (org-remap org-mode-map
19642 'self-insert-command 'org-self-insert-command
19643 'delete-char 'org-delete-char
19644 'delete-backward-char 'org-delete-backward-char)
19645 (org-defkey org-mode-map "|" 'org-force-self-insert))
19647 (defvar org-ctrl-c-ctrl-c-hook nil
19648 "Hook for functions attaching themselves to `C-c C-c'.
19650 This can be used to add additional functionality to the C-c C-c
19651 key which executes context-dependent commands. This hook is run
19652 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19653 run after the last test.
19655 Each function will be called with no arguments. The function
19656 must check if the context is appropriate for it to act. If yes,
19657 it should do its thing and then return a non-nil value. If the
19658 context is wrong, just do nothing and return nil.")
19660 (defvar org-ctrl-c-ctrl-c-final-hook nil
19661 "Hook for functions attaching themselves to `C-c C-c'.
19663 This can be used to add additional functionality to the C-c C-c
19664 key which executes context-dependent commands. This hook is run
19665 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19666 before the first test.
19668 Each function will be called with no arguments. The function
19669 must check if the context is appropriate for it to act. If yes,
19670 it should do its thing and then return a non-nil value. If the
19671 context is wrong, just do nothing and return nil.")
19673 (defvar org-tab-first-hook nil
19674 "Hook for functions to attach themselves to TAB.
19675 See `org-ctrl-c-ctrl-c-hook' for more information.
19676 This hook runs as the first action when TAB is pressed, even before
19677 `org-cycle' messes around with the `outline-regexp' to cater for
19678 inline tasks and plain list item folding.
19679 If any function in this hook returns t, any other actions that
19680 would have been caused by TAB (such as table field motion or visibility
19681 cycling) will not occur.")
19683 (defvar org-tab-after-check-for-table-hook nil
19684 "Hook for functions to attach themselves to TAB.
19685 See `org-ctrl-c-ctrl-c-hook' for more information.
19686 This hook runs after it has been established that the cursor is not in a
19687 table, but before checking if the cursor is in a headline or if global cycling
19688 should be done.
19689 If any function in this hook returns t, not other actions like visibility
19690 cycling will be done.")
19692 (defvar org-tab-after-check-for-cycling-hook nil
19693 "Hook for functions to attach themselves to TAB.
19694 See `org-ctrl-c-ctrl-c-hook' for more information.
19695 This hook runs after it has been established that not table field motion and
19696 not visibility should be done because of current context. This is probably
19697 the place where a package like yasnippets can hook in.")
19699 (defvar org-tab-before-tab-emulation-hook nil
19700 "Hook for functions to attach themselves to TAB.
19701 See `org-ctrl-c-ctrl-c-hook' for more information.
19702 This hook runs after every other options for TAB have been exhausted, but
19703 before indentation and \t insertion takes place.")
19705 (defvar org-metaleft-hook nil
19706 "Hook for functions attaching themselves to `M-left'.
19707 See `org-ctrl-c-ctrl-c-hook' for more information.")
19708 (defvar org-metaright-hook nil
19709 "Hook for functions attaching themselves to `M-right'.
19710 See `org-ctrl-c-ctrl-c-hook' for more information.")
19711 (defvar org-metaup-hook nil
19712 "Hook for functions attaching themselves to `M-up'.
19713 See `org-ctrl-c-ctrl-c-hook' for more information.")
19714 (defvar org-metadown-hook nil
19715 "Hook for functions attaching themselves to `M-down'.
19716 See `org-ctrl-c-ctrl-c-hook' for more information.")
19717 (defvar org-shiftmetaleft-hook nil
19718 "Hook for functions attaching themselves to `M-S-left'.
19719 See `org-ctrl-c-ctrl-c-hook' for more information.")
19720 (defvar org-shiftmetaright-hook nil
19721 "Hook for functions attaching themselves to `M-S-right'.
19722 See `org-ctrl-c-ctrl-c-hook' for more information.")
19723 (defvar org-shiftmetaup-hook nil
19724 "Hook for functions attaching themselves to `M-S-up'.
19725 See `org-ctrl-c-ctrl-c-hook' for more information.")
19726 (defvar org-shiftmetadown-hook nil
19727 "Hook for functions attaching themselves to `M-S-down'.
19728 See `org-ctrl-c-ctrl-c-hook' for more information.")
19729 (defvar org-metareturn-hook nil
19730 "Hook for functions attaching themselves to `M-RET'.
19731 See `org-ctrl-c-ctrl-c-hook' for more information.")
19732 (defvar org-shiftup-hook nil
19733 "Hook for functions attaching themselves to `S-up'.
19734 See `org-ctrl-c-ctrl-c-hook' for more information.")
19735 (defvar org-shiftup-final-hook nil
19736 "Hook for functions attaching themselves to `S-up'.
19737 This one runs after all other options except shift-select have been excluded.
19738 See `org-ctrl-c-ctrl-c-hook' for more information.")
19739 (defvar org-shiftdown-hook nil
19740 "Hook for functions attaching themselves to `S-down'.
19741 See `org-ctrl-c-ctrl-c-hook' for more information.")
19742 (defvar org-shiftdown-final-hook nil
19743 "Hook for functions attaching themselves to `S-down'.
19744 This one runs after all other options except shift-select have been excluded.
19745 See `org-ctrl-c-ctrl-c-hook' for more information.")
19746 (defvar org-shiftleft-hook nil
19747 "Hook for functions attaching themselves to `S-left'.
19748 See `org-ctrl-c-ctrl-c-hook' for more information.")
19749 (defvar org-shiftleft-final-hook nil
19750 "Hook for functions attaching themselves to `S-left'.
19751 This one runs after all other options except shift-select have been excluded.
19752 See `org-ctrl-c-ctrl-c-hook' for more information.")
19753 (defvar org-shiftright-hook nil
19754 "Hook for functions attaching themselves to `S-right'.
19755 See `org-ctrl-c-ctrl-c-hook' for more information.")
19756 (defvar org-shiftright-final-hook nil
19757 "Hook for functions attaching themselves to `S-right'.
19758 This one runs after all other options except shift-select have been excluded.
19759 See `org-ctrl-c-ctrl-c-hook' for more information.")
19761 (defun org-modifier-cursor-error ()
19762 "Throw an error, a modified cursor command was applied in wrong context."
19763 (user-error "This command is active in special context like tables, headlines or items"))
19765 (defun org-shiftselect-error ()
19766 "Throw an error because Shift-Cursor command was applied in wrong context."
19767 (if (and (boundp 'shift-select-mode) shift-select-mode)
19768 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19769 (user-error "This command works only in special context like headlines or timestamps")))
19771 (defun org-call-for-shift-select (cmd)
19772 (let ((this-command-keys-shift-translated t))
19773 (call-interactively cmd)))
19775 (defun org-shifttab (&optional arg)
19776 "Global visibility cycling or move to previous table field.
19777 Call `org-table-previous-field' within a table.
19778 When ARG is nil, cycle globally through visibility states.
19779 When ARG is a numeric prefix, show contents of this level."
19780 (interactive "P")
19781 (cond
19782 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19783 ((integerp arg)
19784 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19785 (message "Content view to level: %d" arg)
19786 (org-content (prefix-numeric-value arg2))
19787 (org-cycle-show-empty-lines t)
19788 (setq org-cycle-global-status 'overview)))
19789 (t (call-interactively 'org-global-cycle))))
19791 (defun org-shiftmetaleft ()
19792 "Promote subtree or delete table column.
19793 Calls `org-promote-subtree', `org-outdent-item-tree', or
19794 `org-table-delete-column', depending on context. See the
19795 individual commands for more information."
19796 (interactive)
19797 (cond
19798 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19799 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19800 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19801 ((if (not (org-region-active-p)) (org-at-item-p)
19802 (save-excursion (goto-char (region-beginning))
19803 (org-at-item-p)))
19804 (call-interactively 'org-outdent-item-tree))
19805 (t (org-modifier-cursor-error))))
19807 (defun org-shiftmetaright ()
19808 "Demote subtree or insert table column.
19809 Calls `org-demote-subtree', `org-indent-item-tree', or
19810 `org-table-insert-column', depending on context. See the
19811 individual commands for more information."
19812 (interactive)
19813 (cond
19814 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19815 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19816 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19817 ((if (not (org-region-active-p)) (org-at-item-p)
19818 (save-excursion (goto-char (region-beginning))
19819 (org-at-item-p)))
19820 (call-interactively 'org-indent-item-tree))
19821 (t (org-modifier-cursor-error))))
19823 (defun org-shiftmetaup (&optional arg)
19824 "Move subtree up or kill table row.
19825 Calls `org-move-subtree-up' or `org-table-kill-row' or
19826 `org-move-item-up' or `org-timestamp-up', depending on context.
19827 See the individual commands for more information."
19828 (interactive "P")
19829 (cond
19830 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19831 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19832 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19833 ((org-at-item-p) (call-interactively 'org-move-item-up))
19834 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19835 (call-interactively 'org-timestamp-up)))
19836 (t (call-interactively 'org-drag-line-backward))))
19838 (defun org-shiftmetadown (&optional arg)
19839 "Move subtree down or insert table row.
19840 Calls `org-move-subtree-down' or `org-table-insert-row' or
19841 `org-move-item-down' or `org-timestamp-up', depending on context.
19842 See the individual commands for more information."
19843 (interactive "P")
19844 (cond
19845 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19846 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19847 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19848 ((org-at-item-p) (call-interactively 'org-move-item-down))
19849 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19850 (call-interactively 'org-timestamp-down)))
19851 (t (call-interactively 'org-drag-line-forward))))
19853 (defsubst org-hidden-tree-error ()
19854 (user-error
19855 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19857 (defun org-metaleft (&optional arg)
19858 "Promote heading or move table column to left.
19859 Calls `org-do-promote' or `org-table-move-column', depending on context.
19860 With no specific context, calls the Emacs default `backward-word'.
19861 See the individual commands for more information."
19862 (interactive "P")
19863 (cond
19864 ((run-hook-with-args-until-success 'org-metaleft-hook))
19865 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19866 ((org-with-limited-levels
19867 (or (org-at-heading-p)
19868 (and (org-region-active-p)
19869 (save-excursion
19870 (goto-char (region-beginning))
19871 (org-at-heading-p)))))
19872 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19873 (call-interactively 'org-do-promote))
19874 ;; At an inline task.
19875 ((org-at-heading-p)
19876 (call-interactively 'org-inlinetask-promote))
19877 ((or (org-at-item-p)
19878 (and (org-region-active-p)
19879 (save-excursion
19880 (goto-char (region-beginning))
19881 (org-at-item-p))))
19882 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19883 (call-interactively 'org-outdent-item))
19884 (t (call-interactively 'backward-word))))
19886 (defun org-metaright (&optional arg)
19887 "Demote a subtree, a list item or move table column to right.
19888 In front of a drawer or a block keyword, indent it correctly.
19889 With no specific context, calls the Emacs default `forward-word'.
19890 See the individual commands for more information."
19891 (interactive "P")
19892 (cond
19893 ((run-hook-with-args-until-success 'org-metaright-hook))
19894 ((org-at-table-p) (call-interactively 'org-table-move-column))
19895 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19896 ((org-at-block-p) (call-interactively 'org-indent-block))
19897 ((org-with-limited-levels
19898 (or (org-at-heading-p)
19899 (and (org-region-active-p)
19900 (save-excursion
19901 (goto-char (region-beginning))
19902 (org-at-heading-p)))))
19903 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19904 (call-interactively 'org-do-demote))
19905 ;; At an inline task.
19906 ((org-at-heading-p)
19907 (call-interactively 'org-inlinetask-demote))
19908 ((or (org-at-item-p)
19909 (and (org-region-active-p)
19910 (save-excursion
19911 (goto-char (region-beginning))
19912 (org-at-item-p))))
19913 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19914 (call-interactively 'org-indent-item))
19915 (t (call-interactively 'forward-word))))
19917 (defun org-check-for-hidden (what)
19918 "Check if there are hidden headlines/items in the current visual line.
19919 WHAT can be either `headlines' or `items'. If the current line is
19920 an outline or item heading and it has a folded subtree below it,
19921 this function returns t, nil otherwise."
19922 (let ((re (cond
19923 ((eq what 'headlines) org-outline-regexp-bol)
19924 ((eq what 'items) (org-item-beginning-re))
19925 (t (error "This should not happen"))))
19926 beg end)
19927 (save-excursion
19928 (catch 'exit
19929 (unless (org-region-active-p)
19930 (setq beg (point-at-bol))
19931 (beginning-of-line 2)
19932 (while (and (not (eobp)) ;; this is like `next-line'
19933 (get-char-property (1- (point)) 'invisible))
19934 (beginning-of-line 2))
19935 (setq end (point))
19936 (goto-char beg)
19937 (goto-char (point-at-eol))
19938 (setq end (max end (point)))
19939 (while (re-search-forward re end t)
19940 (if (get-char-property (match-beginning 0) 'invisible)
19941 (throw 'exit t))))
19942 nil))))
19944 (defun org-metaup (&optional arg)
19945 "Move subtree up or move table row up.
19946 Calls `org-move-subtree-up' or `org-table-move-row' or
19947 `org-move-item-up', depending on context. See the individual commands
19948 for more information."
19949 (interactive "P")
19950 (cond
19951 ((run-hook-with-args-until-success 'org-metaup-hook))
19952 ((org-region-active-p)
19953 (let* ((a (min (region-beginning) (region-end)))
19954 (b (1- (max (region-beginning) (region-end))))
19955 (c (save-excursion (goto-char a)
19956 (move-beginning-of-line 0)))
19957 (d (save-excursion (goto-char a)
19958 (move-end-of-line 0) (point))))
19959 (transpose-regions a b c d)
19960 (goto-char c)))
19961 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19962 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19963 ((org-at-item-p) (call-interactively 'org-move-item-up))
19964 (t (org-drag-element-backward))))
19966 (defun org-metadown (&optional arg)
19967 "Move subtree down or move table row down.
19968 Calls `org-move-subtree-down' or `org-table-move-row' or
19969 `org-move-item-down', depending on context. See the individual
19970 commands for more information."
19971 (interactive "P")
19972 (cond
19973 ((run-hook-with-args-until-success 'org-metadown-hook))
19974 ((org-region-active-p)
19975 (let* ((a (min (region-beginning) (region-end)))
19976 (b (max (region-beginning) (region-end)))
19977 (c (save-excursion (goto-char b)
19978 (move-beginning-of-line 1)))
19979 (d (save-excursion (goto-char b)
19980 (move-end-of-line 1) (1+ (point)))))
19981 (transpose-regions a b c d)
19982 (goto-char d)))
19983 ((org-at-table-p) (call-interactively 'org-table-move-row))
19984 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19985 ((org-at-item-p) (call-interactively 'org-move-item-down))
19986 (t (org-drag-element-forward))))
19988 (defun org-shiftup (&optional arg)
19989 "Increase item in timestamp or increase priority of current headline.
19990 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19991 depending on context. See the individual commands for more information."
19992 (interactive "P")
19993 (cond
19994 ((run-hook-with-args-until-success 'org-shiftup-hook))
19995 ((and org-support-shift-select (org-region-active-p))
19996 (org-call-for-shift-select 'previous-line))
19997 ((org-at-timestamp-p t)
19998 (call-interactively (if org-edit-timestamp-down-means-later
19999 'org-timestamp-down 'org-timestamp-up)))
20000 ((and (not (eq org-support-shift-select 'always))
20001 org-enable-priority-commands
20002 (org-at-heading-p))
20003 (call-interactively 'org-priority-up))
20004 ((and (not org-support-shift-select) (org-at-item-p))
20005 (call-interactively 'org-previous-item))
20006 ((org-clocktable-try-shift 'up arg))
20007 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20008 (org-support-shift-select
20009 (org-call-for-shift-select 'previous-line))
20010 (t (org-shiftselect-error))))
20012 (defun org-shiftdown (&optional arg)
20013 "Decrease item in timestamp or decrease priority of current headline.
20014 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20015 depending on context. See the individual commands for more information."
20016 (interactive "P")
20017 (cond
20018 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20019 ((and org-support-shift-select (org-region-active-p))
20020 (org-call-for-shift-select 'next-line))
20021 ((org-at-timestamp-p t)
20022 (call-interactively (if org-edit-timestamp-down-means-later
20023 'org-timestamp-up 'org-timestamp-down)))
20024 ((and (not (eq org-support-shift-select 'always))
20025 org-enable-priority-commands
20026 (org-at-heading-p))
20027 (call-interactively 'org-priority-down))
20028 ((and (not org-support-shift-select) (org-at-item-p))
20029 (call-interactively 'org-next-item))
20030 ((org-clocktable-try-shift 'down arg))
20031 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20032 (org-support-shift-select
20033 (org-call-for-shift-select 'next-line))
20034 (t (org-shiftselect-error))))
20036 (defun org-shiftright (&optional arg)
20037 "Cycle the thing at point or in the current line, depending on context.
20038 Depending on context, this does one of the following:
20040 - switch a timestamp at point one day into the future
20041 - on a headline, switch to the next TODO keyword.
20042 - on an item, switch entire list to the next bullet type
20043 - on a property line, switch to the next allowed value
20044 - on a clocktable definition line, move time block into the future"
20045 (interactive "P")
20046 (cond
20047 ((run-hook-with-args-until-success 'org-shiftright-hook))
20048 ((and org-support-shift-select (org-region-active-p))
20049 (org-call-for-shift-select 'forward-char))
20050 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20051 ((and (not (eq org-support-shift-select 'always))
20052 (org-at-heading-p))
20053 (let ((org-inhibit-logging
20054 (not org-treat-S-cursor-todo-selection-as-state-change))
20055 (org-inhibit-blocking
20056 (not org-treat-S-cursor-todo-selection-as-state-change)))
20057 (org-call-with-arg 'org-todo 'right)))
20058 ((or (and org-support-shift-select
20059 (not (eq org-support-shift-select 'always))
20060 (org-at-item-bullet-p))
20061 (and (not org-support-shift-select) (org-at-item-p)))
20062 (org-call-with-arg 'org-cycle-list-bullet nil))
20063 ((and (not (eq org-support-shift-select 'always))
20064 (org-at-property-p))
20065 (call-interactively 'org-property-next-allowed-value))
20066 ((org-clocktable-try-shift 'right arg))
20067 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20068 (org-support-shift-select
20069 (org-call-for-shift-select 'forward-char))
20070 (t (org-shiftselect-error))))
20072 (defun org-shiftleft (&optional arg)
20073 "Cycle the thing at point or in the current line, depending on context.
20074 Depending on context, this does one of the following:
20076 - switch a timestamp at point one day into the past
20077 - on a headline, switch to the previous TODO keyword.
20078 - on an item, switch entire list to the previous bullet type
20079 - on a property line, switch to the previous allowed value
20080 - on a clocktable definition line, move time block into the past"
20081 (interactive "P")
20082 (cond
20083 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20084 ((and org-support-shift-select (org-region-active-p))
20085 (org-call-for-shift-select 'backward-char))
20086 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20087 ((and (not (eq org-support-shift-select 'always))
20088 (org-at-heading-p))
20089 (let ((org-inhibit-logging
20090 (not org-treat-S-cursor-todo-selection-as-state-change))
20091 (org-inhibit-blocking
20092 (not org-treat-S-cursor-todo-selection-as-state-change)))
20093 (org-call-with-arg 'org-todo 'left)))
20094 ((or (and org-support-shift-select
20095 (not (eq org-support-shift-select 'always))
20096 (org-at-item-bullet-p))
20097 (and (not org-support-shift-select) (org-at-item-p)))
20098 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20099 ((and (not (eq org-support-shift-select 'always))
20100 (org-at-property-p))
20101 (call-interactively 'org-property-previous-allowed-value))
20102 ((org-clocktable-try-shift 'left arg))
20103 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20104 (org-support-shift-select
20105 (org-call-for-shift-select 'backward-char))
20106 (t (org-shiftselect-error))))
20108 (defun org-shiftcontrolright ()
20109 "Switch to next TODO set."
20110 (interactive)
20111 (cond
20112 ((and org-support-shift-select (org-region-active-p))
20113 (org-call-for-shift-select 'forward-word))
20114 ((and (not (eq org-support-shift-select 'always))
20115 (org-at-heading-p))
20116 (org-call-with-arg 'org-todo 'nextset))
20117 (org-support-shift-select
20118 (org-call-for-shift-select 'forward-word))
20119 (t (org-shiftselect-error))))
20121 (defun org-shiftcontrolleft ()
20122 "Switch to previous TODO set."
20123 (interactive)
20124 (cond
20125 ((and org-support-shift-select (org-region-active-p))
20126 (org-call-for-shift-select 'backward-word))
20127 ((and (not (eq org-support-shift-select 'always))
20128 (org-at-heading-p))
20129 (org-call-with-arg 'org-todo 'previousset))
20130 (org-support-shift-select
20131 (org-call-for-shift-select 'backward-word))
20132 (t (org-shiftselect-error))))
20134 (defun org-shiftcontrolup (&optional n)
20135 "Change timestamps synchronously up in CLOCK log lines.
20136 Optional argument N tells to change by that many units."
20137 (interactive "P")
20138 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20139 (let (org-support-shift-select)
20140 (org-clock-timestamps-up n))
20141 (user-error "Not at a clock log")))
20143 (defun org-shiftcontroldown (&optional n)
20144 "Change timestamps synchronously down in CLOCK log lines.
20145 Optional argument N tells to change by that many units."
20146 (interactive "P")
20147 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20148 (let (org-support-shift-select)
20149 (org-clock-timestamps-down n))
20150 (user-error "Not at a clock log")))
20152 (defun org-ctrl-c-ret ()
20153 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20154 (interactive)
20155 (cond
20156 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20157 (t (call-interactively 'org-insert-heading))))
20159 (defun org-find-visible ()
20160 (let ((s (point)))
20161 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20162 (get-char-property s 'invisible)))
20164 (defun org-find-invisible ()
20165 (let ((s (point)))
20166 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20167 (not (get-char-property s 'invisible))))
20170 (defun org-copy-visible (beg end)
20171 "Copy the visible parts of the region."
20172 (interactive "r")
20173 (let (snippets s)
20174 (save-excursion
20175 (save-restriction
20176 (narrow-to-region beg end)
20177 (setq s (goto-char (point-min)))
20178 (while (not (= (point) (point-max)))
20179 (goto-char (org-find-invisible))
20180 (push (buffer-substring s (point)) snippets)
20181 (setq s (goto-char (org-find-visible))))))
20182 (kill-new (apply 'concat (nreverse snippets)))))
20184 (defun org-copy-special ()
20185 "Copy region in table or copy current subtree.
20186 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20187 See the individual commands for more information."
20188 (interactive)
20189 (call-interactively
20190 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20192 (defun org-cut-special ()
20193 "Cut region in table or cut current subtree.
20194 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20195 See the individual commands for more information."
20196 (interactive)
20197 (call-interactively
20198 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20200 (defun org-paste-special (arg)
20201 "Paste rectangular region into table, or past subtree relative to level.
20202 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20203 See the individual commands for more information."
20204 (interactive "P")
20205 (if (org-at-table-p)
20206 (org-table-paste-rectangle)
20207 (org-paste-subtree arg)))
20209 (defsubst org-in-fixed-width-region-p ()
20210 "Is point in a fixed-width region?"
20211 (save-match-data
20212 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20214 (defun org-edit-special (&optional arg)
20215 "Call a special editor for the element at point.
20216 When at a table, call the formula editor with `org-table-edit-formulas'.
20217 When in a source code block, call `org-edit-src-code'.
20218 When in a fixed-width region, call `org-edit-fixed-width-region'.
20219 When at an #+INCLUDE keyword, visit the included file.
20220 On a link, call `ffap' to visit the link at point.
20221 Otherwise, return a user error."
20222 (interactive "P")
20223 (let ((element (org-element-at-point)))
20224 (assert (not buffer-read-only) nil
20225 "Buffer is read-only: %s" (buffer-name))
20226 (case (org-element-type element)
20227 (src-block
20228 (if (not arg) (org-edit-src-code)
20229 (let* ((info (org-babel-get-src-block-info))
20230 (lang (nth 0 info))
20231 (params (nth 2 info))
20232 (session (cdr (assq :session params))))
20233 (if (not session) (org-edit-src-code)
20234 ;; At a src-block with a session and function called with
20235 ;; an ARG: switch to the buffer related to the inferior
20236 ;; process.
20237 (switch-to-buffer
20238 (funcall (intern (concat "org-babel-prep-session:" lang))
20239 session params))))))
20240 (keyword
20241 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20242 (find-file
20243 (org-remove-double-quotes
20244 (car (org-split-string (org-element-property :value element)))))
20245 (user-error "No special environment to edit here")))
20246 (table
20247 (if (eq (org-element-property :type element) 'table.el)
20248 (org-edit-src-code)
20249 (call-interactively 'org-table-edit-formulas)))
20250 ;; Only Org tables contain `table-row' type elements.
20251 (table-row (call-interactively 'org-table-edit-formulas))
20252 ((example-block export-block) (org-edit-src-code))
20253 (fixed-width (org-edit-fixed-width-region))
20254 (otherwise
20255 ;; No notable element at point. Though, we may be at a link,
20256 ;; which is an object. Thus, scan deeper.
20257 (if (eq (org-element-type (org-element-context element)) 'link)
20258 (call-interactively 'ffap)
20259 (user-error "No special environment to edit here"))))))
20261 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20262 (defun org-ctrl-c-ctrl-c (&optional arg)
20263 "Set tags in headline, or update according to changed information at point.
20265 This command does many different things, depending on context:
20267 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20268 this is what we do.
20270 - If the cursor is on a statistics cookie, update it.
20272 - If the cursor is in a headline, prompt for tags and insert them
20273 into the current line, aligned to `org-tags-column'. When called
20274 with prefix arg, realign all tags in the current buffer.
20276 - If the cursor is in one of the special #+KEYWORD lines, this
20277 triggers scanning the buffer for these lines and updating the
20278 information.
20280 - If the cursor is inside a table, realign the table. This command
20281 works even if the automatic table editor has been turned off.
20283 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20284 the entire table.
20286 - If the cursor is at a footnote reference or definition, jump to
20287 the corresponding definition or references, respectively.
20289 - If the cursor is a the beginning of a dynamic block, update it.
20291 - If the current buffer is a capture buffer, close note and file it.
20293 - If the cursor is on a <<<target>>>, update radio targets and
20294 corresponding links in this buffer.
20296 - If the cursor is on a numbered item in a plain list, renumber the
20297 ordered list.
20299 - If the cursor is on a checkbox, toggle it.
20301 - If the cursor is on a code block, evaluate it. The variable
20302 `org-confirm-babel-evaluate' can be used to control prompting
20303 before code block evaluation, by default every code block
20304 evaluation requires confirmation. Code block evaluation can be
20305 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20306 (interactive "P")
20307 (cond
20308 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20309 org-occur-highlights
20310 org-latex-fragment-image-overlays)
20311 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20312 (org-remove-occur-highlights)
20313 (org-remove-latex-fragment-image-overlays)
20314 (message "Temporary highlights/overlays removed from current buffer"))
20315 ((and (local-variable-p 'org-finish-function (current-buffer))
20316 (fboundp org-finish-function))
20317 (funcall org-finish-function))
20318 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20320 (let* ((context (org-element-context)) (type (org-element-type context)))
20321 ;; Test if point is within a blank line.
20322 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20323 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20324 (user-error "C-c C-c can do nothing useful at this location"))
20325 (case type
20326 ;; When at a link, act according to the parent instead.
20327 (link (setq context (org-element-property :parent context))
20328 (setq type (org-element-type context)))
20329 ;; Unsupported object types: refer to the first supported
20330 ;; element or object containing it.
20331 ((bold code entity export-snippet inline-babel-call inline-src-block
20332 italic latex-fragment line-break macro strike-through subscript
20333 superscript underline verbatim)
20334 (while (and (setq context (org-element-property :parent context))
20335 (not (memq (setq type (org-element-type context))
20336 '(radio-target paragraph verse-block
20337 table-cell)))))))
20338 ;; For convenience: at the first line of a paragraph on the
20339 ;; same line as an item, apply function on that item instead.
20340 (when (eq type 'paragraph)
20341 (let ((parent (org-element-property :parent context)))
20342 (when (and (eq (org-element-type parent) 'item)
20343 (= (point-at-bol) (org-element-property :begin parent)))
20344 (setq context parent type 'item))))
20345 ;; Act according to type of element or object at point.
20346 (case type
20347 (clock (org-clock-update-time-maybe))
20348 (dynamic-block
20349 (save-excursion
20350 (goto-char (org-element-property :post-affiliated context))
20351 (org-update-dblock)))
20352 (footnote-definition
20353 (goto-char (org-element-property :post-affiliated context))
20354 (call-interactively 'org-footnote-action))
20355 (footnote-reference (call-interactively 'org-footnote-action))
20356 ((headline inlinetask)
20357 (save-excursion (goto-char (org-element-property :begin context))
20358 (call-interactively 'org-set-tags)))
20359 (item
20360 ;; At an item: a double C-u set checkbox to "[-]"
20361 ;; unconditionally, whereas a single one will toggle its
20362 ;; presence. Without a universal argument, if the item
20363 ;; has a checkbox, toggle it. Otherwise repair the list.
20364 (let* ((box (org-element-property :checkbox context))
20365 (struct (org-element-property :structure context))
20366 (old-struct (copy-tree struct))
20367 (parents (org-list-parents-alist struct))
20368 (prevs (org-list-prevs-alist struct))
20369 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20370 (org-list-set-checkbox
20371 (org-element-property :begin context) struct
20372 (cond ((equal arg '(16)) "[-]")
20373 ((and (not box) (equal arg '(4))) "[ ]")
20374 ((or (not box) (equal arg '(4))) nil)
20375 ((eq box 'on) "[ ]")
20376 (t "[X]")))
20377 ;; Mimic `org-list-write-struct' but with grabbing
20378 ;; a return value from `org-list-struct-fix-box'.
20379 (org-list-struct-fix-ind struct parents 2)
20380 (org-list-struct-fix-item-end struct)
20381 (org-list-struct-fix-bul struct prevs)
20382 (org-list-struct-fix-ind struct parents)
20383 (let ((block-item
20384 (org-list-struct-fix-box struct parents prevs orderedp)))
20385 (if (and box (equal struct old-struct))
20386 (if (equal arg '(16))
20387 (message "Checkboxes already reset")
20388 (user-error "Cannot toggle this checkbox: %s"
20389 (if (eq box 'on)
20390 "all subitems checked"
20391 "unchecked subitems")))
20392 (org-list-struct-apply-struct struct old-struct)
20393 (org-update-checkbox-count-maybe))
20394 (when block-item
20395 (message "Checkboxes were removed due to empty box at line %d"
20396 (org-current-line block-item))))))
20397 (keyword
20398 (let ((org-inhibit-startup-visibility-stuff t)
20399 (org-startup-align-all-tables nil))
20400 (when (boundp 'org-table-coordinate-overlays)
20401 (mapc 'delete-overlay org-table-coordinate-overlays)
20402 (setq org-table-coordinate-overlays nil))
20403 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20404 (message "Local setup has been refreshed"))
20405 (plain-list
20406 ;; At a plain list, with a double C-u argument, set
20407 ;; checkboxes of each item to "[-]", whereas a single one
20408 ;; will toggle their presence according to the state of the
20409 ;; first item in the list. Without an argument, repair the
20410 ;; list.
20411 (let* ((begin (org-element-property :contents-begin context))
20412 (beginm (move-marker (make-marker) begin))
20413 (struct (org-element-property :structure context))
20414 (old-struct (copy-tree struct))
20415 (first-box (save-excursion
20416 (goto-char begin)
20417 (looking-at org-list-full-item-re)
20418 (match-string-no-properties 3)))
20419 (new-box (cond ((equal arg '(16)) "[-]")
20420 ((equal arg '(4)) (unless first-box "[ ]"))
20421 ((equal first-box "[X]") "[ ]")
20422 (t "[X]"))))
20423 (cond
20424 (arg
20425 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20426 (org-list-get-all-items
20427 begin struct (org-list-prevs-alist struct))))
20428 ((and first-box (eq (point) begin))
20429 ;; For convenience, when point is at bol on the first
20430 ;; item of the list and no argument is provided, simply
20431 ;; toggle checkbox of that item, if any.
20432 (org-list-set-checkbox begin struct new-box)))
20433 (org-list-write-struct
20434 struct (org-list-parents-alist struct) old-struct)
20435 (org-update-checkbox-count-maybe)
20436 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20437 ((property-drawer node-property)
20438 (call-interactively 'org-property-action))
20439 ((radio-target target)
20440 (call-interactively 'org-update-radio-target-regexp))
20441 (statistics-cookie
20442 (call-interactively 'org-update-statistics-cookies))
20443 ((table table-cell table-row)
20444 ;; At a table, recalculate every field and align it. Also
20445 ;; send the table if necessary. If the table has
20446 ;; a `table.el' type, just give up. At a table row or
20447 ;; cell, maybe recalculate line but always align table.
20448 (if (eq (org-element-property :type context) 'table.el)
20449 (message "%s" "Use C-c ' to edit table.el tables")
20450 (let ((org-enable-table-editor t))
20451 (if (or (eq type 'table)
20452 ;; Check if point is at a TBLFM line.
20453 (and (eq type 'table-row)
20454 (= (point) (org-element-property :end context))))
20455 (save-excursion
20456 (if (org-at-TBLFM-p)
20457 (progn (require 'org-table)
20458 (org-table-calc-current-TBLFM))
20459 (goto-char (org-element-property :contents-begin context))
20460 (org-call-with-arg 'org-table-recalculate (or arg t))
20461 (orgtbl-send-table 'maybe)))
20462 (org-table-maybe-eval-formula)
20463 (cond (arg (call-interactively 'org-table-recalculate))
20464 ((org-table-maybe-recalculate-line))
20465 (t (org-table-align)))))))
20466 (timestamp (org-timestamp-change 0 'day))
20467 (otherwise
20468 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20469 (user-error
20470 "C-c C-c can do nothing useful at this location")))))))))
20472 (defun org-mode-restart ()
20473 (interactive)
20474 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20475 (funcall major-mode)
20476 (hack-local-variables)
20477 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20478 (org-indent-mode -1)))
20479 (message "%s restarted" major-mode))
20481 (defun org-kill-note-or-show-branches ()
20482 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20483 (interactive)
20484 (if (not org-finish-function)
20485 (progn
20486 (hide-subtree)
20487 (call-interactively 'show-branches))
20488 (let ((org-note-abort t))
20489 (funcall org-finish-function))))
20491 (defun org-open-line (n)
20492 "Insert a new row in tables, call `open-line' elsewhere.
20493 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20494 (interactive "*p")
20495 (cond
20496 ((not org-special-ctrl-o)
20497 (open-line n))
20498 ((org-at-table-p)
20499 (org-table-insert-row))
20501 (open-line n))))
20503 (defun org-return (&optional indent)
20504 "Goto next table row or insert a newline.
20505 Calls `org-table-next-row' or `newline', depending on context.
20506 See the individual commands for more information."
20507 (interactive)
20508 (let (org-ts-what)
20509 (cond
20510 ((or (bobp) (org-in-src-block-p))
20511 (if indent (newline-and-indent) (newline)))
20512 ((org-at-table-p)
20513 (org-table-justify-field-maybe)
20514 (call-interactively 'org-table-next-row))
20515 ;; when `newline-and-indent' is called within a list, make sure
20516 ;; text moved stays inside the item.
20517 ((and (org-in-item-p) indent)
20518 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20519 (progn
20520 (save-match-data (newline))
20521 (org-indent-line-to (length (match-string 0))))
20522 (let ((ind (org-get-indentation)))
20523 (newline)
20524 (if (org-looking-back org-list-end-re)
20525 (org-indent-line)
20526 (org-indent-line-to ind)))))
20527 ((and org-return-follows-link
20528 (org-at-timestamp-p t)
20529 (not (eq org-ts-what 'after)))
20530 (org-follow-timestamp-link))
20531 ((and org-return-follows-link
20532 (let ((tprop (get-text-property (point) 'face)))
20533 (or (eq tprop 'org-link)
20534 (and (listp tprop) (memq 'org-link tprop)))))
20535 (call-interactively 'org-open-at-point))
20536 ((and (org-at-heading-p)
20537 (looking-at
20538 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20539 (org-show-entry)
20540 (end-of-line 1)
20541 (newline))
20542 (t (if indent (newline-and-indent) (newline))))))
20544 (defun org-return-indent ()
20545 "Goto next table row or insert a newline and indent.
20546 Calls `org-table-next-row' or `newline-and-indent', depending on
20547 context. See the individual commands for more information."
20548 (interactive)
20549 (org-return t))
20551 (defun org-ctrl-c-star ()
20552 "Compute table, or change heading status of lines.
20553 Calls `org-table-recalculate' or `org-toggle-heading',
20554 depending on context."
20555 (interactive)
20556 (cond
20557 ((org-at-table-p)
20558 (call-interactively 'org-table-recalculate))
20560 ;; Convert all lines in region to list items
20561 (call-interactively 'org-toggle-heading))))
20563 (defun org-ctrl-c-minus ()
20564 "Insert separator line in table or modify bullet status of line.
20565 Also turns a plain line or a region of lines into list items.
20566 Calls `org-table-insert-hline', `org-toggle-item', or
20567 `org-cycle-list-bullet', depending on context."
20568 (interactive)
20569 (cond
20570 ((org-at-table-p)
20571 (call-interactively 'org-table-insert-hline))
20572 ((org-region-active-p)
20573 (call-interactively 'org-toggle-item))
20574 ((org-in-item-p)
20575 (call-interactively 'org-cycle-list-bullet))
20577 (call-interactively 'org-toggle-item))))
20579 (defun org-toggle-item (arg)
20580 "Convert headings or normal lines to items, items to normal lines.
20581 If there is no active region, only the current line is considered.
20583 If the first non blank line in the region is a headline, convert
20584 all headlines to items, shifting text accordingly.
20586 If it is an item, convert all items to normal lines.
20588 If it is normal text, change region into a list of items.
20589 With a prefix argument ARG, change the region in a single item."
20590 (interactive "P")
20591 (let ((shift-text
20592 (function
20593 ;; Shift text in current section to IND, from point to END.
20594 ;; The function leaves point to END line.
20595 (lambda (ind end)
20596 (let ((min-i 1000) (end (copy-marker end)))
20597 ;; First determine the minimum indentation (MIN-I) of
20598 ;; the text.
20599 (save-excursion
20600 (catch 'exit
20601 (while (< (point) end)
20602 (let ((i (org-get-indentation)))
20603 (cond
20604 ;; Skip blank lines and inline tasks.
20605 ((looking-at "^[ \t]*$"))
20606 ((looking-at org-outline-regexp-bol))
20607 ;; We can't find less than 0 indentation.
20608 ((zerop i) (throw 'exit (setq min-i 0)))
20609 ((< i min-i) (setq min-i i))))
20610 (forward-line))))
20611 ;; Then indent each line so that a line indented to
20612 ;; MIN-I becomes indented to IND. Ignore blank lines
20613 ;; and inline tasks in the process.
20614 (let ((delta (- ind min-i)))
20615 (while (< (point) end)
20616 (unless (or (looking-at "^[ \t]*$")
20617 (looking-at org-outline-regexp-bol))
20618 (org-indent-line-to (+ (org-get-indentation) delta)))
20619 (forward-line)))))))
20620 (skip-blanks
20621 (function
20622 ;; Return beginning of first non-blank line, starting from
20623 ;; line at POS.
20624 (lambda (pos)
20625 (save-excursion
20626 (goto-char pos)
20627 (skip-chars-forward " \r\t\n")
20628 (point-at-bol)))))
20629 beg end)
20630 ;; Determine boundaries of changes.
20631 (if (org-region-active-p)
20632 (setq beg (funcall skip-blanks (region-beginning))
20633 end (copy-marker (region-end)))
20634 (setq beg (funcall skip-blanks (point-at-bol))
20635 end (copy-marker (point-at-eol))))
20636 ;; Depending on the starting line, choose an action on the text
20637 ;; between BEG and END.
20638 (org-with-limited-levels
20639 (save-excursion
20640 (goto-char beg)
20641 (cond
20642 ;; Case 1. Start at an item: de-itemize. Note that it only
20643 ;; happens when a region is active: `org-ctrl-c-minus'
20644 ;; would call `org-cycle-list-bullet' otherwise.
20645 ((org-at-item-p)
20646 (while (< (point) end)
20647 (when (org-at-item-p)
20648 (skip-chars-forward " \t")
20649 (delete-region (point) (match-end 0)))
20650 (forward-line)))
20651 ;; Case 2. Start at an heading: convert to items.
20652 ((org-at-heading-p)
20653 (let* ((bul (org-list-bullet-string "-"))
20654 (bul-len (length bul))
20655 ;; Indentation of the first heading. It should be
20656 ;; relative to the indentation of its parent, if any.
20657 (start-ind (save-excursion
20658 (cond
20659 ((not org-adapt-indentation) 0)
20660 ((not (outline-previous-heading)) 0)
20661 (t (length (match-string 0))))))
20662 ;; Level of first heading. Further headings will be
20663 ;; compared to it to determine hierarchy in the list.
20664 (ref-level (org-reduced-level (org-outline-level))))
20665 (while (< (point) end)
20666 (let* ((level (org-reduced-level (org-outline-level)))
20667 (delta (max 0 (- level ref-level))))
20668 ;; If current headline is less indented than the first
20669 ;; one, set it as reference, in order to preserve
20670 ;; subtrees.
20671 (when (< level ref-level) (setq ref-level level))
20672 (replace-match bul t t)
20673 (org-indent-line-to (+ start-ind (* delta bul-len)))
20674 ;; Ensure all text down to END (or SECTION-END) belongs
20675 ;; to the newly created item.
20676 (let ((section-end (save-excursion
20677 (or (outline-next-heading) (point)))))
20678 (forward-line)
20679 (funcall shift-text
20680 (+ start-ind (* (1+ delta) bul-len))
20681 (min end section-end)))))))
20682 ;; Case 3. Normal line with ARG: make the first line of region
20683 ;; an item, and shift indentation of others lines to
20684 ;; set them as item's body.
20685 (arg (let* ((bul (org-list-bullet-string "-"))
20686 (bul-len (length bul))
20687 (ref-ind (org-get-indentation)))
20688 (skip-chars-forward " \t")
20689 (insert bul)
20690 (forward-line)
20691 (while (< (point) end)
20692 ;; Ensure that lines less indented than first one
20693 ;; still get included in item body.
20694 (funcall shift-text
20695 (+ ref-ind bul-len)
20696 (min end (save-excursion (or (outline-next-heading)
20697 (point)))))
20698 (forward-line))))
20699 ;; Case 4. Normal line without ARG: turn each non-item line
20700 ;; into an item.
20702 (while (< (point) end)
20703 (unless (or (org-at-heading-p) (org-at-item-p))
20704 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20705 (replace-match
20706 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20707 (forward-line))))))))
20709 (defun org-toggle-heading (&optional nstars)
20710 "Convert headings to normal text, or items or text to headings.
20711 If there is no active region, only convert the current line.
20713 With a \\[universal-argument] prefix, convert the whole list at
20714 point into heading.
20716 In a region:
20718 - If the first non blank line is a headline, remove the stars
20719 from all headlines in the region.
20721 - If it is a normal line, turn each and every normal line (i.e.,
20722 not an heading or an item) in the region into headings. If you
20723 want to convert only the first line of this region, use one
20724 universal prefix argument.
20726 - If it is a plain list item, turn all plain list items into headings.
20728 When converting a line into a heading, the number of stars is chosen
20729 such that the lines become children of the current entry. However,
20730 when a numeric prefix argument is given, its value determines the
20731 number of stars to add."
20732 (interactive "P")
20733 (let ((skip-blanks
20734 (function
20735 ;; Return beginning of first non-blank line, starting from
20736 ;; line at POS.
20737 (lambda (pos)
20738 (save-excursion
20739 (goto-char pos)
20740 (while (org-at-comment-p) (forward-line))
20741 (skip-chars-forward " \r\t\n")
20742 (point-at-bol)))))
20743 beg end toggled)
20744 ;; Determine boundaries of changes. If a universal prefix has
20745 ;; been given, put the list in a region. If region ends at a bol,
20746 ;; do not consider the last line to be in the region.
20748 (when (and current-prefix-arg (org-at-item-p))
20749 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20750 (org-mark-element))
20752 (if (org-region-active-p)
20753 (setq beg (funcall skip-blanks (region-beginning))
20754 end (copy-marker (save-excursion
20755 (goto-char (region-end))
20756 (if (bolp) (point) (point-at-eol)))))
20757 (setq beg (funcall skip-blanks (point-at-bol))
20758 end (copy-marker (point-at-eol))))
20759 ;; Ensure inline tasks don't count as headings.
20760 (org-with-limited-levels
20761 (save-excursion
20762 (goto-char beg)
20763 (cond
20764 ;; Case 1. Started at an heading: de-star headings.
20765 ((org-at-heading-p)
20766 (while (< (point) end)
20767 (when (org-at-heading-p t)
20768 (looking-at org-outline-regexp) (replace-match "")
20769 (setq toggled t))
20770 (forward-line)))
20771 ;; Case 2. Started at an item: change items into headlines.
20772 ;; One star will be added by `org-list-to-subtree'.
20773 ((org-at-item-p)
20774 (let* ((stars (make-string
20775 ;; subtract the star that will be added again by
20776 ;; `org-list-to-subtree'
20777 (if (numberp nstars) (1- nstars)
20778 (or (org-current-level) 0))
20779 ?*))
20780 (add-stars
20781 (cond (nstars "") ; stars from prefix only
20782 ((equal stars "") "") ; before first heading
20783 (org-odd-levels-only "*") ; inside heading, odd
20784 (t "")))) ; inside heading, oddeven
20785 (while (< (point) end)
20786 (when (org-at-item-p)
20787 ;; Pay attention to cases when region ends before list.
20788 (let* ((struct (org-list-struct))
20789 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20790 (save-restriction
20791 (narrow-to-region (point) list-end)
20792 (insert
20793 (org-list-to-subtree
20794 (org-list-parse-list t)
20795 `(:istart (concat ',stars ',add-stars (funcall get-stars depth))
20796 :icount (concat ',stars ',add-stars (funcall get-stars depth)))))))
20797 (setq toggled t))
20798 (forward-line))))
20799 ;; Case 3. Started at normal text: make every line an heading,
20800 ;; skipping headlines and items.
20801 (t (let* ((stars
20802 (make-string
20803 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20804 (add-stars
20805 (cond (nstars "") ; stars from prefix only
20806 ((equal stars "") "*") ; before first heading
20807 (org-odd-levels-only "**") ; inside heading, odd
20808 (t "*"))) ; inside heading, oddeven
20809 (rpl (concat stars add-stars " "))
20810 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20811 (while (< (point) (if (equal nstars '(4)) lend end))
20812 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20813 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20814 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20815 (forward-line)))))))
20816 (unless toggled (message "Cannot toggle heading from here"))))
20818 (defun org-meta-return (&optional _arg)
20819 "Insert a new heading or wrap a region in a table.
20820 Calls `org-insert-heading' or `org-table-wrap-region', depending
20821 on context. See the individual commands for more information."
20822 (interactive)
20823 (org-check-before-invisible-edit 'insert)
20824 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20825 (let* ((element (org-element-at-point))
20826 (type (org-element-type element)))
20827 (when (eq type 'table-row)
20828 (setq element (org-element-property :parent element))
20829 (setq type 'table))
20830 (if (and (eq type 'table)
20831 (eq (org-element-property :type element) 'org)
20832 (>= (point) (org-element-property :contents-begin element))
20833 (< (point) (org-element-property :contents-end element)))
20834 (call-interactively 'org-table-wrap-region)
20835 (call-interactively 'org-insert-heading)))))
20837 ;;; Menu entries
20839 (defsubst org-in-subtree-not-table-p ()
20840 "Are we in a subtree and not in a table?"
20841 (and (not (org-before-first-heading-p))
20842 (not (org-at-table-p))))
20844 ;; Define the Org-mode menus
20845 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20846 '("Tbl"
20847 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20848 ["Next Field" org-cycle (org-at-table-p)]
20849 ["Previous Field" org-shifttab (org-at-table-p)]
20850 ["Next Row" org-return (org-at-table-p)]
20851 "--"
20852 ["Blank Field" org-table-blank-field (org-at-table-p)]
20853 ["Edit Field" org-table-edit-field (org-at-table-p)]
20854 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20855 "--"
20856 ("Column"
20857 ["Move Column Left" org-metaleft (org-at-table-p)]
20858 ["Move Column Right" org-metaright (org-at-table-p)]
20859 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20860 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20861 ("Row"
20862 ["Move Row Up" org-metaup (org-at-table-p)]
20863 ["Move Row Down" org-metadown (org-at-table-p)]
20864 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20865 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20866 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20867 "--"
20868 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20869 ("Rectangle"
20870 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20871 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20872 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20873 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20874 "--"
20875 ("Calculate"
20876 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20877 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20878 ["Edit Formulas" org-edit-special (org-at-table-p)]
20879 "--"
20880 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20881 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20882 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20883 "--"
20884 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20885 "--"
20886 ["Sum Column/Rectangle" org-table-sum
20887 (or (org-at-table-p) (org-region-active-p))]
20888 ["Which Column?" org-table-current-column (org-at-table-p)])
20889 ["Debug Formulas"
20890 org-table-toggle-formula-debugger
20891 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20892 ["Show Col/Row Numbers"
20893 org-table-toggle-coordinate-overlays
20894 :style toggle
20895 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20896 "--"
20897 ["Create" org-table-create (and (not (org-at-table-p))
20898 org-enable-table-editor)]
20899 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20900 ["Import from File" org-table-import (not (org-at-table-p))]
20901 ["Export to File" org-table-export (org-at-table-p)]
20902 "--"
20903 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20905 (easy-menu-define org-org-menu org-mode-map "Org menu"
20906 '("Org"
20907 ("Show/Hide"
20908 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20909 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20910 ["Sparse Tree..." org-sparse-tree t]
20911 ["Reveal Context" org-reveal t]
20912 ["Show All" show-all t]
20913 "--"
20914 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20915 "--"
20916 ["New Heading" org-insert-heading t]
20917 ("Navigate Headings"
20918 ["Up" outline-up-heading t]
20919 ["Next" outline-next-visible-heading t]
20920 ["Previous" outline-previous-visible-heading t]
20921 ["Next Same Level" outline-forward-same-level t]
20922 ["Previous Same Level" outline-backward-same-level t]
20923 "--"
20924 ["Jump" org-goto t])
20925 ("Edit Structure"
20926 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20927 "--"
20928 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20929 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20930 "--"
20931 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20932 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20933 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20934 "--"
20935 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20936 "--"
20937 ["Copy visible text" org-copy-visible t]
20938 "--"
20939 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20940 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20941 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20942 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20943 "--"
20944 ["Sort Region/Children" org-sort t]
20945 "--"
20946 ["Convert to odd levels" org-convert-to-odd-levels t]
20947 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20948 ("Editing"
20949 ["Emphasis..." org-emphasize t]
20950 ["Edit Source Example" org-edit-special t]
20951 "--"
20952 ["Footnote new/jump" org-footnote-action t]
20953 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20954 ("Archive"
20955 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20956 "--"
20957 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20958 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20959 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20961 "--"
20962 ("Hyperlinks"
20963 ["Store Link (Global)" org-store-link t]
20964 ["Find existing link to here" org-occur-link-in-agenda-files t]
20965 ["Insert Link" org-insert-link t]
20966 ["Follow Link" org-open-at-point t]
20967 "--"
20968 ["Next link" org-next-link t]
20969 ["Previous link" org-previous-link t]
20970 "--"
20971 ["Descriptive Links"
20972 org-toggle-link-display
20973 :style radio
20974 :selected org-descriptive-links
20976 ["Literal Links"
20977 org-toggle-link-display
20978 :style radio
20979 :selected (not org-descriptive-links)])
20980 "--"
20981 ("TODO Lists"
20982 ["TODO/DONE/-" org-todo t]
20983 ("Select keyword"
20984 ["Next keyword" org-shiftright (org-at-heading-p)]
20985 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20986 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20987 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20988 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20989 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20990 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20991 "--"
20992 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20993 :selected org-enforce-todo-dependencies :style toggle :active t]
20994 "Settings for tree at point"
20995 ["Do Children sequentially" org-toggle-ordered-property :style radio
20996 :selected (org-entry-get nil "ORDERED")
20997 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20998 ["Do Children parallel" org-toggle-ordered-property :style radio
20999 :selected (not (org-entry-get nil "ORDERED"))
21000 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21001 "--"
21002 ["Set Priority" org-priority t]
21003 ["Priority Up" org-shiftup t]
21004 ["Priority Down" org-shiftdown t]
21005 "--"
21006 ["Get news from all feeds" org-feed-update-all t]
21007 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21008 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21009 ("TAGS and Properties"
21010 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21011 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21012 "--"
21013 ["Set property" org-set-property (not (org-before-first-heading-p))]
21014 ["Column view of properties" org-columns t]
21015 ["Insert Column View DBlock" org-insert-columns-dblock t])
21016 ("Dates and Scheduling"
21017 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21018 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21019 ("Change Date"
21020 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21021 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21022 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21023 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21024 ["Compute Time Range" org-evaluate-time-range t]
21025 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21026 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21027 "--"
21028 ["Custom time format" org-toggle-time-stamp-overlays
21029 :style radio :selected org-display-custom-times]
21030 "--"
21031 ["Goto Calendar" org-goto-calendar t]
21032 ["Date from Calendar" org-date-from-calendar t]
21033 "--"
21034 ["Start/Restart Timer" org-timer-start t]
21035 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21036 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21037 ["Insert Timer String" org-timer t]
21038 ["Insert Timer Item" org-timer-item t])
21039 ("Logging work"
21040 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21041 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21042 ["Clock out" org-clock-out t]
21043 ["Clock cancel" org-clock-cancel t]
21044 "--"
21045 ["Mark as default task" org-clock-mark-default-task t]
21046 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21047 ["Goto running clock" org-clock-goto t]
21048 "--"
21049 ["Display times" org-clock-display t]
21050 ["Create clock table" org-clock-report t]
21051 "--"
21052 ["Record DONE time"
21053 (progn (setq org-log-done (not org-log-done))
21054 (message "Switching to %s will %s record a timestamp"
21055 (car org-done-keywords)
21056 (if org-log-done "automatically" "not")))
21057 :style toggle :selected org-log-done])
21058 "--"
21059 ["Agenda Command..." org-agenda t]
21060 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21061 ("File List for Agenda")
21062 ("Special views current file"
21063 ["TODO Tree" org-show-todo-tree t]
21064 ["Check Deadlines" org-check-deadlines t]
21065 ["Timeline" org-timeline t]
21066 ["Tags/Property tree" org-match-sparse-tree t])
21067 "--"
21068 ["Export/Publish..." org-export-dispatch t]
21069 ("LaTeX"
21070 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21071 :selected org-cdlatex-mode]
21072 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21073 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21074 ["Modify math symbol" org-cdlatex-math-modify
21075 (org-inside-LaTeX-fragment-p)]
21076 ["Insert citation" org-reftex-citation t]
21077 "--"
21078 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21079 "--"
21080 ("MobileOrg"
21081 ["Push Files and Views" org-mobile-push t]
21082 ["Get Captured and Flagged" org-mobile-pull t]
21083 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21084 "--"
21085 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21086 "--"
21087 ("Documentation"
21088 ["Show Version" org-version t]
21089 ["Info Documentation" org-info t])
21090 ("Customize"
21091 ["Browse Org Group" org-customize t]
21092 "--"
21093 ["Expand This Menu" org-create-customize-menu
21094 (fboundp 'customize-menu-create)])
21095 ["Send bug report" org-submit-bug-report t]
21096 "--"
21097 ("Refresh/Reload"
21098 ["Refresh setup current buffer" org-mode-restart t]
21099 ["Reload Org (after update)" org-reload t]
21100 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21103 (defun org-info (&optional node)
21104 "Read documentation for Org-mode in the info system.
21105 With optional NODE, go directly to that node."
21106 (interactive)
21107 (info (format "(org)%s" (or node ""))))
21109 ;;;###autoload
21110 (defun org-submit-bug-report ()
21111 "Submit a bug report on Org-mode via mail.
21113 Don't hesitate to report any problems or inaccurate documentation.
21115 If you don't have setup sending mail from (X)Emacs, please copy the
21116 output buffer into your mail program, as it gives us important
21117 information about your Org-mode version and configuration."
21118 (interactive)
21119 (require 'reporter)
21120 (defvar reporter-prompt-for-summary-p)
21121 (org-load-modules-maybe)
21122 (org-require-autoloaded-modules)
21123 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21124 (reporter-submit-bug-report
21125 "emacs-orgmode@gnu.org"
21126 (org-version nil 'full)
21127 (let (list)
21128 (save-window-excursion
21129 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21130 (delete-other-windows)
21131 (erase-buffer)
21132 (insert "You are about to submit a bug report to the Org-mode mailing list.
21134 We would like to add your full Org-mode and Outline configuration to the
21135 bug report. This greatly simplifies the work of the maintainer and
21136 other experts on the mailing list.
21138 HOWEVER, some variables you have customized may contain private
21139 information. The names of customers, colleagues, or friends, might
21140 appear in the form of file names, tags, todo states, or search strings.
21141 If you answer yes to the prompt, you might want to check and remove
21142 such private information before sending the email.")
21143 (add-text-properties (point-min) (point-max) '(face org-warning))
21144 (when (yes-or-no-p "Include your Org-mode configuration ")
21145 (mapatoms
21146 (lambda (v)
21147 (and (boundp v)
21148 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21149 (or (and (symbol-value v)
21150 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21151 (and
21152 (get v 'custom-type) (get v 'standard-value)
21153 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21154 (push v list)))))
21155 (kill-buffer (get-buffer "*Warn about privacy*"))
21156 list))
21157 nil nil
21158 "Remember to cover the basics, that is, what you expected to happen and
21159 what in fact did happen. You don't know how to make a good report? See
21161 http://orgmode.org/manual/Feedback.html#Feedback
21163 Your bug report will be posted to the Org-mode mailing list.
21164 ------------------------------------------------------------------------")
21165 (save-excursion
21166 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21167 (replace-match "\\1Bug: \\3 [\\2]")))))
21170 (defun org-install-agenda-files-menu ()
21171 (let ((bl (buffer-list)))
21172 (save-excursion
21173 (while bl
21174 (set-buffer (pop bl))
21175 (if (derived-mode-p 'org-mode) (setq bl nil)))
21176 (when (derived-mode-p 'org-mode)
21177 (easy-menu-change
21178 '("Org") "File List for Agenda"
21179 (append
21180 (list
21181 ["Edit File List" (org-edit-agenda-file-list) t]
21182 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21183 ["Remove Current File from List" org-remove-file t]
21184 ["Cycle through agenda files" org-cycle-agenda-files t]
21185 ["Occur in all agenda files" org-occur-in-agenda-files t]
21186 "--")
21187 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21189 ;;;; Documentation
21191 (defun org-require-autoloaded-modules ()
21192 (interactive)
21193 (mapc 'require
21194 '(org-agenda org-archive org-attach org-clock org-colview org-id
21195 org-table org-timer)))
21197 ;;;###autoload
21198 (defun org-reload (&optional uncompiled)
21199 "Reload all org lisp files.
21200 With prefix arg UNCOMPILED, load the uncompiled versions."
21201 (interactive "P")
21202 (require 'loadhist)
21203 (let* ((org-dir (org-find-library-dir "org"))
21204 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21205 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21206 (remove-re (mapconcat 'identity
21207 (mapcar (lambda (f) (concat "^" f "$"))
21208 (list (if (featurep 'xemacs)
21209 "org-colview"
21210 "org-colview-xemacs")
21211 "org" "org-loaddefs" "org-version"))
21212 "\\|"))
21213 (feats (delete-dups
21214 (mapcar 'file-name-sans-extension
21215 (mapcar 'file-name-nondirectory
21216 (delq nil
21217 (mapcar 'feature-file
21218 features))))))
21219 (lfeat (append
21220 (sort
21221 (setq feats
21222 (delq nil (mapcar
21223 (lambda (f)
21224 (if (and (string-match feature-re f)
21225 (not (string-match remove-re f)))
21226 f nil))
21227 feats)))
21228 'string-lessp)
21229 (list "org-version" "org")))
21230 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21231 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21232 load-uncore load-misses)
21233 (setq load-misses
21234 (delq 't
21235 (mapcar (lambda (f)
21236 (or (org-load-noerror-mustsuffix (concat org-dir f))
21237 (and (string= org-dir contrib-dir)
21238 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21239 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21240 (add-to-list 'load-uncore f 'append)
21243 lfeat)))
21244 (if load-uncore
21245 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21246 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21247 (if load-misses
21248 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21249 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21250 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21252 ;;;###autoload
21253 (defun org-customize ()
21254 "Call the customize function with org as argument."
21255 (interactive)
21256 (org-load-modules-maybe)
21257 (org-require-autoloaded-modules)
21258 (customize-browse 'org))
21260 (defun org-create-customize-menu ()
21261 "Create a full customization menu for Org-mode, insert it into the menu."
21262 (interactive)
21263 (org-load-modules-maybe)
21264 (org-require-autoloaded-modules)
21265 (if (fboundp 'customize-menu-create)
21266 (progn
21267 (easy-menu-change
21268 '("Org") "Customize"
21269 `(["Browse Org group" org-customize t]
21270 "--"
21271 ,(customize-menu-create 'org)
21272 ["Set" Custom-set t]
21273 ["Save" Custom-save t]
21274 ["Reset to Current" Custom-reset-current t]
21275 ["Reset to Saved" Custom-reset-saved t]
21276 ["Reset to Standard Settings" Custom-reset-standard t]))
21277 (message "\"Org\"-menu now contains full customization menu"))
21278 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21280 ;;;; Miscellaneous stuff
21282 ;;; Generally useful functions
21284 (defun org-get-at-bol (property)
21285 "Get text property PROPERTY at beginning of line."
21286 (get-text-property (point-at-bol) property))
21288 (defun org-find-text-property-in-string (prop s)
21289 "Return the first non-nil value of property PROP in string S."
21290 (or (get-text-property 0 prop s)
21291 (get-text-property (or (next-single-property-change 0 prop s) 0)
21292 prop s)))
21294 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21295 "Display the given MESSAGE as a warning."
21296 (if (fboundp 'display-warning)
21297 (display-warning 'org message
21298 (if (featurep 'xemacs) 'warning :warning))
21299 (let ((buf (get-buffer-create "*Org warnings*")))
21300 (with-current-buffer buf
21301 (goto-char (point-max))
21302 (insert "Warning (Org): " message)
21303 (unless (bolp)
21304 (newline)))
21305 (display-buffer buf)
21306 (sit-for 0))))
21308 (defun org-eval (form)
21309 "Eval FORM and return result."
21310 (condition-case error
21311 (eval form)
21312 (error (format "%%![Error: %s]" error))))
21314 (defun org-in-clocktable-p ()
21315 "Check if the cursor is in a clocktable."
21316 (let ((pos (point)) start)
21317 (save-excursion
21318 (end-of-line 1)
21319 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21320 (setq start (match-beginning 0))
21321 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21322 (>= (match-end 0) pos)
21323 start))))
21325 (defun org-in-commented-line ()
21326 "Is point in a line starting with `#'?"
21327 (equal (char-after (point-at-bol)) ?#))
21329 (defun org-in-indented-comment-line ()
21330 "Is point in a line starting with `#' after some white space?"
21331 (save-excursion
21332 (save-match-data
21333 (goto-char (point-at-bol))
21334 (looking-at "[ \t]*#"))))
21336 (defun org-in-verbatim-emphasis ()
21337 (save-match-data
21338 (and (org-in-regexp org-emph-re 2)
21339 (>= (point) (match-beginning 3))
21340 (<= (point) (match-end 4))
21341 (member (match-string 3) '("=" "~")))))
21343 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21344 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21345 (if (and marker (marker-buffer marker)
21346 (buffer-live-p (marker-buffer marker)))
21347 (progn
21348 (org-pop-to-buffer-same-window (marker-buffer marker))
21349 (if (or (> marker (point-max)) (< marker (point-min)))
21350 (widen))
21351 (goto-char marker)
21352 (org-show-context 'org-goto))
21353 (if bookmark
21354 (bookmark-jump bookmark)
21355 (error "Cannot find location"))))
21357 (defun org-quote-csv-field (s)
21358 "Quote field for inclusion in CSV material."
21359 (if (string-match "[\",]" s)
21360 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21363 (defun org-force-self-insert (N)
21364 "Needed to enforce self-insert under remapping."
21365 (interactive "p")
21366 (self-insert-command N))
21368 (defun org-string-width (s)
21369 "Compute width of string, ignoring invisible characters.
21370 This ignores character with invisibility property `org-link', and also
21371 characters with property `org-cwidth', because these will become invisible
21372 upon the next fontification round."
21373 (let (b l)
21374 (when (or (eq t buffer-invisibility-spec)
21375 (assq 'org-link buffer-invisibility-spec))
21376 (while (setq b (text-property-any 0 (length s)
21377 'invisible 'org-link s))
21378 (setq s (concat (substring s 0 b)
21379 (substring s (or (next-single-property-change
21380 b 'invisible s)
21381 (length s)))))))
21382 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21383 (setq s (concat (substring s 0 b)
21384 (substring s (or (next-single-property-change
21385 b 'org-cwidth s)
21386 (length s))))))
21387 (setq l (string-width s) b -1)
21388 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21389 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21392 (defun org-shorten-string (s maxlength)
21393 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21394 If the string is shorter or has length MAXLENGTH, just return the
21395 original string. If it is longer, the functions finds a space in the
21396 string, breaks this string off at that locations and adds three dots
21397 as ellipsis. Including the ellipsis, the string will not be longer
21398 than MAXLENGTH. If finding a good breaking point in the string does
21399 not work, the string is just chopped off in the middle of a word
21400 if necessary."
21401 (if (<= (length s) maxlength)
21403 (let* ((n (max (- maxlength 4) 1))
21404 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21405 (if (string-match re s)
21406 (concat (match-string 1 s) "...")
21407 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21409 (defun org-get-indentation (&optional line)
21410 "Get the indentation of the current line, interpreting tabs.
21411 When LINE is given, assume it represents a line and compute its indentation."
21412 (if line
21413 (if (string-match "^ *" (org-remove-tabs line))
21414 (match-end 0))
21415 (save-excursion
21416 (beginning-of-line 1)
21417 (skip-chars-forward " \t")
21418 (current-column))))
21420 (defun org-get-string-indentation (s)
21421 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21422 (let ((n -1) (i 0) (w tab-width) c)
21423 (catch 'exit
21424 (while (< (setq n (1+ n)) (length s))
21425 (setq c (aref s n))
21426 (cond ((= c ?\ ) (setq i (1+ i)))
21427 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21428 (t (throw 'exit t)))))
21431 (defun org-remove-tabs (s &optional width)
21432 "Replace tabulators in S with spaces.
21433 Assumes that s is a single line, starting in column 0."
21434 (setq width (or width tab-width))
21435 (while (string-match "\t" s)
21436 (setq s (replace-match
21437 (make-string
21438 (- (* width (/ (+ (match-beginning 0) width) width))
21439 (match-beginning 0)) ?\ )
21440 t t s)))
21443 (defun org-fix-indentation (line ind)
21444 "Fix indentation in LINE.
21445 IND is a cons cell with target and minimum indentation.
21446 If the current indentation in LINE is smaller than the minimum,
21447 leave it alone. If it is larger than ind, set it to the target."
21448 (let* ((l (org-remove-tabs line))
21449 (i (org-get-indentation l))
21450 (i1 (car ind)) (i2 (cdr ind)))
21451 (if (>= i i2) (setq l (substring line i2)))
21452 (if (> i1 0)
21453 (concat (make-string i1 ?\ ) l)
21454 l)))
21456 (defun org-remove-indentation (code &optional n)
21457 "Remove the maximum common indentation from the lines in CODE.
21458 N may optionally be the number of spaces to remove."
21459 (with-temp-buffer
21460 (insert code)
21461 (org-do-remove-indentation n)
21462 (buffer-string)))
21464 (defun org-do-remove-indentation (&optional n)
21465 "Remove the maximum common indentation from the buffer."
21466 (untabify (point-min) (point-max))
21467 (let ((min 10000) re)
21468 (if n
21469 (setq min n)
21470 (goto-char (point-min))
21471 (while (re-search-forward "^ *[^ \n]" nil t)
21472 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21473 (unless (or (= min 0) (= min 10000))
21474 (setq re (format "^ \\{%d\\}" min))
21475 (goto-char (point-min))
21476 (while (re-search-forward re nil t)
21477 (replace-match "")
21478 (end-of-line 1))
21479 min)))
21481 (defun org-fill-template (template alist)
21482 "Find each %key of ALIST in TEMPLATE and replace it."
21483 (let ((case-fold-search nil))
21484 (dolist (entry (sort (copy-sequence alist)
21485 (lambda (a b) (< (length (car a)) (length (car b))))))
21486 (setq template
21487 (replace-regexp-in-string
21488 (concat "%" (regexp-quote (car entry)))
21489 (or (cdr entry) "") template t t)))
21490 template))
21492 (defun org-base-buffer (buffer)
21493 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21494 (if (not buffer)
21495 buffer
21496 (or (buffer-base-buffer buffer)
21497 buffer)))
21499 (defun org-trim (s)
21500 "Remove whitespace at beginning and end of string."
21501 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21502 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21505 (defun org-wrap (string &optional width lines)
21506 "Wrap string to either a number of lines, or a width in characters.
21507 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21508 that costs. If there is a word longer than WIDTH, the text is actually
21509 wrapped to the length of that word.
21510 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21511 many lines, whatever width that takes.
21512 The return value is a list of lines, without newlines at the end."
21513 (let* ((words (org-split-string string "[ \t\n]+"))
21514 (maxword (apply 'max (mapcar 'org-string-width words)))
21515 w ll)
21516 (cond (width
21517 (org-do-wrap words (max maxword width)))
21518 (lines
21519 (setq w maxword)
21520 (setq ll (org-do-wrap words maxword))
21521 (if (<= (length ll) lines)
21523 (setq ll words)
21524 (while (> (length ll) lines)
21525 (setq w (1+ w))
21526 (setq ll (org-do-wrap words w)))
21527 ll))
21528 (t (error "Cannot wrap this")))))
21530 (defun org-do-wrap (words width)
21531 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21532 (let (lines line)
21533 (while words
21534 (setq line (pop words))
21535 (while (and words (< (+ (length line) (length (car words))) width))
21536 (setq line (concat line " " (pop words))))
21537 (setq lines (push line lines)))
21538 (nreverse lines)))
21540 (defun org-split-string (string &optional separators)
21541 "Splits STRING into substrings at SEPARATORS.
21542 No empty strings are returned if there are matches at the beginning
21543 and end of string."
21544 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21545 (start 0)
21546 notfirst
21547 (list nil))
21548 (while (and (string-match rexp string
21549 (if (and notfirst
21550 (= start (match-beginning 0))
21551 (< start (length string)))
21552 (1+ start) start))
21553 (< (match-beginning 0) (length string)))
21554 (setq notfirst t)
21555 (or (eq (match-beginning 0) 0)
21556 (and (eq (match-beginning 0) (match-end 0))
21557 (eq (match-beginning 0) start))
21558 (setq list
21559 (cons (substring string start (match-beginning 0))
21560 list)))
21561 (setq start (match-end 0)))
21562 (or (eq start (length string))
21563 (setq list
21564 (cons (substring string start)
21565 list)))
21566 (nreverse list)))
21568 (defun org-quote-vert (s)
21569 "Replace \"|\" with \"\\vert\"."
21570 (while (string-match "|" s)
21571 (setq s (replace-match "\\vert" t t s)))
21574 (defun org-uuidgen-p (s)
21575 "Is S an ID created by UUIDGEN?"
21576 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21578 (defun org-in-src-block-p (&optional inside)
21579 "Whether point is in a code source block.
21580 When INSIDE is non-nil, don't consider we are within a src block
21581 when point is at #+BEGIN_SRC or #+END_SRC."
21582 (let ((case-fold-search t) ov)
21583 (or (and (setq ov (overlays-at (point)))
21584 (memq 'org-block-background
21585 (overlay-properties (car ov))))
21586 (and (not inside)
21587 (save-match-data
21588 (save-excursion
21589 (beginning-of-line)
21590 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21592 (defun org-context ()
21593 "Return a list of contexts of the current cursor position.
21594 If several contexts apply, all are returned.
21595 Each context entry is a list with a symbol naming the context, and
21596 two positions indicating start and end of the context. Possible
21597 contexts are:
21599 :headline anywhere in a headline
21600 :headline-stars on the leading stars in a headline
21601 :todo-keyword on a TODO keyword (including DONE) in a headline
21602 :tags on the TAGS in a headline
21603 :priority on the priority cookie in a headline
21604 :item on the first line of a plain list item
21605 :item-bullet on the bullet/number of a plain list item
21606 :checkbox on the checkbox in a plain list item
21607 :table in an org-mode table
21608 :table-special on a special filed in a table
21609 :table-table in a table.el table
21610 :clocktable in a clocktable
21611 :src-block in a source block
21612 :link on a hyperlink
21613 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21614 :target on a <<target>>
21615 :radio-target on a <<<radio-target>>>
21616 :latex-fragment on a LaTeX fragment
21617 :latex-preview on a LaTeX fragment with overlaid preview image
21619 This function expects the position to be visible because it uses font-lock
21620 faces as a help to recognize the following contexts: :table-special, :link,
21621 and :keyword."
21622 (let* ((f (get-text-property (point) 'face))
21623 (faces (if (listp f) f (list f)))
21624 (case-fold-search t)
21625 (p (point)) clist o)
21626 ;; First the large context
21627 (cond
21628 ((org-at-heading-p t)
21629 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21630 (when (progn
21631 (beginning-of-line 1)
21632 (looking-at org-todo-line-tags-regexp))
21633 (push (org-point-in-group p 1 :headline-stars) clist)
21634 (push (org-point-in-group p 2 :todo-keyword) clist)
21635 (push (org-point-in-group p 4 :tags) clist))
21636 (goto-char p)
21637 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21638 (if (looking-at "\\[#[A-Z0-9]\\]")
21639 (push (org-point-in-group p 0 :priority) clist)))
21641 ((org-at-item-p)
21642 (push (org-point-in-group p 2 :item-bullet) clist)
21643 (push (list :item (point-at-bol)
21644 (save-excursion (org-end-of-item) (point)))
21645 clist)
21646 (and (org-at-item-checkbox-p)
21647 (push (org-point-in-group p 0 :checkbox) clist)))
21649 ((org-at-table-p)
21650 (push (list :table (org-table-begin) (org-table-end)) clist)
21651 (if (memq 'org-formula faces)
21652 (push (list :table-special
21653 (previous-single-property-change p 'face)
21654 (next-single-property-change p 'face)) clist)))
21655 ((org-at-table-p 'any)
21656 (push (list :table-table) clist)))
21657 (goto-char p)
21659 (let ((case-fold-search t))
21660 ;; New the "medium" contexts: clocktables, source blocks
21661 (cond ((org-in-clocktable-p)
21662 (push (list :clocktable
21663 (and (or (looking-at "#\\+BEGIN: clocktable")
21664 (search-backward "#+BEGIN: clocktable" nil t))
21665 (match-beginning 0))
21666 (and (re-search-forward "#\\+END:?" nil t)
21667 (match-end 0))) clist))
21668 ((org-in-src-block-p)
21669 (push (list :src-block
21670 (and (or (looking-at "#\\+BEGIN_SRC")
21671 (search-backward "#+BEGIN_SRC" nil t))
21672 (match-beginning 0))
21673 (and (search-forward "#+END_SRC" nil t)
21674 (match-beginning 0))) clist))))
21675 (goto-char p)
21677 ;; Now the small context
21678 (cond
21679 ((org-at-timestamp-p)
21680 (push (org-point-in-group p 0 :timestamp) clist))
21681 ((memq 'org-link faces)
21682 (push (list :link
21683 (previous-single-property-change p 'face)
21684 (next-single-property-change p 'face)) clist))
21685 ((memq 'org-special-keyword faces)
21686 (push (list :keyword
21687 (previous-single-property-change p 'face)
21688 (next-single-property-change p 'face)) clist))
21689 ((org-at-target-p)
21690 (push (org-point-in-group p 0 :target) clist)
21691 (goto-char (1- (match-beginning 0)))
21692 (if (looking-at org-radio-target-regexp)
21693 (push (org-point-in-group p 0 :radio-target) clist))
21694 (goto-char p))
21695 ((setq o (car (delq nil
21696 (mapcar
21697 (lambda (x)
21698 (if (memq x org-latex-fragment-image-overlays) x))
21699 (overlays-at (point))))))
21700 (push (list :latex-fragment
21701 (overlay-start o) (overlay-end o)) clist)
21702 (push (list :latex-preview
21703 (overlay-start o) (overlay-end o)) clist))
21704 ((org-inside-LaTeX-fragment-p)
21705 ;; FIXME: positions wrong.
21706 (push (list :latex-fragment (point) (point)) clist)))
21708 (setq clist (nreverse (delq nil clist)))
21709 clist))
21711 ;; FIXME: Compare with at-regexp-p Do we need both?
21712 (defun org-in-regexp (re &optional nlines visually)
21713 "Check if point is inside a match of regexp.
21714 Normally only the current line is checked, but you can include NLINES extra
21715 lines both before and after point into the search.
21716 If VISUALLY is set, require that the cursor is not after the match but
21717 really on, so that the block visually is on the match."
21718 (catch 'exit
21719 (let ((pos (point))
21720 (eol (point-at-eol (+ 1 (or nlines 0))))
21721 (inc (if visually 1 0)))
21722 (save-excursion
21723 (beginning-of-line (- 1 (or nlines 0)))
21724 (while (re-search-forward re eol t)
21725 (if (and (<= (match-beginning 0) pos)
21726 (>= (+ inc (match-end 0)) pos))
21727 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21729 (defun org-at-regexp-p (regexp)
21730 "Is point inside a match of REGEXP in the current line?"
21731 (catch 'exit
21732 (save-excursion
21733 (let ((pos (point)) (end (point-at-eol)))
21734 (beginning-of-line 1)
21735 (while (re-search-forward regexp end t)
21736 (if (and (<= (match-beginning 0) pos)
21737 (>= (match-end 0) pos))
21738 (throw 'exit t)))
21739 nil))))
21741 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21742 "Non-nil when point is between matches of START-RE and END-RE.
21744 Also return a non-nil value when point is on one of the matches.
21746 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21747 buffer positions. Default values are the positions of headlines
21748 surrounding the point.
21750 The functions returns a cons cell whose car (resp. cdr) is the
21751 position before START-RE (resp. after END-RE)."
21752 (save-match-data
21753 (let ((pos (point))
21754 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21755 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21756 beg end)
21757 (save-excursion
21758 ;; Point is on a block when on START-RE or if START-RE can be
21759 ;; found before it...
21760 (and (or (org-at-regexp-p start-re)
21761 (re-search-backward start-re limit-up t))
21762 (setq beg (match-beginning 0))
21763 ;; ... and END-RE after it...
21764 (goto-char (match-end 0))
21765 (re-search-forward end-re limit-down t)
21766 (> (setq end (match-end 0)) pos)
21767 ;; ... without another START-RE in-between.
21768 (goto-char (match-beginning 0))
21769 (not (re-search-backward start-re (1+ beg) t))
21770 ;; Return value.
21771 (cons beg end))))))
21773 (defun org-in-block-p (names)
21774 "Non-nil when point belongs to a block whose name belongs to NAMES.
21776 NAMES is a list of strings containing names of blocks.
21778 Return first block name matched, or nil. Beware that in case of
21779 nested blocks, the returned name may not belong to the closest
21780 block from point."
21781 (save-match-data
21782 (catch 'exit
21783 (let ((case-fold-search t)
21784 (lim-up (save-excursion (outline-previous-heading)))
21785 (lim-down (save-excursion (outline-next-heading))))
21786 (mapc (lambda (name)
21787 (let ((n (regexp-quote name)))
21788 (when (org-between-regexps-p
21789 (concat "^[ \t]*#\\+begin_" n)
21790 (concat "^[ \t]*#\\+end_" n)
21791 lim-up lim-down)
21792 (throw 'exit n))))
21793 names))
21794 nil)))
21796 (defun org-in-drawer-p ()
21797 "Is point within a drawer?"
21798 (save-match-data
21799 (let ((case-fold-search t)
21800 (lim-up (save-excursion (outline-previous-heading)))
21801 (lim-down (save-excursion (outline-next-heading))))
21802 (org-between-regexps-p
21803 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21804 "^[ \t]*:end:.*$"
21805 lim-up lim-down))))
21807 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21808 "Call `multi-occur' with buffers for all agenda files."
21809 (interactive "sOrg-files matching: ")
21810 (let* ((files (org-agenda-files))
21811 (tnames (mapcar #'file-truename files))
21812 (extra org-agenda-text-search-extra-files))
21813 (when (eq (car extra) 'agenda-archives)
21814 (setq extra (cdr extra))
21815 (setq files (org-add-archive-files files)))
21816 (dolist (f extra)
21817 (unless (member (file-truename f) tnames)
21818 (unless (member f files) (setq files (append files (list f))))
21819 (setq tnames (append tnames (list (file-truename f))))))
21820 (multi-occur
21821 (mapcar (lambda (x)
21822 (with-current-buffer
21823 ;; FIXME: Why not just (find-file-noselect x)?
21824 ;; Is it to avoid the "revert buffer" prompt?
21825 (or (get-file-buffer x) (find-file-noselect x))
21826 (widen)
21827 (current-buffer)))
21828 files)
21829 regexp)))
21831 (if (boundp 'occur-mode-find-occurrence-hook)
21832 ;; Emacs 23
21833 (add-hook 'occur-mode-find-occurrence-hook
21834 (lambda ()
21835 (when (derived-mode-p 'org-mode)
21836 (org-reveal))))
21837 ;; Emacs 22
21838 (defadvice occur-mode-goto-occurrence
21839 (after org-occur-reveal activate)
21840 (and (derived-mode-p 'org-mode) (org-reveal)))
21841 (defadvice occur-mode-goto-occurrence-other-window
21842 (after org-occur-reveal activate)
21843 (and (derived-mode-p 'org-mode) (org-reveal)))
21844 (defadvice occur-mode-display-occurrence
21845 (after org-occur-reveal activate)
21846 (when (derived-mode-p 'org-mode)
21847 (let ((pos (occur-mode-find-occurrence)))
21848 (with-current-buffer (marker-buffer pos)
21849 (save-excursion
21850 (goto-char pos)
21851 (org-reveal)))))))
21853 (defun org-occur-link-in-agenda-files ()
21854 "Create a link and search for it in the agendas.
21855 The link is not stored in `org-stored-links', it is just created
21856 for the search purpose."
21857 (interactive)
21858 (let ((link (condition-case nil
21859 (org-store-link nil)
21860 (error "Unable to create a link to here"))))
21861 (org-occur-in-agenda-files (regexp-quote link))))
21863 (defun org-reverse-string (string)
21864 "Return the reverse of STRING."
21865 (apply 'string (reverse (string-to-list string))))
21867 ;; defsubst org-uniquify must be defined before first use
21869 (defun org-uniquify-alist (alist)
21870 "Merge elements of ALIST with the same key.
21872 For example, in this alist:
21874 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
21875 => \\='((a 1 3) (b 2))
21877 merge (a 1) and (a 3) into (a 1 3).
21879 The function returns the new ALIST."
21880 (let (rtn)
21881 (mapc
21882 (lambda (e)
21883 (let (n)
21884 (if (not (assoc (car e) rtn))
21885 (push e rtn)
21886 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21887 (setq rtn (assq-delete-all (car e) rtn))
21888 (push n rtn))))
21889 alist)
21890 rtn))
21892 (defun org-delete-all (elts list)
21893 "Remove all elements in ELTS from LIST."
21894 (while elts
21895 (setq list (delete (pop elts) list)))
21896 list)
21898 (defun org-count (cl-item cl-seq)
21899 "Count the number of occurrences of ITEM in SEQ.
21900 Taken from `count' in cl-seq.el with all keyword arguments removed."
21901 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21902 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21903 (while (< cl-start cl-end)
21904 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21905 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21906 (setq cl-start (1+ cl-start)))
21907 cl-count))
21909 (defun org-remove-if (predicate seq)
21910 "Remove everything from SEQ that fulfills PREDICATE."
21911 (let (res e)
21912 (while seq
21913 (setq e (pop seq))
21914 (if (not (funcall predicate e)) (push e res)))
21915 (nreverse res)))
21917 (defun org-remove-if-not (predicate seq)
21918 "Remove everything from SEQ that does not fulfill PREDICATE."
21919 (let (res e)
21920 (while seq
21921 (setq e (pop seq))
21922 (if (funcall predicate e) (push e res)))
21923 (nreverse res)))
21925 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21926 "Reduce two-argument FUNCTION across SEQ.
21927 Taken from `reduce' in cl-seq.el with all keyword arguments but
21928 \":initial-value\" removed."
21929 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21930 (cadr (memq :initial-value cl-keys)))
21931 (cl-seq (pop cl-seq))
21932 (t (funcall cl-func)))))
21933 (while cl-seq
21934 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21935 cl-accum))
21937 (defun org-every (pred seq)
21938 "Return true if PREDICATE is true of every element of SEQ.
21939 Adapted from `every' in cl.el."
21940 (catch 'org-every
21941 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21944 (defun org-some (pred seq)
21945 "Return true if PREDICATE is true of any element of SEQ.
21946 Adapted from `some' in cl.el."
21947 (catch 'org-some
21948 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21949 nil))
21951 (defun org-back-over-empty-lines ()
21952 "Move backwards over whitespace, to the beginning of the first empty line.
21953 Returns the number of empty lines passed."
21954 (let ((pos (point)))
21955 (if (cdr (assoc 'heading org-blank-before-new-entry))
21956 (skip-chars-backward " \t\n\r")
21957 (unless (eobp)
21958 (forward-line -1)))
21959 (beginning-of-line 2)
21960 (goto-char (min (point) pos))
21961 (count-lines (point) pos)))
21963 (defun org-skip-whitespace ()
21964 (skip-chars-forward " \t\n\r"))
21966 (defun org-point-in-group (point group &optional context)
21967 "Check if POINT is in match-group GROUP.
21968 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21969 match. If the match group does not exist or point is not inside it,
21970 return nil."
21971 (and (match-beginning group)
21972 (>= point (match-beginning group))
21973 (<= point (match-end group))
21974 (if context
21975 (list context (match-beginning group) (match-end group))
21976 t)))
21978 (defun org-switch-to-buffer-other-window (&rest args)
21979 "Switch to buffer in a second window on the current frame.
21980 In particular, do not allow pop-up frames.
21981 Returns the newly created buffer."
21982 (org-no-popups
21983 (apply 'switch-to-buffer-other-window args)))
21985 (defun org-combine-plists (&rest plists)
21986 "Create a single property list from all plists in PLISTS.
21987 The process starts by copying the first list, and then setting properties
21988 from the other lists. Settings in the last list are the most significant
21989 ones and overrule settings in the other lists."
21990 (let ((rtn (copy-sequence (pop plists)))
21991 p v ls)
21992 (while plists
21993 (setq ls (pop plists))
21994 (while ls
21995 (setq p (pop ls) v (pop ls))
21996 (setq rtn (plist-put rtn p v))))
21997 rtn))
21999 (defun org-replace-escapes (string table)
22000 "Replace %-escapes in STRING with values in TABLE.
22001 TABLE is an association list with keys like \"%a\" and string values.
22002 The sequences in STRING may contain normal field width and padding information,
22003 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22004 so values can contain further %-escapes if they are define later in TABLE."
22005 (let ((tbl (copy-alist table))
22006 (case-fold-search nil)
22007 (pchg 0)
22008 e re rpl)
22009 (dolist (e tbl)
22010 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22011 (when (and (cdr e) (string-match re (cdr e)))
22012 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22013 (safe "SREF"))
22014 (add-text-properties 0 3 (list 'sref sref) safe)
22015 (setcdr e (replace-match safe t t (cdr e)))))
22016 (while (string-match re string)
22017 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22018 (cdr e)))
22019 (setq string (replace-match rpl t t string))))
22020 (while (setq pchg (next-property-change pchg string))
22021 (let ((sref (get-text-property pchg 'sref string)))
22022 (when (and sref (string-match "SREF" string pchg))
22023 (setq string (replace-match sref t t string)))))
22024 string))
22026 (defun org-sublist (list start end)
22027 "Return a section of LIST, from START to END.
22028 Counting starts at 1."
22029 (let (rtn (c start))
22030 (setq list (nthcdr (1- start) list))
22031 (while (and list (<= c end))
22032 (push (pop list) rtn)
22033 (setq c (1+ c)))
22034 (nreverse rtn)))
22036 (defun org-find-base-buffer-visiting (file)
22037 "Like `find-buffer-visiting' but always return the base buffer and
22038 not an indirect buffer."
22039 (let ((buf (or (get-file-buffer file)
22040 (find-buffer-visiting file))))
22041 (if buf
22042 (or (buffer-base-buffer buf) buf)
22043 nil)))
22045 (defun org-image-file-name-regexp (&optional extensions)
22046 "Return regexp matching the file names of images.
22047 If EXTENSIONS is given, only match these."
22048 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22049 (image-file-name-regexp)
22050 (let ((image-file-name-extensions
22051 (or extensions
22052 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22053 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22054 (concat "\\."
22055 (regexp-opt (nconc (mapcar 'upcase
22056 image-file-name-extensions)
22057 image-file-name-extensions)
22059 "\\'"))))
22061 (defun org-file-image-p (file &optional extensions)
22062 "Return non-nil if FILE is an image."
22063 (save-match-data
22064 (string-match (org-image-file-name-regexp extensions) file)))
22066 (defun org-get-cursor-date (&optional with-time)
22067 "Return the date at cursor in as a time.
22068 This works in the calendar and in the agenda, anywhere else it just
22069 returns the current time.
22070 If WITH-TIME is non-nil, returns the time of the event at point (in
22071 the agenda) or the current time of the day."
22072 (let (date day defd tp hod mod)
22073 (when with-time
22074 (setq tp (get-text-property (point) 'time))
22075 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22076 (setq hod (string-to-number (match-string 1 tp))
22077 mod (string-to-number (match-string 2 tp))))
22078 (or tp (let ((now (decode-time)))
22079 (setq hod (nth 2 now)
22080 mod (nth 1 now)))))
22081 (cond
22082 ((eq major-mode 'calendar-mode)
22083 (setq date (calendar-cursor-to-date)
22084 defd (encode-time 0 (or mod 0) (or hod 0)
22085 (nth 1 date) (nth 0 date) (nth 2 date))))
22086 ((eq major-mode 'org-agenda-mode)
22087 (setq day (get-text-property (point) 'day))
22088 (if day
22089 (setq date (calendar-gregorian-from-absolute day)
22090 defd (encode-time 0 (or mod 0) (or hod 0)
22091 (nth 1 date) (nth 0 date) (nth 2 date))))))
22092 (or defd (current-time))))
22094 (defun org-mark-subtree (&optional up)
22095 "Mark the current subtree.
22096 This puts point at the start of the current subtree, and mark at
22097 the end. If a numeric prefix UP is given, move up into the
22098 hierarchy of headlines by UP levels before marking the subtree."
22099 (interactive "P")
22100 (org-with-limited-levels
22101 (cond ((org-at-heading-p) (beginning-of-line))
22102 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22103 (t (outline-previous-visible-heading 1))))
22104 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22105 (if (org-called-interactively-p 'any)
22106 (call-interactively 'org-mark-element)
22107 (org-mark-element)))
22110 ;;; Indentation
22112 (defun org-indent-line ()
22113 "Indent line depending on context."
22114 (interactive)
22115 (let* ((pos (point))
22116 (itemp (org-at-item-p))
22117 (case-fold-search t)
22118 (org-drawer-regexp (or org-drawer-regexp "\000"))
22119 (inline-task-p (and (featurep 'org-inlinetask)
22120 (org-inlinetask-in-task-p)))
22121 (inline-re (and inline-task-p
22122 (org-inlinetask-outline-regexp)))
22123 column)
22124 (if (and orgstruct-is-++ (eq pos (point)))
22125 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22126 (indent-according-to-mode))
22127 (beginning-of-line 1)
22128 (cond
22129 ;; Headings
22130 ((looking-at org-outline-regexp) (setq column 0))
22131 ;; Footnote definition
22132 ((looking-at org-footnote-definition-re) (setq column 0))
22133 ;; Literal examples
22134 ((looking-at "[ \t]*:\\( \\|$\\)")
22135 (setq column (org-get-indentation))) ; do nothing
22136 ;; Lists
22137 ((ignore-errors (goto-char (org-in-item-p)))
22138 (setq column (if itemp
22139 (org-get-indentation)
22140 (org-list-item-body-column (point))))
22141 (goto-char pos))
22142 ;; Drawers
22143 ((and (looking-at "[ \t]*:END:")
22144 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22145 (save-excursion
22146 (goto-char (1- (match-beginning 1)))
22147 (setq column (current-column))))
22148 ;; Special blocks
22149 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22150 (save-excursion
22151 (re-search-backward
22152 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22153 (setq column (org-get-indentation (match-string 0))))
22154 ((and (not (looking-at "[ \t]*#\\+begin_"))
22155 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22156 (save-excursion
22157 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22158 (setq column
22159 (cond ((equal (downcase (match-string 1)) "src")
22160 ;; src blocks: let `org-edit-src-exit' handle them
22161 (org-get-indentation))
22162 ((equal (downcase (match-string 1)) "example")
22163 (max (org-get-indentation)
22164 (org-get-indentation (match-string 0))))
22166 (org-get-indentation (match-string 0))))))
22167 ;; This line has nothing special, look at the previous relevant
22168 ;; line to compute indentation
22170 (beginning-of-line 0)
22171 (while (and (not (bobp))
22172 (not (looking-at org-table-line-regexp))
22173 (not (looking-at org-drawer-regexp))
22174 ;; When point started in an inline task, do not move
22175 ;; above task starting line.
22176 (not (and inline-task-p (looking-at inline-re)))
22177 ;; Skip drawers, blocks, empty lines, verbatim,
22178 ;; comments, tables, footnotes definitions, lists,
22179 ;; inline tasks.
22180 (or (and (looking-at "[ \t]*:END:")
22181 (re-search-backward org-drawer-regexp nil t))
22182 (and (looking-at "[ \t]*#\\+end_")
22183 (re-search-backward "[ \t]*#\\+begin_"nil t))
22184 (looking-at "[ \t]*[\n:#|]")
22185 (looking-at org-footnote-definition-re)
22186 (and (not inline-task-p)
22187 (featurep 'org-inlinetask)
22188 (org-inlinetask-in-task-p)
22189 (or (org-inlinetask-goto-beginning) t))))
22190 (beginning-of-line 0))
22191 (cond
22192 ;; There was a list item above.
22193 ((ignore-errors (goto-char (org-in-item-p)))
22194 (goto-char (org-list-get-top-point (org-list-struct)))
22195 (setq column (org-get-indentation)))
22196 ;; There was an heading above.
22197 ((looking-at "\\*+[ \t]+")
22198 (if (not org-adapt-indentation)
22199 (setq column 0)
22200 (goto-char (match-end 0))
22201 (setq column (current-column))))
22202 ;; A drawer had started and is unfinished
22203 ((looking-at org-drawer-regexp)
22204 (goto-char (1- (match-beginning 1)))
22205 (setq column (current-column)))
22206 ;; Else, nothing noticeable found: get indentation and go on.
22207 (t (setq column (org-get-indentation))))))
22208 ;; Now apply indentation and move cursor accordingly
22209 (goto-char pos)
22210 (if (<= (current-column) (current-indentation))
22211 (org-indent-line-to column)
22212 (save-excursion (org-indent-line-to column)))
22213 ;; Special polishing for properties, see `org-property-format'
22214 (setq column (current-column))
22215 (beginning-of-line 1)
22216 (if (looking-at org-property-re)
22217 (replace-match (concat (match-string 4)
22218 (format org-property-format
22219 (match-string 1) (match-string 3)))
22220 t t))
22221 (org-move-to-column column))))
22223 (defun org-indent-drawer ()
22224 "Indent the drawer at point."
22225 (interactive)
22226 (let ((p (point))
22227 (e (and (save-excursion (re-search-forward ":END:" nil t))
22228 (match-end 0)))
22229 (folded
22230 (save-excursion
22231 (end-of-line)
22232 (when (overlays-at (point))
22233 (member 'invisible (overlay-properties
22234 (car (overlays-at (point)))))))))
22235 (when folded (org-cycle))
22236 (indent-for-tab-command)
22237 (while (and (move-beginning-of-line 2) (< (point) e))
22238 (indent-for-tab-command))
22239 (goto-char p)
22240 (when folded (org-cycle)))
22241 (message "Drawer at point indented"))
22243 (defun org-indent-block ()
22244 "Indent the block at point."
22245 (interactive)
22246 (let ((p (point))
22247 (case-fold-search t)
22248 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22249 (match-end 0)))
22250 (folded
22251 (save-excursion
22252 (end-of-line)
22253 (when (overlays-at (point))
22254 (member 'invisible (overlay-properties
22255 (car (overlays-at (point)))))))))
22256 (when folded (org-cycle))
22257 (indent-for-tab-command)
22258 (while (and (move-beginning-of-line 2) (< (point) e))
22259 (indent-for-tab-command))
22260 (goto-char p)
22261 (when folded (org-cycle)))
22262 (message "Block at point indented"))
22264 (defun org-indent-region (start end)
22265 "Indent region."
22266 (interactive "r")
22267 (save-excursion
22268 (let ((line-end (org-current-line end)))
22269 (goto-char start)
22270 (while (< (org-current-line) line-end)
22271 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22272 (t (call-interactively 'org-indent-line)))
22273 (move-beginning-of-line 2)))))
22276 ;;; Filling
22278 ;; We use our own fill-paragraph and auto-fill functions.
22280 ;; `org-fill-paragraph' relies on adaptive filling and context
22281 ;; checking. Appropriate `fill-prefix' is computed with
22282 ;; `org-adaptive-fill-function'.
22284 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22285 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22286 ;; `org-adaptive-fill-function' value. Internally,
22287 ;; `org-comment-line-break-function' breaks the line.
22289 ;; `org-setup-filling' installs filling and auto-filling related
22290 ;; variables during `org-mode' initialization.
22292 (defvar org-element-paragraph-separate) ; org-element.el
22293 (defun org-setup-filling ()
22294 (require 'org-element)
22295 ;; Prevent auto-fill from inserting unwanted new items.
22296 (when (boundp 'fill-nobreak-predicate)
22297 (org-set-local
22298 'fill-nobreak-predicate
22299 (org-uniquify
22300 (append fill-nobreak-predicate
22301 '(org-fill-line-break-nobreak-p
22302 org-fill-paragraph-with-timestamp-nobreak-p)))))
22303 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22304 (org-set-local 'paragraph-start paragraph-ending)
22305 (org-set-local 'paragraph-separate paragraph-ending))
22306 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22307 (org-set-local 'auto-fill-inhibit-regexp nil)
22308 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22309 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22310 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22312 (defun org-fill-line-break-nobreak-p ()
22313 "Non-nil when a new line at point would create an Org line break."
22314 (save-excursion
22315 (skip-chars-backward "[ \t]")
22316 (skip-chars-backward "\\\\")
22317 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22319 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22320 "Non-nil when a new line at point would split a timestamp."
22321 (and (org-at-timestamp-p t)
22322 (not (looking-at org-ts-regexp-both))))
22324 (declare-function message-in-body-p "message" ())
22325 (defvar orgtbl-line-start-regexp) ; From org-table.el
22326 (defun org-adaptive-fill-function ()
22327 "Compute a fill prefix for the current line.
22328 Return fill prefix, as a string, or nil if current line isn't
22329 meant to be filled. For convenience, if `adaptive-fill-regexp'
22330 matches in paragraphs or comments, use it."
22331 (catch 'exit
22332 (when (derived-mode-p 'message-mode)
22333 (save-excursion
22334 (beginning-of-line)
22335 (cond ((or (not (message-in-body-p))
22336 (looking-at orgtbl-line-start-regexp))
22337 (throw 'exit nil))
22338 ((looking-at message-cite-prefix-regexp)
22339 (throw 'exit (match-string-no-properties 0)))
22340 ((looking-at org-outline-regexp)
22341 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22342 (org-with-wide-buffer
22343 (let* ((p (line-beginning-position))
22344 (element (save-excursion
22345 (beginning-of-line)
22346 (or (ignore-errors (org-element-at-point))
22347 (user-error "An element cannot be parsed line %d"
22348 (line-number-at-pos (point))))))
22349 (type (org-element-type element))
22350 (post-affiliated (org-element-property :post-affiliated element)))
22351 (unless (and post-affiliated (< p post-affiliated))
22352 (case type
22353 (comment
22354 (save-excursion
22355 (beginning-of-line)
22356 (looking-at "[ \t]*")
22357 (concat (match-string 0) "# ")))
22358 (footnote-definition "")
22359 ((item plain-list)
22360 (make-string (org-list-item-body-column
22361 (or post-affiliated
22362 (org-element-property :begin element)))
22363 ? ))
22364 (paragraph
22365 ;; Fill prefix is usually the same as the current line,
22366 ;; unless the paragraph is at the beginning of an item.
22367 (let ((parent (org-element-property :parent element)))
22368 (save-excursion
22369 (beginning-of-line)
22370 (cond ((eq (org-element-type parent) 'item)
22371 (make-string (org-list-item-body-column
22372 (org-element-property :begin parent))
22373 ? ))
22374 ((and adaptive-fill-regexp
22375 ;; Locally disable
22376 ;; `adaptive-fill-function' to let
22377 ;; `fill-context-prefix' handle
22378 ;; `adaptive-fill-regexp' variable.
22379 (let (adaptive-fill-function)
22380 (fill-context-prefix
22381 post-affiliated
22382 (org-element-property :end element)))))
22383 ((looking-at "[ \t]+") (match-string 0))
22384 (t "")))))
22385 (comment-block
22386 ;; Only fill contents if P is within block boundaries.
22387 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22388 (forward-line)
22389 (point)))
22390 (cend (save-excursion
22391 (goto-char (org-element-property :end element))
22392 (skip-chars-backward " \r\t\n")
22393 (line-beginning-position))))
22394 (when (and (>= p cbeg) (< p cend))
22395 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22396 (match-string 0)
22397 ""))))))))))
22399 (declare-function message-goto-body "message" ())
22400 (defvar message-cite-prefix-regexp) ; From message.el
22401 (defun org-fill-paragraph (&optional justify)
22402 "Fill element at point, when applicable.
22404 This function only applies to comment blocks, comments, example
22405 blocks and paragraphs. Also, as a special case, re-align table
22406 when point is at one.
22408 If JUSTIFY is non-nil (interactively, with prefix argument),
22409 justify as well. If `sentence-end-double-space' is non-nil, then
22410 period followed by one space does not end a sentence, so don't
22411 break a line there. The variable `fill-column' controls the
22412 width for filling.
22414 For convenience, when point is at a plain list, an item or
22415 a footnote definition, try to fill the first paragraph within."
22416 (interactive)
22417 (if (and (derived-mode-p 'message-mode)
22418 (or (not (message-in-body-p))
22419 (save-excursion (move-beginning-of-line 1)
22420 (looking-at message-cite-prefix-regexp))))
22421 ;; First ensure filling is correct in message-mode.
22422 (let ((fill-paragraph-function
22423 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22424 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22425 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22426 (paragraph-separate
22427 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22428 (fill-paragraph nil))
22429 (with-syntax-table org-mode-transpose-word-syntax-table
22430 ;; Move to end of line in order to get the first paragraph
22431 ;; within a plain list or a footnote definition.
22432 (let ((element (save-excursion
22433 (end-of-line)
22434 (or (ignore-errors (org-element-at-point))
22435 (user-error "An element cannot be parsed line %d"
22436 (line-number-at-pos (point)))))))
22437 ;; First check if point is in a blank line at the beginning of
22438 ;; the buffer. In that case, ignore filling.
22439 (case (org-element-type element)
22440 ;; Use major mode filling function is src blocks.
22441 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22442 ;; Align Org tables, leave table.el tables as-is.
22443 (table-row (org-table-align) t)
22444 (table
22445 (when (eq (org-element-property :type element) 'org)
22446 (save-excursion
22447 (goto-char (org-element-property :post-affiliated element))
22448 (org-table-align)))
22450 (paragraph
22451 ;; Paragraphs may contain `line-break' type objects.
22452 (let ((beg (max (point-min)
22453 (org-element-property :contents-begin element)))
22454 (end (min (point-max)
22455 (org-element-property :contents-end element))))
22456 ;; Do nothing if point is at an affiliated keyword.
22457 (if (< (line-end-position) beg) t
22458 (when (derived-mode-p 'message-mode)
22459 ;; In `message-mode', do not fill following citation
22460 ;; in current paragraph nor text before message body.
22461 (let ((body-start (save-excursion (message-goto-body))))
22462 (when body-start (setq beg (max body-start beg))))
22463 (when (save-excursion
22464 (re-search-forward
22465 (concat "^" message-cite-prefix-regexp) end t))
22466 (setq end (match-beginning 0))))
22467 ;; Fill paragraph, taking line breaks into account.
22468 ;; For that, slice the paragraph using line breaks as
22469 ;; separators, and fill the parts in reverse order to
22470 ;; avoid messing with markers.
22471 (save-excursion
22472 (goto-char end)
22473 (mapc
22474 (lambda (pos)
22475 (fill-region-as-paragraph pos (point) justify)
22476 (goto-char pos))
22477 ;; Find the list of ending positions for line breaks
22478 ;; in the current paragraph. Add paragraph
22479 ;; beginning to include first slice.
22480 (nreverse
22481 (cons beg
22482 (org-element-map
22483 (org-element--parse-objects
22484 beg end nil (org-element-restriction 'paragraph))
22485 'line-break
22486 (lambda (lb) (org-element-property :end lb)))))))
22487 t)))
22488 ;; Contents of `comment-block' type elements should be
22489 ;; filled as plain text, but only if point is within block
22490 ;; markers.
22491 (comment-block
22492 (let* ((case-fold-search t)
22493 (beg (save-excursion
22494 (goto-char (org-element-property :begin element))
22495 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22496 (forward-line)
22497 (point)))
22498 (end (save-excursion
22499 (goto-char (org-element-property :end element))
22500 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22501 (line-beginning-position))))
22502 (if (or (< (point) beg) (> (point) end)) t
22503 (fill-region-as-paragraph
22504 (save-excursion (end-of-line)
22505 (re-search-backward "^[ \t]*$" beg 'move)
22506 (line-beginning-position))
22507 (save-excursion (beginning-of-line)
22508 (re-search-forward "^[ \t]*$" end 'move)
22509 (line-beginning-position))
22510 justify))))
22511 ;; Fill comments.
22512 (comment
22513 (let ((begin (org-element-property :post-affiliated element))
22514 (end (org-element-property :end element)))
22515 (when (and (>= (point) begin) (<= (point) end))
22516 (let ((begin (save-excursion
22517 (end-of-line)
22518 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22519 (progn (forward-line) (point))
22520 begin)))
22521 (end (save-excursion
22522 (end-of-line)
22523 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22524 (1- (line-beginning-position))
22525 (skip-chars-backward " \r\t\n")
22526 (line-end-position)))))
22527 ;; Do not fill comments when at a blank line.
22528 (when (> end begin)
22529 (let ((fill-prefix
22530 (save-excursion
22531 (beginning-of-line)
22532 (looking-at "[ \t]*#")
22533 (let ((comment-prefix (match-string 0)))
22534 (goto-char (match-end 0))
22535 (if (looking-at adaptive-fill-regexp)
22536 (concat comment-prefix (match-string 0))
22537 (concat comment-prefix " "))))))
22538 (save-excursion
22539 (fill-region-as-paragraph begin end justify))))))
22541 ;; Ignore every other element.
22542 (otherwise t))))))
22544 (defun org-auto-fill-function ()
22545 "Auto-fill function."
22546 ;; Check if auto-filling is meaningful.
22547 (let ((fc (current-fill-column)))
22548 (when (and fc (> (current-column) fc))
22549 (let* ((fill-prefix (org-adaptive-fill-function))
22550 ;; Enforce empty fill prefix, if required. Otherwise, it
22551 ;; will be computed again.
22552 (adaptive-fill-mode (not (equal fill-prefix ""))))
22553 (when fill-prefix (do-auto-fill))))))
22555 (defun org-comment-line-break-function (&optional soft)
22556 "Break line at point and indent, continuing comment if within one.
22557 The inserted newline is marked hard if variable
22558 `use-hard-newlines' is true, unless optional argument SOFT is
22559 non-nil."
22560 (if soft (insert-and-inherit ?\n) (newline 1))
22561 (save-excursion (forward-char -1) (delete-horizontal-space))
22562 (delete-horizontal-space)
22563 (indent-to-left-margin)
22564 (insert-before-markers-and-inherit fill-prefix))
22567 ;;; Comments
22569 ;; Org comments syntax is quite complex. It requires the entire line
22570 ;; to be just a comment. Also, even with the right syntax at the
22571 ;; beginning of line, some some elements (i.e. verse-block or
22572 ;; example-block) don't accept comments. Usual Emacs comment commands
22573 ;; cannot cope with those requirements. Therefore, Org replaces them.
22575 ;; Org still relies on `comment-dwim', but cannot trust
22576 ;; `comment-only-p'. So, `comment-region-function' and
22577 ;; `uncomment-region-function' both point
22578 ;; to`org-comment-or-uncomment-region'. Eventually,
22579 ;; `org-insert-comment' takes care of insertion of comments at the
22580 ;; beginning of line.
22582 ;; `org-setup-comments-handling' install comments related variables
22583 ;; during `org-mode' initialization.
22585 (defun org-setup-comments-handling ()
22586 (interactive)
22587 (org-set-local 'comment-use-syntax nil)
22588 (org-set-local 'comment-start "# ")
22589 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22590 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22591 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22592 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22594 (defun org-insert-comment ()
22595 "Insert an empty comment above current line.
22596 If the line is empty, insert comment at its beginning."
22597 (beginning-of-line)
22598 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22599 (org-indent-line)
22600 (insert "# "))
22602 (defvar comment-empty-lines) ; From newcomment.el.
22603 (defun org-comment-or-uncomment-region (beg end &rest _)
22604 "Comment or uncomment each non-blank line in the region.
22605 Uncomment each non-blank line between BEG and END if it only
22606 contains commented lines. Otherwise, comment them."
22607 (save-restriction
22608 ;; Restrict region
22609 (narrow-to-region (save-excursion (goto-char beg)
22610 (skip-chars-forward " \r\t\n" end)
22611 (line-beginning-position))
22612 (save-excursion (goto-char end)
22613 (skip-chars-backward " \r\t\n" beg)
22614 (line-end-position)))
22615 (let ((uncommentp
22616 ;; UNCOMMENTP is non-nil when every non blank line between
22617 ;; BEG and END is a comment.
22618 (save-excursion
22619 (goto-char (point-min))
22620 (while (and (not (eobp))
22621 (let ((element (org-element-at-point)))
22622 (and (eq (org-element-type element) 'comment)
22623 (goto-char (min (point-max)
22624 (org-element-property
22625 :end element)))))))
22626 (eobp))))
22627 (if uncommentp
22628 ;; Only blank lines and comments in region: uncomment it.
22629 (save-excursion
22630 (goto-char (point-min))
22631 (while (not (eobp))
22632 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22633 (replace-match "" nil nil nil 1))
22634 (forward-line)))
22635 ;; Comment each line in region.
22636 (let ((min-indent (point-max)))
22637 ;; First find the minimum indentation across all lines.
22638 (save-excursion
22639 (goto-char (point-min))
22640 (while (and (not (eobp)) (not (zerop min-indent)))
22641 (unless (looking-at "[ \t]*$")
22642 (setq min-indent (min min-indent (current-indentation))))
22643 (forward-line)))
22644 ;; Then loop over all lines.
22645 (save-excursion
22646 (goto-char (point-min))
22647 (while (not (eobp))
22648 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22649 ;; Don't get fooled by invisible text (e.g. link path)
22650 ;; when moving to column MIN-INDENT.
22651 (let ((buffer-invisibility-spec nil))
22652 (org-move-to-column min-indent t))
22653 (insert comment-start))
22654 (forward-line))))))))
22657 ;;; Planning
22659 ;; This section contains tools to operate on timestamp objects, as
22660 ;; returned by, e.g. `org-element-context'.
22662 (defun org-timestamp-has-time-p (timestamp)
22663 "Non-nil when TIMESTAMP has a time specified."
22664 (org-element-property :hour-start timestamp))
22666 (defun org-timestamp-format (timestamp format &optional end zone)
22667 "Format a TIMESTAMP element into a string.
22669 FORMAT is a format specifier to be passed to
22670 `format-time-string'.
22672 When optional argument END is non-nil, use end of date-range or
22673 time-range, if possible.
22675 The optional ZONE is omitted or nil for Emacs local time, t for
22676 Universal Time, `wall' for system wall clock time, or a string as
22677 in the TZ environment variable. It can also be a list (as from
22678 `current-time-zone') or an integer (as from `decode-time')
22679 applied without consideration for daylight saving time."
22680 (format-time-string
22681 format
22682 (apply 'encode-time
22683 (cons 0
22684 (mapcar
22685 (lambda (prop) (or (org-element-property prop timestamp) 0))
22686 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22687 '(:minute-start :hour-start :day-start :month-start
22688 :year-start)))))
22689 zone))
22691 (defun org-timestamp-split-range (timestamp &optional end)
22692 "Extract a timestamp object from a date or time range.
22694 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22695 the end of the range. Otherwise, extract its start.
22697 Return a new timestamp object sharing the same parent as
22698 TIMESTAMP."
22699 (let ((type (org-element-property :type timestamp)))
22700 (if (memq type '(active inactive diary)) timestamp
22701 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22702 ;; Set new type.
22703 (org-element-put-property
22704 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22705 ;; Copy start properties over end properties if END is
22706 ;; non-nil. Otherwise, copy end properties over `start' ones.
22707 (let ((p-alist '((:minute-start . :minute-end)
22708 (:hour-start . :hour-end)
22709 (:day-start . :day-end)
22710 (:month-start . :month-end)
22711 (:year-start . :year-end))))
22712 (dolist (p-cell p-alist)
22713 (org-element-put-property
22714 split-ts
22715 (funcall (if end 'car 'cdr) p-cell)
22716 (org-element-property
22717 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22718 ;; Eventually refresh `:raw-value'.
22719 (org-element-put-property split-ts :raw-value nil)
22720 (org-element-put-property
22721 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22723 (defun org-timestamp-translate (timestamp &optional boundary)
22724 "Apply `org-translate-time' on a TIMESTAMP object.
22725 When optional argument BOUNDARY is non-nil, it is either the
22726 symbol `start' or `end'. In this case, only translate the
22727 starting or ending part of TIMESTAMP if it is a date or time
22728 range. Otherwise, translate both parts."
22729 (if (and (not boundary)
22730 (memq (org-element-property :type timestamp)
22731 '(active-range inactive-range)))
22732 (concat
22733 (org-translate-time
22734 (org-element-property :raw-value
22735 (org-timestamp-split-range timestamp)))
22736 "--"
22737 (org-translate-time
22738 (org-element-property :raw-value
22739 (org-timestamp-split-range timestamp t))))
22740 (org-translate-time
22741 (org-element-property
22742 :raw-value
22743 (if (not boundary) timestamp
22744 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22748 ;;; Other stuff.
22750 (defun org-toggle-fixed-width-section (arg)
22751 "Toggle the fixed-width export.
22752 If there is no active region, the QUOTE keyword at the current headline is
22753 inserted or removed. When present, it causes the text between this headline
22754 and the next to be exported as fixed-width text, and unmodified.
22755 If there is an active region, this command adds or removes a colon as the
22756 first character of this line. If the first character of a line is a colon,
22757 this line is also exported in fixed-width font."
22758 (interactive "P")
22759 (let* ((cc 0)
22760 (regionp (org-region-active-p))
22761 (beg (if regionp (region-beginning) (point)))
22762 (end (if regionp (region-end)))
22763 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22764 (case-fold-search nil)
22765 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22766 off)
22767 (if regionp
22768 (save-excursion
22769 (goto-char beg)
22770 (setq cc (current-column))
22771 (beginning-of-line 1)
22772 (setq off (looking-at re))
22773 (while (> nlines 0)
22774 (setq nlines (1- nlines))
22775 (beginning-of-line 1)
22776 (cond
22777 (arg
22778 (org-move-to-column cc t)
22779 (insert ": \n")
22780 (forward-line -1))
22781 ((and off (looking-at re))
22782 (replace-match "" t t nil 1))
22783 ((not off) (org-move-to-column cc t) (insert ": ")))
22784 (forward-line 1)))
22785 (save-excursion
22786 (org-back-to-heading)
22787 (cond
22788 ((looking-at (format org-heading-keyword-regexp-format
22789 org-quote-string))
22790 (goto-char (match-end 1))
22791 (looking-at (concat " +" org-quote-string))
22792 (replace-match "" t t)
22793 (when (eolp) (insert " ")))
22794 ((looking-at org-outline-regexp)
22795 (goto-char (match-end 0))
22796 (insert org-quote-string " ")))))))
22798 (defvar reftex-docstruct-symbol)
22799 (defvar reftex-cite-format)
22800 (defvar org--rds)
22802 (defun org-reftex-citation ()
22803 "Use reftex-citation to insert a citation into the buffer.
22804 This looks for a line like
22806 #+BIBLIOGRAPHY: foo plain option:-d
22808 and derives from it that foo.bib is the bibliography file relevant
22809 for this document. It then installs the necessary environment for RefTeX
22810 to work in this buffer and calls `reftex-citation' to insert a citation
22811 into the buffer.
22813 Export of such citations to both LaTeX and HTML is handled by the contributed
22814 package ox-bibtex by Taru Karttunen."
22815 (interactive)
22816 (let ((reftex-docstruct-symbol 'org--rds)
22817 (reftex-cite-format "\\cite{%l}")
22818 org--rds bib)
22819 (save-excursion
22820 (save-restriction
22821 (widen)
22822 (let ((case-fold-search t)
22823 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22824 (if (not (save-excursion
22825 (or (re-search-forward re nil t)
22826 (re-search-backward re nil t))))
22827 (error "No bibliography defined in file")
22828 (setq bib (concat (match-string 1) ".bib")
22829 org--rds (list (list 'bib bib)))))))
22830 (call-interactively 'reftex-citation)))
22832 ;;;; Functions extending outline functionality
22834 (defun org-beginning-of-line (&optional arg)
22835 "Go to the beginning of the current line. If that is invisible, continue
22836 to a visible line beginning. This makes the function of C-a more intuitive.
22837 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22838 first attempt, and only move to after the tags when the cursor is already
22839 beyond the end of the headline."
22840 (interactive "P")
22841 (let ((pos (point))
22842 (special (if (consp org-special-ctrl-a/e)
22843 (car org-special-ctrl-a/e)
22844 org-special-ctrl-a/e))
22845 deactivate-mark refpos)
22846 (if (org-bound-and-true-p visual-line-mode)
22847 (beginning-of-visual-line 1)
22848 (beginning-of-line 1))
22849 (if (and arg (fboundp 'move-beginning-of-line))
22850 (call-interactively 'move-beginning-of-line)
22851 (if (bobp)
22853 (backward-char 1)
22854 (if (org-truely-invisible-p)
22855 (while (and (not (bobp)) (org-truely-invisible-p))
22856 (backward-char 1)
22857 (beginning-of-line 1))
22858 (forward-char 1))))
22859 (when special
22860 (cond
22861 ((and (looking-at org-complex-heading-regexp)
22862 (= (char-after (match-end 1)) ?\ ))
22863 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22864 (point-at-eol)))
22865 (goto-char
22866 (if (eq special t)
22867 (cond ((> pos refpos) refpos)
22868 ((= pos (point)) refpos)
22869 (t (point)))
22870 (cond ((> pos (point)) (point))
22871 ((not (eq last-command this-command)) (point))
22872 (t refpos)))))
22873 ((org-at-item-p)
22874 ;; Being at an item and not looking at an the item means point
22875 ;; was previously moved to beginning of a visual line, which
22876 ;; doesn't contain the item. Therefore, do nothing special,
22877 ;; just stay here.
22878 (when (looking-at org-list-full-item-re)
22879 ;; Set special position at first white space character after
22880 ;; bullet, and check-box, if any.
22881 (let ((after-bullet
22882 (let ((box (match-end 3)))
22883 (if (not box) (match-end 1)
22884 (let ((after (char-after box)))
22885 (if (and after (= after ? )) (1+ box) box))))))
22886 ;; Special case: Move point to special position when
22887 ;; currently after it or at beginning of line.
22888 (if (eq special t)
22889 (when (or (> pos after-bullet) (= (point) pos))
22890 (goto-char after-bullet))
22891 ;; Reversed case: Move point to special position when
22892 ;; point was already at beginning of line and command is
22893 ;; repeated.
22894 (when (and (= (point) pos) (eq last-command this-command))
22895 (goto-char after-bullet))))))))
22896 (org-no-warnings
22897 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22898 (setq disable-point-adjustment
22899 (or (not (invisible-p (point)))
22900 (not (invisible-p (max (point-min) (1- (point))))))))
22902 (defun org-end-of-line (&optional arg)
22903 "Go to the end of the line.
22904 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22905 tags on the first attempt, and only move to after the tags when
22906 the cursor is already beyond the end of the headline."
22907 (interactive "P")
22908 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22909 org-special-ctrl-a/e))
22910 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22911 'end-of-visual-line)
22912 ((fboundp 'move-end-of-line) 'move-end-of-line)
22913 (t 'end-of-line)))
22914 deactivate-mark)
22915 (if (or (not special) arg) (call-interactively move-fun)
22916 (let* ((element (save-excursion (beginning-of-line)
22917 (org-element-at-point)))
22918 (type (org-element-type element)))
22919 (cond
22920 ((memq type '(headline inlinetask))
22921 (let ((pos (point)))
22922 (beginning-of-line 1)
22923 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22924 (if (eq special t)
22925 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22926 (goto-char (match-beginning 1))
22927 (goto-char (match-end 0)))
22928 (if (or (< pos (match-end 0))
22929 (not (eq this-command last-command)))
22930 (goto-char (match-end 0))
22931 (goto-char (match-beginning 1))))
22932 (call-interactively move-fun))))
22933 ((org-element-property :hiddenp element)
22934 ;; If element is hidden, `move-end-of-line' would put point
22935 ;; after it. Use `end-of-line' to stay on current line.
22936 (call-interactively 'end-of-line))
22937 (t (call-interactively move-fun)))))
22938 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22939 (setq disable-point-adjustment
22940 (or (not (invisible-p (point)))
22941 (not (invisible-p (max (point-min) (1- (point))))))))
22943 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22944 (define-key org-mode-map "\C-e" 'org-end-of-line)
22946 (defun org-backward-sentence (&optional _arg)
22947 "Go to beginning of sentence, or beginning of table field.
22948 This will call `backward-sentence' or `org-table-beginning-of-field',
22949 depending on context."
22950 (interactive)
22951 (cond
22952 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22953 (t (call-interactively 'backward-sentence))))
22955 (defun org-forward-sentence (&optional _arg)
22956 "Go to end of sentence, or end of table field.
22957 This will call `forward-sentence' or `org-table-end-of-field',
22958 depending on context."
22959 (interactive)
22960 (cond
22961 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22962 (t (call-interactively 'forward-sentence))))
22964 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22965 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22967 (defun org-kill-line (&optional _arg)
22968 "Kill line, to tags or end of line."
22969 (interactive)
22970 (cond
22971 ((or (not org-special-ctrl-k)
22972 (bolp)
22973 (not (org-at-heading-p)))
22974 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22975 org-ctrl-k-protect-subtree)
22976 (if (or (eq org-ctrl-k-protect-subtree 'error)
22977 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22978 (user-error "C-k aborted as it would kill a hidden subtree")))
22979 (call-interactively
22980 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22981 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22982 (kill-region (point) (match-beginning 1))
22983 (org-set-tags nil t))
22984 (t (kill-region (point) (point-at-eol)))))
22986 (define-key org-mode-map "\C-k" 'org-kill-line)
22988 (defun org-yank (&optional arg)
22989 "Yank. If the kill is a subtree, treat it specially.
22990 This command will look at the current kill and check if is a single
22991 subtree, or a series of subtrees[1]. If it passes the test, and if the
22992 cursor is at the beginning of a line or after the stars of a currently
22993 empty headline, then the yank is handled specially. How exactly depends
22994 on the value of the following variables, both set by default.
22996 org-yank-folded-subtrees
22997 When set, the subtree(s) will be folded after insertion, but only
22998 if doing so would now swallow text after the yanked text.
23000 org-yank-adjusted-subtrees
23001 When set, the subtree will be promoted or demoted in order to
23002 fit into the local outline tree structure, which means that the level
23003 will be adjusted so that it becomes the smaller one of the two
23004 *visible* surrounding headings.
23006 Any prefix to this command will cause `yank' to be called directly with
23007 no special treatment. In particular, a simple \\[universal-argument] prefix \
23008 will just
23009 plainly yank the text as it is.
23011 [1] The test checks if the first non-white line is a heading
23012 and if there are no other headings with fewer stars."
23013 (interactive "P")
23014 (org-yank-generic 'yank arg))
23016 (defun org-yank-generic (command arg)
23017 "Perform some yank-like command.
23019 This function implements the behavior described in the `org-yank'
23020 documentation. However, it has been generalized to work for any
23021 interactive command with similar behavior."
23023 ;; pretend to be command COMMAND
23024 (setq this-command command)
23026 (if arg
23027 (call-interactively command)
23029 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23030 (and (org-kill-is-subtree-p)
23031 (or (bolp)
23032 (and (looking-at "[ \t]*$")
23033 (string-match
23034 "\\`\\*+\\'"
23035 (buffer-substring (point-at-bol) (point)))))))
23036 swallowp)
23037 (cond
23038 ((and subtreep org-yank-folded-subtrees)
23039 (let ((beg (point))
23040 end)
23041 (if (and subtreep org-yank-adjusted-subtrees)
23042 (org-paste-subtree nil nil 'for-yank)
23043 (call-interactively command))
23045 (setq end (point))
23046 (goto-char beg)
23047 (when (and (bolp) subtreep
23048 (not (setq swallowp
23049 (org-yank-folding-would-swallow-text beg end))))
23050 (org-with-limited-levels
23051 (or (looking-at org-outline-regexp)
23052 (re-search-forward org-outline-regexp-bol end t))
23053 (while (and (< (point) end) (looking-at org-outline-regexp))
23054 (hide-subtree)
23055 (org-cycle-show-empty-lines 'folded)
23056 (condition-case nil
23057 (outline-forward-same-level 1)
23058 (error (goto-char end))))))
23059 (when swallowp
23060 (message
23061 "Inserted text not folded because that would swallow text"))
23063 (goto-char end)
23064 (skip-chars-forward " \t\n\r")
23065 (beginning-of-line 1)
23066 (push-mark beg 'nomsg)))
23067 ((and subtreep org-yank-adjusted-subtrees)
23068 (let ((beg (point-at-bol)))
23069 (org-paste-subtree nil nil 'for-yank)
23070 (push-mark beg 'nomsg)))
23072 (call-interactively command))))))
23074 (defun org-yank-folding-would-swallow-text (beg end)
23075 "Would hide-subtree at BEG swallow any text after END?"
23076 (let (level)
23077 (org-with-limited-levels
23078 (save-excursion
23079 (goto-char beg)
23080 (when (or (looking-at org-outline-regexp)
23081 (re-search-forward org-outline-regexp-bol end t))
23082 (setq level (org-outline-level)))
23083 (goto-char end)
23084 (skip-chars-forward " \t\r\n\v\f")
23085 (if (or (eobp)
23086 (and (bolp) (looking-at org-outline-regexp)
23087 (<= (org-outline-level) level)))
23088 nil ; Nothing would be swallowed
23089 t))))) ; something would swallow
23091 (define-key org-mode-map "\C-y" 'org-yank)
23093 (defun org-truely-invisible-p ()
23094 "Check if point is at a character currently not visible.
23095 This version does not only check the character property, but also
23096 `visible-mode'."
23097 ;; Early versions of noutline don't have `outline-invisible-p'.
23098 (if (org-bound-and-true-p visible-mode)
23100 (outline-invisible-p)))
23102 (defun org-invisible-p2 ()
23103 "Check if point is at a character currently not visible."
23104 (save-excursion
23105 (if (and (eolp) (not (bobp))) (backward-char 1))
23106 ;; Early versions of noutline don't have `outline-invisible-p'.
23107 (outline-invisible-p)))
23109 (defun org-back-to-heading (&optional invisible-ok)
23110 "Call `outline-back-to-heading', but provide a better error message."
23111 (condition-case nil
23112 (outline-back-to-heading invisible-ok)
23113 (error (error "Before first headline at position %d in buffer %s"
23114 (point) (current-buffer)))))
23116 (defun org-before-first-heading-p ()
23117 "Before first heading?"
23118 (save-excursion
23119 (end-of-line)
23120 (null (re-search-backward org-outline-regexp-bol nil t))))
23122 (defun org-at-heading-p (&optional ignored)
23123 (outline-on-heading-p t))
23124 ;; Compatibility alias with Org versions < 7.8.03
23125 (defalias 'org-on-heading-p 'org-at-heading-p)
23127 (defun org-at-comment-p nil
23128 "Is cursor in a line starting with a # character?"
23129 (save-excursion
23130 (beginning-of-line)
23131 (looking-at "^#")))
23133 (defun org-at-drawer-p nil
23134 "Is cursor at a drawer keyword?"
23135 (save-excursion
23136 (move-beginning-of-line 1)
23137 (looking-at org-drawer-regexp)))
23139 (defun org-at-block-p nil
23140 "Is cursor at a block keyword?"
23141 (save-excursion
23142 (move-beginning-of-line 1)
23143 (looking-at org-block-regexp)))
23145 (defun org-point-at-end-of-empty-headline ()
23146 "If point is at the end of an empty headline, return t, else nil.
23147 If the heading only contains a TODO keyword, it is still still considered
23148 empty."
23149 (and (looking-at "[ \t]*$")
23150 (when org-todo-line-regexp
23151 (save-excursion
23152 (beginning-of-line 1)
23153 (let ((case-fold-search nil))
23154 (looking-at org-todo-line-regexp)
23155 (string= (match-string 3) ""))))))
23157 (defun org-at-heading-or-item-p ()
23158 (or (org-at-heading-p) (org-at-item-p)))
23160 (defun org-at-target-p ()
23161 (or (org-in-regexp org-radio-target-regexp)
23162 (org-in-regexp org-target-regexp)))
23163 ;; Compatibility alias with Org versions < 7.8.03
23164 (defalias 'org-on-target-p 'org-at-target-p)
23166 (defun org-up-heading-all (arg)
23167 "Move to the heading line of which the present line is a subheading.
23168 This function considers both visible and invisible heading lines.
23169 With argument, move up ARG levels."
23170 (if (fboundp 'outline-up-heading-all)
23171 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23172 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23174 (defun org-up-heading-safe ()
23175 "Move to the heading line of which the present line is a subheading.
23176 This version will not throw an error. It will return the level of the
23177 headline found, or nil if no higher level is found.
23179 Also, this function will be a lot faster than `outline-up-heading',
23180 because it relies on stars being the outline starters. This can really
23181 make a significant difference in outlines with very many siblings."
23182 (let (start-level re)
23183 (org-back-to-heading t)
23184 (setq start-level (funcall outline-level))
23185 (if (equal start-level 1)
23187 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23188 (if (re-search-backward re nil t)
23189 (funcall outline-level)))))
23191 (defun org-first-sibling-p ()
23192 "Is this heading the first child of its parents?"
23193 (interactive)
23194 (let ((re org-outline-regexp-bol)
23195 level l)
23196 (unless (org-at-heading-p t)
23197 (user-error "Not at a heading"))
23198 (setq level (funcall outline-level))
23199 (save-excursion
23200 (if (not (re-search-backward re nil t))
23202 (setq l (funcall outline-level))
23203 (< l level)))))
23205 (defun org-goto-sibling (&optional previous)
23206 "Goto the next sibling, even if it is invisible.
23207 When PREVIOUS is set, go to the previous sibling instead. Returns t
23208 when a sibling was found. When none is found, return nil and don't
23209 move point."
23210 (let ((fun (if previous 're-search-backward 're-search-forward))
23211 (pos (point))
23212 (re org-outline-regexp-bol)
23213 level l)
23214 (when (condition-case nil (org-back-to-heading t) (error nil))
23215 (setq level (funcall outline-level))
23216 (catch 'exit
23217 (or previous (forward-char 1))
23218 (while (funcall fun re nil t)
23219 (setq l (funcall outline-level))
23220 (when (< l level) (goto-char pos) (throw 'exit nil))
23221 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23222 (goto-char pos)
23223 nil))))
23225 (defun org-show-siblings ()
23226 "Show all siblings of the current headline."
23227 (save-excursion
23228 (while (org-goto-sibling) (org-flag-heading nil)))
23229 (save-excursion
23230 (while (org-goto-sibling 'previous)
23231 (org-flag-heading nil))))
23233 (defun org-goto-first-child ()
23234 "Goto the first child, even if it is invisible.
23235 Return t when a child was found. Otherwise don't move point and
23236 return nil."
23237 (let (level (pos (point)) (re org-outline-regexp-bol))
23238 (when (condition-case nil (org-back-to-heading t) (error nil))
23239 (setq level (outline-level))
23240 (forward-char 1)
23241 (if (and (re-search-forward re nil t) (> (outline-level) level))
23242 (progn (goto-char (match-beginning 0)) t)
23243 (goto-char pos) nil))))
23245 (defun org-show-hidden-entry ()
23246 "Show an entry where even the heading is hidden."
23247 (save-excursion
23248 (org-show-entry)))
23250 (defun org-flag-heading (flag &optional entry)
23251 "Flag the current heading. FLAG non-nil means make invisible.
23252 When ENTRY is non-nil, show the entire entry."
23253 (save-excursion
23254 (org-back-to-heading t)
23255 ;; Check if we should show the entire entry
23256 (if entry
23257 (progn
23258 (org-show-entry)
23259 (save-excursion
23260 (and (outline-next-heading)
23261 (org-flag-heading nil))))
23262 (outline-flag-region (max (point-min) (1- (point)))
23263 (save-excursion (outline-end-of-heading) (point))
23264 flag))))
23266 (defun org-get-next-sibling ()
23267 "Move to next heading of the same level, and return point.
23268 If there is no such heading, return nil.
23269 This is like outline-next-sibling, but invisible headings are ok."
23270 (let ((level (funcall outline-level)))
23271 (outline-next-heading)
23272 (while (and (not (eobp)) (> (funcall outline-level) level))
23273 (outline-next-heading))
23274 (if (or (eobp) (< (funcall outline-level) level))
23276 (point))))
23278 (defun org-get-last-sibling ()
23279 "Move to previous heading of the same level, and return point.
23280 If there is no such heading, return nil."
23281 (let ((opoint (point))
23282 (level (funcall outline-level)))
23283 (outline-previous-heading)
23284 (when (and (/= (point) opoint) (outline-on-heading-p t))
23285 (while (and (> (funcall outline-level) level)
23286 (not (bobp)))
23287 (outline-previous-heading))
23288 (if (< (funcall outline-level) level)
23290 (point)))))
23292 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23293 "Goto to the end of a subtree."
23294 ;; This contains an exact copy of the original function, but it uses
23295 ;; `org-back-to-heading', to make it work also in invisible
23296 ;; trees. And is uses an invisible-ok argument.
23297 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23298 ;; Furthermore, when used inside Org, finding the end of a large subtree
23299 ;; with many children and grandchildren etc, this can be much faster
23300 ;; than the outline version.
23301 (org-back-to-heading invisible-ok)
23302 (let ((first t)
23303 (level (funcall outline-level)))
23304 (if (and (derived-mode-p 'org-mode) (< level 1000))
23305 ;; A true heading (not a plain list item), in Org-mode
23306 ;; This means we can easily find the end by looking
23307 ;; only for the right number of stars. Using a regexp to do
23308 ;; this is so much faster than using a Lisp loop.
23309 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23310 (forward-char 1)
23311 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23312 ;; something else, do it the slow way
23313 (while (and (not (eobp))
23314 (or first (> (funcall outline-level) level)))
23315 (setq first nil)
23316 (outline-next-heading)))
23317 (unless to-heading
23318 (if (memq (preceding-char) '(?\n ?\^M))
23319 (progn
23320 ;; Go to end of line before heading
23321 (forward-char -1)
23322 (if (memq (preceding-char) '(?\n ?\^M))
23323 ;; leave blank line before heading
23324 (forward-char -1))))))
23325 (point))
23327 (defun org-end-of-meta-data-and-drawers ()
23328 "Jump to the first text after meta data and drawers in the current entry.
23329 This will move over empty lines, lines with planning time stamps,
23330 clocking lines, and drawers."
23331 (org-back-to-heading t)
23332 (let ((end (save-excursion (outline-next-heading) (point)))
23333 (re (concat "\\(" org-drawer-regexp "\\)"
23334 "\\|" "[ \t]*" org-keyword-time-regexp)))
23335 (forward-line 1)
23336 (while (re-search-forward re end t)
23337 (if (not (match-end 1))
23338 ;; empty or planning line
23339 (forward-line 1)
23340 ;; a drawer, find the end
23341 (re-search-forward "^[ \t]*:END:" end 'move)
23342 (forward-line 1)))
23343 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23344 (point)))
23346 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23347 "Move forward to the ARG'th subheading at same level as this one.
23348 Stop at the first and last subheadings of a superior heading.
23349 Normally this only looks at visible headings, but when INVISIBLE-OK is
23350 non-nil it will also look at invisible ones."
23351 (interactive "p")
23352 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23353 (if (and arg (< arg 0))
23354 (goto-char (point-min))
23355 (outline-next-heading))
23356 (org-at-heading-p)
23357 (let ((level (- (match-end 0) (match-beginning 0) 1))
23358 (f (if (and arg (< arg 0))
23359 're-search-backward
23360 're-search-forward))
23361 (count (if arg (abs arg) 1))
23362 (result (point)))
23363 (while (and (prog1 (> count 0)
23364 (forward-char (if (and arg (< arg 0)) -1 1)))
23365 (funcall f org-outline-regexp-bol nil 'move))
23366 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23367 (cond ((< l level) (setq count 0))
23368 ((and (= l level)
23369 (or invisible-ok
23370 (progn
23371 (goto-char (line-beginning-position))
23372 (not (outline-invisible-p)))))
23373 (setq count (1- count))
23374 (when (eq l level)
23375 (setq result (point)))))))
23376 (goto-char result))
23377 (beginning-of-line 1)))
23379 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23380 "Move backward to the ARG'th subheading at same level as this one.
23381 Stop at the first and last subheadings of a superior heading."
23382 (interactive "p")
23383 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23385 (defun org-next-block (arg &optional backward block-regexp)
23386 "Jump to the next block.
23387 With a prefix argument ARG, jump forward ARG many source blocks.
23388 When BACKWARD is non-nil, jump to the previous block.
23389 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23390 (interactive "p")
23391 (let ((re (or block-regexp org-block-regexp))
23392 (re-search-fn (or (and backward 're-search-backward)
23393 're-search-forward)))
23394 (if (looking-at re) (forward-char 1))
23395 (condition-case nil
23396 (funcall re-search-fn re nil nil arg)
23397 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23398 (goto-char (match-beginning 0)) (org-show-context)))
23400 (defun org-previous-block (arg &optional block-regexp)
23401 "Jump to the previous block.
23402 With a prefix argument ARG, jump backward ARG many source blocks.
23403 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23404 (interactive "p")
23405 (org-next-block arg t block-regexp))
23407 (defun org-forward-paragraph ()
23408 "Move forward to beginning of next paragraph or equivalent.
23410 The function moves point to the beginning of the next visible
23411 structural element, which can be a paragraph, a table, a list
23412 item, etc. It also provides some special moves for convenience:
23414 - On an affiliated keyword, jump to the beginning of the
23415 relative element.
23416 - On an item or a footnote definition, move to the second
23417 element inside, if any.
23418 - On a table or a property drawer, jump after it.
23419 - On a verse or source block, stop after blank lines."
23420 (interactive)
23421 (when (eobp) (user-error "Cannot move further down"))
23422 (let* ((deactivate-mark nil)
23423 (element (org-element-at-point))
23424 (type (org-element-type element))
23425 (post-affiliated (org-element-property :post-affiliated element))
23426 (contents-begin (org-element-property :contents-begin element))
23427 (contents-end (org-element-property :contents-end element))
23428 (end (let ((end (org-element-property :end element)) (parent element))
23429 (while (and (setq parent (org-element-property :parent parent))
23430 (= (org-element-property :contents-end parent) end))
23431 (setq end (org-element-property :end parent)))
23432 end)))
23433 (cond ((not element)
23434 (skip-chars-forward " \r\t\n")
23435 (or (eobp) (beginning-of-line)))
23436 ;; On affiliated keywords, move to element's beginning.
23437 ((and post-affiliated (< (point) post-affiliated))
23438 (goto-char post-affiliated))
23439 ;; At a table row, move to the end of the table. Similarly,
23440 ;; at a node property, move to the end of the property
23441 ;; drawer.
23442 ((memq type '(node-property table-row))
23443 (goto-char (org-element-property
23444 :end (org-element-property :parent element))))
23445 ((memq type '(property-drawer table)) (goto-char end))
23446 ;; Consider blank lines as separators in verse and source
23447 ;; blocks to ease editing.
23448 ((memq type '(src-block verse-block))
23449 (when (eq type 'src-block)
23450 (setq contents-end
23451 (save-excursion (goto-char end)
23452 (skip-chars-backward " \r\t\n")
23453 (line-beginning-position))))
23454 (beginning-of-line)
23455 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23456 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23457 (goto-char end)
23458 (skip-chars-forward " \r\t\n")
23459 (if (= (point) contents-end) (goto-char end)
23460 (beginning-of-line))))
23461 ;; With no contents, just skip element.
23462 ((not contents-begin) (goto-char end))
23463 ;; If contents are invisible, skip the element altogether.
23464 ((outline-invisible-p (line-end-position))
23465 (case type
23466 (headline
23467 (org-with-limited-levels (outline-next-visible-heading 1)))
23468 ;; At a plain list, make sure we move to the next item
23469 ;; instead of skipping the whole list.
23470 (plain-list (forward-char)
23471 (org-forward-paragraph))
23472 (otherwise (goto-char end))))
23473 ((>= (point) contents-end) (goto-char end))
23474 ((>= (point) contents-begin)
23475 ;; This can only happen on paragraphs and plain lists.
23476 (case type
23477 (paragraph (goto-char end))
23478 ;; At a plain list, try to move to second element in
23479 ;; first item, if possible.
23480 (plain-list (end-of-line)
23481 (org-forward-paragraph))))
23482 ;; When contents start on the middle of a line (e.g. in
23483 ;; items and footnote definitions), try to reach first
23484 ;; element starting after current line.
23485 ((> (line-end-position) contents-begin)
23486 (end-of-line)
23487 (org-forward-paragraph))
23488 (t (goto-char contents-begin)))))
23490 (defun org-backward-paragraph ()
23491 "Move backward to start of previous paragraph or equivalent.
23493 The function moves point to the beginning of the current
23494 structural element, which can be a paragraph, a table, a list
23495 item, etc., or to the beginning of the previous visible one if
23496 point is already there. It also provides some special moves for
23497 convenience:
23499 - On an affiliated keyword, jump to the first one.
23500 - On a table or a property drawer, move to its beginning.
23501 - On a verse or source block, stop before blank lines."
23502 (interactive)
23503 (when (bobp) (user-error "Cannot move further up"))
23504 (let* ((deactivate-mark nil)
23505 (element (org-element-at-point))
23506 (type (org-element-type element))
23507 (contents-begin (org-element-property :contents-begin element))
23508 (contents-end (org-element-property :contents-end element))
23509 (post-affiliated (org-element-property :post-affiliated element))
23510 (begin (org-element-property :begin element)))
23511 (cond
23512 ((not element) (goto-char (point-min)))
23513 ((= (point) begin)
23514 (backward-char)
23515 (org-backward-paragraph))
23516 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23517 ((memq type '(node-property table-row))
23518 (goto-char (org-element-property
23519 :post-affiliated (org-element-property :parent element))))
23520 ((memq type '(property-drawer table)) (goto-char begin))
23521 ((memq type '(src-block verse-block))
23522 (when (eq type 'src-block)
23523 (setq contents-begin
23524 (save-excursion (goto-char begin) (forward-line) (point))))
23525 (if (= (point) contents-begin) (goto-char post-affiliated)
23526 ;; Inside a verse block, see blank lines as paragraph
23527 ;; separators.
23528 (let ((origin (point)))
23529 (skip-chars-backward " \r\t\n" contents-begin)
23530 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23531 (skip-chars-forward " \r\t\n" origin)
23532 (if (= (point) origin) (goto-char contents-begin)
23533 (beginning-of-line))))))
23534 ((not contents-begin) (goto-char (or post-affiliated begin)))
23535 ((eq type 'paragraph)
23536 (goto-char contents-begin)
23537 ;; When at first paragraph in an item or a footnote definition,
23538 ;; move directly to beginning of line.
23539 (let ((parent-contents
23540 (org-element-property
23541 :contents-begin (org-element-property :parent element))))
23542 (when (and parent-contents (= parent-contents contents-begin))
23543 (beginning-of-line))))
23544 ;; At the end of a greater element, move to the beginning of the
23545 ;; last element within.
23546 ((>= (point) contents-end)
23547 (goto-char (1- contents-end))
23548 (org-backward-paragraph))
23549 (t (goto-char (or post-affiliated begin))))
23550 ;; Ensure we never leave point invisible.
23551 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23553 (defun org-forward-element ()
23554 "Move forward by one element.
23555 Move to the next element at the same level, when possible."
23556 (interactive)
23557 (cond ((eobp) (user-error "Cannot move further down"))
23558 ((org-with-limited-levels (org-at-heading-p))
23559 (let ((origin (point)))
23560 (goto-char (org-end-of-subtree nil t))
23561 (unless (org-with-limited-levels (org-at-heading-p))
23562 (goto-char origin)
23563 (user-error "Cannot move further down"))))
23565 (let* ((elem (org-element-at-point))
23566 (end (org-element-property :end elem))
23567 (parent (org-element-property :parent elem)))
23568 (cond ((and parent (= (org-element-property :contents-end parent) end))
23569 (goto-char (org-element-property :end parent)))
23570 ((integer-or-marker-p end) (goto-char end))
23571 (t (message "No element at point")))))))
23573 (defun org-backward-element ()
23574 "Move backward by one element.
23575 Move to the previous element at the same level, when possible."
23576 (interactive)
23577 (cond ((bobp) (user-error "Cannot move further up"))
23578 ((org-with-limited-levels (org-at-heading-p))
23579 ;; At a headline, move to the previous one, if any, or stay
23580 ;; here.
23581 (let ((origin (point)))
23582 (org-with-limited-levels (org-backward-heading-same-level 1))
23583 ;; When current headline has no sibling above, move to its
23584 ;; parent.
23585 (when (= (point) origin)
23586 (or (org-with-limited-levels (org-up-heading-safe))
23587 (progn (goto-char origin)
23588 (user-error "Cannot move further up"))))))
23590 (let* ((trail (org-element-at-point 'keep-trail))
23591 (elem (car trail))
23592 (prev-elem (nth 1 trail))
23593 (beg (org-element-property :begin elem)))
23594 (cond
23595 ;; Move to beginning of current element if point isn't
23596 ;; there already.
23597 ((null beg) (message "No element at point"))
23598 ((/= (point) beg) (goto-char beg))
23599 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23600 ((org-before-first-heading-p) (goto-char (point-min)))
23601 (t (org-back-to-heading)))))))
23603 (defun org-up-element ()
23604 "Move to upper element."
23605 (interactive)
23606 (if (org-with-limited-levels (org-at-heading-p))
23607 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23608 (let* ((elem (org-element-at-point))
23609 (parent (org-element-property :parent elem)))
23610 (if parent (goto-char (org-element-property :begin parent))
23611 (if (org-with-limited-levels (org-before-first-heading-p))
23612 (user-error "No surrounding element")
23613 (org-with-limited-levels (org-back-to-heading)))))))
23615 (defvar org-element-greater-elements)
23616 (defun org-down-element ()
23617 "Move to inner element."
23618 (interactive)
23619 (let ((element (org-element-at-point)))
23620 (cond
23621 ((memq (org-element-type element) '(plain-list table))
23622 (goto-char (org-element-property :contents-begin element))
23623 (forward-char))
23624 ((memq (org-element-type element) org-element-greater-elements)
23625 ;; If contents are hidden, first disclose them.
23626 (when (org-element-property :hiddenp element) (org-cycle))
23627 (goto-char (or (org-element-property :contents-begin element)
23628 (user-error "No content for this element"))))
23629 (t (user-error "No inner element")))))
23631 (defun org-drag-element-backward ()
23632 "Move backward element at point."
23633 (interactive)
23634 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23635 (let* ((trail (org-element-at-point 'keep-trail))
23636 (elem (car trail))
23637 (prev-elem (nth 1 trail)))
23638 ;; Error out if no previous element or previous element is
23639 ;; a parent of the current one.
23640 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23641 (user-error "Cannot drag element backward")
23642 (let ((pos (point)))
23643 (org-element-swap-A-B prev-elem elem)
23644 (goto-char (+ (org-element-property :begin prev-elem)
23645 (- pos (org-element-property :begin elem)))))))))
23647 (defun org-drag-element-forward ()
23648 "Move forward element at point."
23649 (interactive)
23650 (let* ((pos (point))
23651 (elem (org-element-at-point)))
23652 (when (= (point-max) (org-element-property :end elem))
23653 (user-error "Cannot drag element forward"))
23654 (goto-char (org-element-property :end elem))
23655 (let ((next-elem (org-element-at-point)))
23656 (when (or (org-element-nested-p elem next-elem)
23657 (and (eq (org-element-type next-elem) 'headline)
23658 (not (eq (org-element-type elem) 'headline))))
23659 (goto-char pos)
23660 (user-error "Cannot drag element forward"))
23661 ;; Compute new position of point: it's shifted by NEXT-ELEM
23662 ;; body's length (without final blanks) and by the length of
23663 ;; blanks between ELEM and NEXT-ELEM.
23664 (let ((size-next (- (save-excursion
23665 (goto-char (org-element-property :end next-elem))
23666 (skip-chars-backward " \r\t\n")
23667 (forward-line)
23668 ;; Small correction if buffer doesn't end
23669 ;; with a newline character.
23670 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23671 (org-element-property :begin next-elem)))
23672 (size-blank (- (org-element-property :end elem)
23673 (save-excursion
23674 (goto-char (org-element-property :end elem))
23675 (skip-chars-backward " \r\t\n")
23676 (forward-line)
23677 (point)))))
23678 (org-element-swap-A-B elem next-elem)
23679 (goto-char (+ pos size-next size-blank))))))
23681 (defun org-drag-line-forward (arg)
23682 "Drag the line at point ARG lines forward."
23683 (interactive "p")
23684 (dotimes (n (abs arg))
23685 (let ((c (current-column)))
23686 (if (< 0 arg)
23687 (progn
23688 (beginning-of-line 2)
23689 (transpose-lines 1)
23690 (beginning-of-line 0))
23691 (transpose-lines 1)
23692 (beginning-of-line -1))
23693 (org-move-to-column c))))
23695 (defun org-drag-line-backward (arg)
23696 "Drag the line at point ARG lines backward."
23697 (interactive "p")
23698 (org-drag-line-forward (- arg)))
23700 (defun org-mark-element ()
23701 "Put point at beginning of this element, mark at end.
23703 Interactively, if this command is repeated or (in Transient Mark
23704 mode) if the mark is active, it marks the next element after the
23705 ones already marked."
23706 (interactive)
23707 (let (deactivate-mark)
23708 (if (and (org-called-interactively-p 'any)
23709 (or (and (eq last-command this-command) (mark t))
23710 (and transient-mark-mode mark-active)))
23711 (set-mark
23712 (save-excursion
23713 (goto-char (mark))
23714 (goto-char (org-element-property :end (org-element-at-point)))))
23715 (let ((element (org-element-at-point)))
23716 (end-of-line)
23717 (push-mark (org-element-property :end element) t t)
23718 (goto-char (org-element-property :begin element))))))
23720 (defun org-narrow-to-element ()
23721 "Narrow buffer to current element."
23722 (interactive)
23723 (let ((elem (org-element-at-point)))
23724 (cond
23725 ((eq (car elem) 'headline)
23726 (narrow-to-region
23727 (org-element-property :begin elem)
23728 (org-element-property :end elem)))
23729 ((memq (car elem) org-element-greater-elements)
23730 (narrow-to-region
23731 (org-element-property :contents-begin elem)
23732 (org-element-property :contents-end elem)))
23734 (narrow-to-region
23735 (org-element-property :begin elem)
23736 (org-element-property :end elem))))))
23738 (defun org-transpose-element ()
23739 "Transpose current and previous elements, keeping blank lines between.
23740 Point is moved after both elements."
23741 (interactive)
23742 (org-skip-whitespace)
23743 (let ((end (org-element-property :end (org-element-at-point))))
23744 (org-drag-element-backward)
23745 (goto-char end)))
23747 (defun org-unindent-buffer ()
23748 "Un-indent the visible part of the buffer.
23749 Relative indentation (between items, inside blocks, etc.) isn't
23750 modified."
23751 (interactive)
23752 (unless (eq major-mode 'org-mode)
23753 (user-error "Cannot un-indent a buffer not in Org mode"))
23754 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23755 unindent-tree ; For byte-compiler.
23756 (unindent-tree
23757 (function
23758 (lambda (contents)
23759 (mapc
23760 (lambda (element)
23761 (if (memq (org-element-type element) '(headline section))
23762 (funcall unindent-tree (org-element-contents element))
23763 (save-excursion
23764 (save-restriction
23765 (narrow-to-region
23766 (org-element-property :begin element)
23767 (org-element-property :end element))
23768 (org-do-remove-indentation)))))
23769 (reverse contents))))))
23770 (funcall unindent-tree (org-element-contents parse-tree))))
23772 (defun org-show-subtree ()
23773 "Show everything after this heading at deeper levels."
23774 (interactive)
23775 (outline-flag-region
23776 (point)
23777 (save-excursion
23778 (org-end-of-subtree t t))
23779 nil))
23781 (defun org-show-entry ()
23782 "Show the body directly following this heading.
23783 Show the heading too, if it is currently invisible."
23784 (interactive)
23785 (save-excursion
23786 (condition-case nil
23787 (progn
23788 (org-back-to-heading t)
23789 (outline-flag-region
23790 (max (point-min) (1- (point)))
23791 (save-excursion
23792 (if (re-search-forward
23793 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23794 (match-beginning 1)
23795 (point-max)))
23796 nil)
23797 (org-cycle-hide-drawers 'children))
23798 (error nil))))
23800 (defun org-make-options-regexp (kwds &optional extra)
23801 "Make a regular expression for keyword lines."
23802 (concat
23803 "^#\\+\\("
23804 (mapconcat 'regexp-quote kwds "\\|")
23805 (if extra (concat "\\|" extra))
23806 "\\):[ \t]*\\(.*\\)"))
23808 ;; Make isearch reveal the necessary context
23809 (defun org-isearch-end ()
23810 "Reveal context after isearch exits."
23811 (when isearch-success ; only if search was successful
23812 (if (featurep 'xemacs)
23813 ;; Under XEmacs, the hook is run in the correct place,
23814 ;; we directly show the context.
23815 (org-show-context 'isearch)
23816 ;; In Emacs the hook runs *before* restoring the overlays.
23817 ;; So we have to use a one-time post-command-hook to do this.
23818 ;; (Emacs 22 has a special variable, see function `org-mode')
23819 (unless (and (boundp 'isearch-mode-end-hook-quit)
23820 isearch-mode-end-hook-quit)
23821 ;; Only when the isearch was not quitted.
23822 (org-add-hook 'post-command-hook 'org-isearch-post-command
23823 'append 'local)))))
23825 (defun org-isearch-post-command ()
23826 "Remove self from hook, and show context."
23827 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23828 (org-show-context 'isearch))
23831 ;;;; Integration with and fixes for other packages
23833 ;;; Imenu support
23835 (defvar org-imenu-markers nil
23836 "All markers currently used by Imenu.")
23837 (make-variable-buffer-local 'org-imenu-markers)
23839 (defun org-imenu-new-marker (&optional pos)
23840 "Return a new marker for use by Imenu, and remember the marker."
23841 (let ((m (make-marker)))
23842 (move-marker m (or pos (point)))
23843 (push m org-imenu-markers)
23846 (defun org-imenu-get-tree ()
23847 "Produce the index for Imenu."
23848 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23849 (setq org-imenu-markers nil)
23850 (let* ((n org-imenu-depth)
23851 (re (concat "^" (org-get-limited-outline-regexp)))
23852 (subs (make-vector (1+ n) nil))
23853 (last-level 0)
23854 m level head0 head)
23855 (save-excursion
23856 (save-restriction
23857 (widen)
23858 (goto-char (point-max))
23859 (while (re-search-backward re nil t)
23860 (setq level (org-reduced-level (funcall outline-level)))
23861 (when (and (<= level n)
23862 (looking-at org-complex-heading-regexp)
23863 (setq head0 (org-match-string-no-properties 4)))
23864 (setq head (org-link-display-format head0)
23865 m (org-imenu-new-marker))
23866 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23867 (if (>= level last-level)
23868 (push (cons head m) (aref subs level))
23869 (push (cons head (aref subs (1+ level))) (aref subs level))
23870 (loop for i from (1+ level) to n do (aset subs i nil)))
23871 (setq last-level level)))))
23872 (aref subs 1)))
23874 (eval-after-load "imenu"
23875 '(progn
23876 (add-hook 'imenu-after-jump-hook
23877 (lambda ()
23878 (if (derived-mode-p 'org-mode)
23879 (org-show-context 'org-goto))))))
23881 (defun org-link-display-format (link)
23882 "Replace a link with its the description.
23883 If there is no description, use the link target."
23884 (save-match-data
23885 (if (string-match org-bracket-link-analytic-regexp link)
23886 (replace-match (if (match-end 5)
23887 (match-string 5 link)
23888 (concat (match-string 1 link)
23889 (match-string 3 link)))
23890 nil t link)
23891 link)))
23893 (defun org-toggle-link-display ()
23894 "Toggle the literal or descriptive display of links."
23895 (interactive)
23896 (if org-descriptive-links
23897 (progn (org-remove-from-invisibility-spec '(org-link))
23898 (org-restart-font-lock)
23899 (setq org-descriptive-links nil))
23900 (progn (add-to-invisibility-spec '(org-link))
23901 (org-restart-font-lock)
23902 (setq org-descriptive-links t))))
23904 ;; Speedbar support
23906 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23907 "Overlay marking the agenda restriction line in speedbar.")
23908 (overlay-put org-speedbar-restriction-lock-overlay
23909 'face 'org-agenda-restriction-lock)
23910 (overlay-put org-speedbar-restriction-lock-overlay
23911 'help-echo "Agendas are currently limited to this item.")
23912 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23914 (defun org-speedbar-set-agenda-restriction ()
23915 "Restrict future agenda commands to the location at point in speedbar.
23916 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23917 (interactive)
23918 (require 'org-agenda)
23919 (let (p m tp np dir txt)
23920 (cond
23921 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23922 'org-imenu t))
23923 (setq m (get-text-property p 'org-imenu-marker))
23924 (with-current-buffer (marker-buffer m)
23925 (goto-char m)
23926 (org-agenda-set-restriction-lock 'subtree)))
23927 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23928 'speedbar-function 'speedbar-find-file))
23929 (setq tp (previous-single-property-change
23930 (1+ p) 'speedbar-function)
23931 np (next-single-property-change
23932 tp 'speedbar-function)
23933 dir (speedbar-line-directory)
23934 txt (buffer-substring-no-properties (or tp (point-min))
23935 (or np (point-max))))
23936 (with-current-buffer (find-file-noselect
23937 (let ((default-directory dir))
23938 (expand-file-name txt)))
23939 (unless (derived-mode-p 'org-mode)
23940 (user-error "Cannot restrict to non-Org-mode file"))
23941 (org-agenda-set-restriction-lock 'file)))
23942 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23943 (move-overlay org-speedbar-restriction-lock-overlay
23944 (point-at-bol) (point-at-eol))
23945 (setq current-prefix-arg nil)
23946 (org-agenda-maybe-redo)))
23948 (defvar speedbar-file-key-map)
23949 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23950 (eval-after-load "speedbar"
23951 '(progn
23952 (speedbar-add-supported-extension ".org")
23953 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23954 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23955 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23956 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23957 (add-hook 'speedbar-visiting-tag-hook
23958 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23960 ;;; Fixes and Hacks for problems with other packages
23962 ;; Make flyspell not check words in links, to not mess up our keymap
23963 (defvar org-element-affiliated-keywords) ; From org-element.el
23964 (defvar org-element-block-name-alist) ; From org-element.el
23965 (defun org-mode-flyspell-verify ()
23966 "Don't let flyspell put overlays at active buttons, or on
23967 {todo,all-time,additional-option-like}-keywords."
23968 (require 'org-element) ; For `org-element-affiliated-keywords'
23969 (let ((pos (max (1- (point)) (point-min)))
23970 (word (thing-at-point 'word)))
23971 (and (not (get-text-property pos 'keymap))
23972 (not (get-text-property pos 'org-no-flyspell))
23973 (not (member word org-todo-keywords-1))
23974 (not (member word org-all-time-keywords))
23975 (not (member word org-options-keywords))
23976 (not (member word (mapcar 'car org-startup-options)))
23977 (not (member-ignore-case word org-element-affiliated-keywords))
23978 (not (member-ignore-case word (org-get-export-keywords)))
23979 (not (member-ignore-case
23980 word (mapcar 'car org-element-block-name-alist)))
23981 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23982 (not (org-in-src-block-p)))))
23984 (defun org-remove-flyspell-overlays-in (beg end)
23985 "Remove flyspell overlays in region."
23986 (and (org-bound-and-true-p flyspell-mode)
23987 (fboundp 'flyspell-delete-region-overlays)
23988 (flyspell-delete-region-overlays beg end))
23989 (add-text-properties beg end '(org-no-flyspell t)))
23991 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23992 (eval-after-load "bookmark"
23993 '(if (boundp 'bookmark-after-jump-hook)
23994 ;; We can use the hook
23995 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23996 ;; Hook not available, use advice
23997 (defadvice bookmark-jump (after org-make-visible activate)
23998 "Make the position visible."
23999 (org-bookmark-jump-unhide))))
24001 ;; Make sure saveplace shows the location if it was hidden
24002 (eval-after-load "saveplace"
24003 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24004 "Make the position visible."
24005 (org-bookmark-jump-unhide)))
24007 ;; Make sure ecb shows the location if it was hidden
24008 (eval-after-load "ecb"
24009 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24010 "Make hierarchy visible when jumping into location from ECB tree buffer."
24011 (if (derived-mode-p 'org-mode)
24012 (org-show-context))))
24014 (defun org-bookmark-jump-unhide ()
24015 "Unhide the current position, to show the bookmark location."
24016 (and (derived-mode-p 'org-mode)
24017 (or (outline-invisible-p)
24018 (save-excursion (goto-char (max (point-min) (1- (point))))
24019 (outline-invisible-p)))
24020 (org-show-context 'bookmark-jump)))
24022 ;; Make session.el ignore our circular variable
24023 (defvar session-globals-exclude)
24024 (eval-after-load "session"
24025 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24027 ;;;; Finish up
24029 (provide 'org)
24031 (run-hooks 'org-load-hook)
24033 ;;; org.el ends here