org.el (org-store-link): When a bracket link is found in a headline, use the link...
[org-mode.git] / lisp / org.el
blob0afa3d9017a73d9212345fb34201e753ae5c125e
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu 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-binding in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
120 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
121 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
123 (declare-function orgtbl-mode "org-table" (&optional arg))
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-beamer-mode "ox-beamer" ())
126 (declare-function org-table-edit-field "org-table" (arg))
127 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
128 (declare-function org-table-set-constants "org-table" ())
129 (declare-function org-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-agenda-redo "org-agenda" (&optional all))
134 (declare-function org-table-align "org-table" ())
135 (declare-function org-table-paste-rectangle "org-table" ())
136 (declare-function org-table-maybe-eval-formula "org-table" ())
137 (declare-function org-table-maybe-recalculate-line "org-table" ())
139 (declare-function org-element--parse-objects "org-element"
140 (beg end acc restriction))
141 (declare-function org-element-at-point "org-element" (&optional keep-trail))
142 (declare-function org-element-contents "org-element" (element))
143 (declare-function org-element-context "org-element" (&optional element))
144 (declare-function org-element-interpret-data "org-element"
145 (data &optional parent))
146 (declare-function org-element-map "org-element"
147 (data types fun &optional info first-match no-recursion))
148 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
149 (declare-function org-element-parse-buffer "org-element"
150 (&optional granularity visible-only))
151 (declare-function org-element-property "org-element" (property element))
152 (declare-function org-element-put-property "org-element"
153 (element property value))
154 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
155 (declare-function org-element--parse-objects "org-element"
156 (beg end acc restriction))
157 (declare-function org-element-parse-buffer "org-element"
158 (&optional granularity visible-only))
159 (declare-function org-element-restriction "org-element" (element))
160 (declare-function org-element-type "org-element" (element))
162 ;; load languages based on value of `org-babel-load-languages'
163 (defvar org-babel-load-languages)
165 ;;;###autoload
166 (defun org-babel-do-load-languages (sym value)
167 "Load the languages defined in `org-babel-load-languages'."
168 (set-default sym value)
169 (mapc (lambda (pair)
170 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
171 (if active
172 (progn
173 (require (intern (concat "ob-" lang))))
174 (progn
175 (funcall 'fmakunbound
176 (intern (concat "org-babel-execute:" lang)))
177 (funcall 'fmakunbound
178 (intern (concat "org-babel-expand-body:" lang)))))))
179 org-babel-load-languages))
181 ;;;###autoload
182 (defun org-babel-load-file (file &optional compile)
183 "Load Emacs Lisp source code blocks in the Org-mode FILE.
184 This function exports the source code using `org-babel-tangle'
185 and then loads the resulting file using `load-file'. With prefix
186 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
187 file to byte-code before it is loaded."
188 (interactive "fFile to load: \nP")
189 (require 'ob-core)
190 (let* ((age (lambda (file)
191 (float-time
192 (time-subtract (current-time)
193 (nth 5 (or (file-attributes (file-truename file))
194 (file-attributes file)))))))
195 (base-name (file-name-sans-extension file))
196 (exported-file (concat base-name ".el")))
197 ;; tangle if the org-mode file is newer than the elisp file
198 (unless (and (file-exists-p exported-file)
199 (> (funcall age file) (funcall age exported-file)))
200 (org-babel-tangle-file file exported-file "emacs-lisp"))
201 (message "%s %s"
202 (if compile
203 (progn (byte-compile-file exported-file 'load)
204 "Compiled and loaded")
205 (progn (load-file exported-file) "Loaded"))
206 exported-file)))
208 (defcustom org-babel-load-languages '((emacs-lisp . t))
209 "Languages which can be evaluated in Org-mode buffers.
210 This list can be used to load support for any of the languages
211 below, note that each language will depend on a different set of
212 system executables and/or Emacs modes. When a language is
213 \"loaded\", then code blocks in that language can be evaluated
214 with `org-babel-execute-src-block' bound by default to C-c
215 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
216 be set to remove code block evaluation from the C-c C-c
217 keybinding. By default only Emacs Lisp (which has no
218 requirements) is loaded."
219 :group 'org-babel
220 :set 'org-babel-do-load-languages
221 :version "24.1"
222 :type '(alist :tag "Babel Languages"
223 :key-type
224 (choice
225 (const :tag "Awk" awk)
226 (const :tag "C" C)
227 (const :tag "R" R)
228 (const :tag "Asymptote" asymptote)
229 (const :tag "Calc" calc)
230 (const :tag "Clojure" clojure)
231 (const :tag "CSS" css)
232 (const :tag "Ditaa" ditaa)
233 (const :tag "Dot" dot)
234 (const :tag "Emacs Lisp" emacs-lisp)
235 (const :tag "Fortran" fortran)
236 (const :tag "Gnuplot" gnuplot)
237 (const :tag "Haskell" haskell)
238 (const :tag "IO" io)
239 (const :tag "Java" java)
240 (const :tag "Javascript" js)
241 (const :tag "LaTeX" latex)
242 (const :tag "Ledger" ledger)
243 (const :tag "Lilypond" lilypond)
244 (const :tag "Lisp" lisp)
245 (const :tag "Makefile" makefile)
246 (const :tag "Maxima" maxima)
247 (const :tag "Matlab" matlab)
248 (const :tag "Mscgen" mscgen)
249 (const :tag "Ocaml" ocaml)
250 (const :tag "Octave" octave)
251 (const :tag "Org" org)
252 (const :tag "Perl" perl)
253 (const :tag "Pico Lisp" picolisp)
254 (const :tag "PlantUML" plantuml)
255 (const :tag "Python" python)
256 (const :tag "Ruby" ruby)
257 (const :tag "Sass" sass)
258 (const :tag "Scala" scala)
259 (const :tag "Scheme" scheme)
260 (const :tag "Screen" screen)
261 (const :tag "Shell Script" sh)
262 (const :tag "Shen" shen)
263 (const :tag "Sql" sql)
264 (const :tag "Sqlite" sqlite))
265 :value-type (boolean :tag "Activate" :value t)))
267 ;;;; Customization variables
268 (defcustom org-clone-delete-id nil
269 "Remove ID property of clones of a subtree.
270 When non-nil, clones of a subtree don't inherit the ID property.
271 Otherwise they inherit the ID property with a new unique
272 identifier."
273 :type 'boolean
274 :version "24.1"
275 :group 'org-id)
277 ;;; Version
278 (org-check-version)
280 ;;;###autoload
281 (defun org-version (&optional here full message)
282 "Show the org-mode version in the echo area.
283 With prefix argument HERE, insert it at point.
284 When FULL is non-nil, use a verbose version string.
285 When MESSAGE is non-nil, display a message with the version."
286 (interactive "P")
287 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
288 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
289 (load-suffixes (list ".el"))
290 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
291 (org-trash (or
292 (and (fboundp 'org-release) (fboundp 'org-git-version))
293 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
294 (load-suffixes save-load-suffixes)
295 (org-version (org-release))
296 (git-version (org-git-version))
297 (version (format "Org-mode version %s (%s @ %s)"
298 org-version
299 git-version
300 (if org-install-dir
301 (if (string= org-dir org-install-dir)
302 org-install-dir
303 (concat "mixed installation! " org-install-dir " and " org-dir))
304 "org-loaddefs.el can not be found!")))
305 (_version (if full version org-version)))
306 (if (org-called-interactively-p 'interactive)
307 (if here
308 (insert version)
309 (message version))
310 (if message (message _version))
311 _version)))
313 (defconst org-version (org-version))
315 ;;; Compatibility constants
317 ;;; The custom variables
319 (defgroup org nil
320 "Outline-based notes management and organizer."
321 :tag "Org"
322 :group 'outlines
323 :group 'calendar)
325 (defcustom org-mode-hook nil
326 "Mode hook for Org-mode, run after the mode was turned on."
327 :group 'org
328 :type 'hook)
330 (defcustom org-load-hook nil
331 "Hook that is run after org.el has been loaded."
332 :group 'org
333 :type 'hook)
335 (defcustom org-log-buffer-setup-hook nil
336 "Hook that is run after an Org log buffer is created."
337 :group 'org
338 :version "24.1"
339 :type 'hook)
341 (defvar org-modules) ; defined below
342 (defvar org-modules-loaded nil
343 "Have the modules been loaded already?")
345 (defun org-load-modules-maybe (&optional force)
346 "Load all extensions listed in `org-modules'."
347 (when (or force (not org-modules-loaded))
348 (mapc (lambda (ext)
349 (condition-case nil (require ext)
350 (error (message "Problems while trying to load feature `%s'" ext))))
351 org-modules)
352 (setq org-modules-loaded t)))
354 (defun org-set-modules (var value)
355 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
356 (set var value)
357 (when (featurep 'org)
358 (org-load-modules-maybe 'force)))
360 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
361 "Modules that should always be loaded together with org.el.
363 If a description starts with <C>, the file is not part of Emacs
364 and loading it will require that you have downloaded and properly
365 installed the Org mode distribution.
367 You can also use this system to load external packages (i.e. neither Org
368 core modules, nor modules from the CONTRIB directory). Just add symbols
369 to the end of the list. If the package is called org-xyz.el, then you need
370 to add the symbol `xyz', and the package must have a call to:
372 \(provide 'org-xyz)
374 For export specific modules, see also `org-export-backends'."
375 :group 'org
376 :set 'org-set-modules
377 :version "24.4"
378 :package-version '(Org . "8.0")
379 :type
380 '(set :greedy t
381 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
382 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
383 (const :tag " crypt: Encryption of subtrees" org-crypt)
384 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
385 (const :tag " docview: Links to doc-view buffers" org-docview)
386 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
387 (const :tag " habit: Track your consistency with habits" org-habit)
388 (const :tag " id: Global IDs for identifying entries" org-id)
389 (const :tag " info: Links to Info nodes" org-info)
390 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
391 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
392 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
393 (const :tag " mouse: Additional mouse support" org-mouse)
394 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
395 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
396 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
398 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
399 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
400 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
401 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
402 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
403 (const :tag "C collector: Collect properties into tables" org-collector)
404 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
405 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
406 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
407 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
408 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
409 (const :tag "C eval: Include command output as text" org-eval)
410 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
411 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
412 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
413 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
414 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
415 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
416 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
417 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
418 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
419 (const :tag "C mac-message: Links to messages in Apple Mail" org-mac-message)
420 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
421 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
422 (const :tag "C mew: Links to Mew folders/messages" org-mew)
423 (const :tag "C mtags: Support for muse-like tags" org-mtags)
424 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
425 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
426 (const :tag "C registry: A registry for Org-mode links" org-registry)
427 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
428 (const :tag "C secretary: Team management with org-mode" org-secretary)
429 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
430 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
431 (const :tag "C track: Keep up with Org-mode development" org-track)
432 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
433 (const :tag "C vm: Links to VM folders/messages" org-vm)
434 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
435 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
436 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
438 (defvar org-export-registered-backends) ; From ox.el
439 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
440 (defcustom org-export-backends '(ascii html icalendar latex)
441 "List of export back-ends that should be always available.
443 If a description starts with <C>, the file is not part of Emacs
444 and loading it will require that you have downloaded and properly
445 installed the Org mode distribution.
447 Unlike to `org-modules', libraries in this list will not be
448 loaded along with Org, but only once the export framework is
449 needed.
451 This variable needs to be set before org.el is loaded. If you
452 need to make a change while Emacs is running, use the customize
453 interface or run the following code, where VALUE stands for the
454 new value of the variable, after updating it:
456 \(progn
457 \(setq org-export-registered-backends
458 \(org-remove-if-not
459 \(lambda (backend)
460 \(or (memq backend val)
461 \(catch 'parentp
462 \(mapc
463 \(lambda (b)
464 \(and (org-export-derived-backend-p b (car backend))
465 \(throw 'parentp t)))
466 val)
467 nil)))
468 org-export-registered-backends))
469 \(let ((new-list (mapcar 'car org-export-registered-backends)))
470 \(dolist (backend val)
471 \(cond
472 \((not (load (format \"ox-%s\" backend) t t))
473 \(message \"Problems while trying to load export back-end `%s'\"
474 backend))
475 \((not (memq backend new-list)) (push backend new-list))))
476 \(set-default var new-list)))
478 Adding a back-end to this list will also pull the back-end it
479 depends on, if any."
480 :group 'org
481 :group 'org-export
482 :version "24.4"
483 :package-version '(Org . "8.0")
484 :initialize 'custom-initialize-set
485 :set (lambda (var val)
486 (if (not (featurep 'ox)) (set-default var val)
487 ;; Any back-end not required anymore (not present in VAL and not
488 ;; a parent of any back-end in the new value) is removed from the
489 ;; list of registered back-ends.
490 (setq org-export-registered-backends
491 (org-remove-if-not
492 (lambda (backend)
493 (or (memq backend val)
494 (catch 'parentp
495 (mapc
496 (lambda (b)
497 (and (org-export-derived-backend-p b (car backend))
498 (throw 'parentp t)))
499 val)
500 nil)))
501 org-export-registered-backends))
502 ;; Now build NEW-LIST of both new back-ends and required
503 ;; parents.
504 (let ((new-list (mapcar 'car org-export-registered-backends)))
505 (dolist (backend val)
506 (cond
507 ((not (load (format "ox-%s" backend) t t))
508 (message "Problems while trying to load export back-end `%s'"
509 backend))
510 ((not (memq backend new-list)) (push backend new-list))))
511 ;; Set VAR to that list with fixed dependencies.
512 (set-default var new-list))))
513 :type '(set :greedy t
514 (const :tag " ascii Export buffer to ASCII format" ascii)
515 (const :tag " beamer Export buffer to Beamer presentation" beamer)
516 (const :tag " html Export buffer to HTML format" html)
517 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
518 (const :tag " latex Export buffer to LaTeX format" latex)
519 (const :tag " man Export buffer to MAN format" man)
520 (const :tag " md Export buffer to Markdown format" md)
521 (const :tag " odt Export buffer to ODT format" odt)
522 (const :tag " org Export buffer to Org format" org)
523 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
524 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
525 (const :tag "C deck Export buffer to deck.js presentations" deck)
526 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
527 (const :tag "C groff Export buffer to Groff format" groff)
528 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
529 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
530 (const :tag "C s5 Export buffer to s5 presentations" s5)
531 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
533 (eval-after-load 'ox
534 '(mapc
535 (lambda (backend)
536 (condition-case nil (require (intern (format "ox-%s" backend)))
537 (error (message "Problems while trying to load export back-end `%s'"
538 backend))))
539 org-export-backends))
541 (defcustom org-support-shift-select nil
542 "Non-nil means make shift-cursor commands select text when possible.
544 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
545 start selecting a region, or enlarge regions started in this way.
546 In Org-mode, in special contexts, these same keys are used for
547 other purposes, important enough to compete with shift selection.
548 Org tries to balance these needs by supporting `shift-select-mode'
549 outside these special contexts, under control of this variable.
551 The default of this variable is nil, to avoid confusing behavior. Shifted
552 cursor keys will then execute Org commands in the following contexts:
553 - on a headline, changing TODO state (left/right) and priority (up/down)
554 - on a time stamp, changing the time
555 - in a plain list item, changing the bullet type
556 - in a property definition line, switching between allowed values
557 - in the BEGIN line of a clock table (changing the time block).
558 Outside these contexts, the commands will throw an error.
560 When this variable is t and the cursor is not in a special
561 context, Org-mode will support shift-selection for making and
562 enlarging regions. To make this more effective, the bullet
563 cycling will no longer happen anywhere in an item line, but only
564 if the cursor is exactly on the bullet.
566 If you set this variable to the symbol `always', then the keys
567 will not be special in headlines, property lines, and item lines,
568 to make shift selection work there as well. If this is what you
569 want, you can use the following alternative commands: `C-c C-t'
570 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
571 can be used to switch TODO sets, `C-c -' to cycle item bullet
572 types, and properties can be edited by hand or in column view.
574 However, when the cursor is on a timestamp, shift-cursor commands
575 will still edit the time stamp - this is just too good to give up.
577 XEmacs user should have this variable set to nil, because
578 `shift-select-mode' is in Emacs 23 or later only."
579 :group 'org
580 :type '(choice
581 (const :tag "Never" nil)
582 (const :tag "When outside special context" t)
583 (const :tag "Everywhere except timestamps" always)))
585 (defcustom org-loop-over-headlines-in-active-region nil
586 "Shall some commands act upon headlines in the active region?
588 When set to `t', some commands will be performed in all headlines
589 within the active region.
591 When set to `start-level', some commands will be performed in all
592 headlines within the active region, provided that these headlines
593 are of the same level than the first one.
595 When set to a string, those commands will be performed on the
596 matching headlines within the active region. Such string must be
597 a tags/property/todo match as it is used in the agenda tags view.
599 The list of commands is: `org-schedule', `org-deadline',
600 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
601 `org-archive-to-archive-sibling'. The archiving commands skip
602 already archived entries."
603 :type '(choice (const :tag "Don't loop" nil)
604 (const :tag "All headlines in active region" t)
605 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
606 (string :tag "Tags/Property/Todo matcher"))
607 :version "24.1"
608 :group 'org-todo
609 :group 'org-archive)
611 (defgroup org-startup nil
612 "Options concerning startup of Org-mode."
613 :tag "Org Startup"
614 :group 'org)
616 (defcustom org-startup-folded t
617 "Non-nil means entering Org-mode will switch to OVERVIEW.
618 This can also be configured on a per-file basis by adding one of
619 the following lines anywhere in the buffer:
621 #+STARTUP: fold (or `overview', this is equivalent)
622 #+STARTUP: nofold (or `showall', this is equivalent)
623 #+STARTUP: content
624 #+STARTUP: showeverything
626 By default, this option is ignored when Org opens agenda files
627 for the first time. If you want the agenda to honor the startup
628 option, set `org-agenda-inhibit-startup' to nil."
629 :group 'org-startup
630 :type '(choice
631 (const :tag "nofold: show all" nil)
632 (const :tag "fold: overview" t)
633 (const :tag "content: all headlines" content)
634 (const :tag "show everything, even drawers" showeverything)))
636 (defcustom org-startup-truncated t
637 "Non-nil means entering Org-mode will set `truncate-lines'.
638 This is useful since some lines containing links can be very long and
639 uninteresting. Also tables look terrible when wrapped."
640 :group 'org-startup
641 :type 'boolean)
643 (defcustom org-startup-indented nil
644 "Non-nil means turn on `org-indent-mode' on startup.
645 This can also be configured on a per-file basis by adding one of
646 the following lines anywhere in the buffer:
648 #+STARTUP: indent
649 #+STARTUP: noindent"
650 :group 'org-structure
651 :type '(choice
652 (const :tag "Not" nil)
653 (const :tag "Globally (slow on startup in large files)" t)))
655 (defcustom org-use-sub-superscripts t
656 "Non-nil means interpret \"_\" and \"^\" for display.
657 When this option is turned on, you can use TeX-like syntax for sub- and
658 superscripts. Several characters after \"_\" or \"^\" will be
659 considered as a single item - so grouping with {} is normally not
660 needed. For example, the following things will be parsed as single
661 sub- or superscripts.
663 10^24 or 10^tau several digits will be considered 1 item.
664 10^-12 or 10^-tau a leading sign with digits or a word
665 x^2-y^3 will be read as x^2 - y^3, because items are
666 terminated by almost any nonword/nondigit char.
667 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
669 Still, ambiguity is possible - so when in doubt use {} to enclose
670 the sub/superscript. If you set this variable to the symbol
671 `{}', the braces are *required* in order to trigger
672 interpretations as sub/superscript. This can be helpful in
673 documents that need \"_\" frequently in plain text."
674 :group 'org-startup
675 :version "24.1"
676 :type '(choice
677 (const :tag "Always interpret" t)
678 (const :tag "Only with braces" {})
679 (const :tag "Never interpret" nil)))
681 (defcustom org-startup-with-beamer-mode nil
682 "Non-nil means turn on `org-beamer-mode' on startup.
683 This can also be configured on a per-file basis by adding one of
684 the following lines anywhere in the buffer:
686 #+STARTUP: beamer"
687 :group 'org-startup
688 :version "24.1"
689 :type 'boolean)
691 (defcustom org-startup-align-all-tables nil
692 "Non-nil means align all tables when visiting a file.
693 This is useful when the column width in tables is forced with <N> cookies
694 in table fields. Such tables will look correct only after the first re-align.
695 This can also be configured on a per-file basis by adding one of
696 the following lines anywhere in the buffer:
697 #+STARTUP: align
698 #+STARTUP: noalign"
699 :group 'org-startup
700 :type 'boolean)
702 (defcustom org-startup-with-inline-images nil
703 "Non-nil means show inline images when loading a new Org file.
704 This can also be configured on a per-file basis by adding one of
705 the following lines anywhere in the buffer:
706 #+STARTUP: inlineimages
707 #+STARTUP: noinlineimages"
708 :group 'org-startup
709 :version "24.1"
710 :type 'boolean)
712 (defcustom org-startup-with-latex-preview nil
713 "Non-nil means preview LaTeX fragments when loading a new Org file.
715 This can also be configured on a per-file basis by adding one of
716 the followinglines anywhere in the buffer:
717 #+STARTUP: latexpreview
718 #+STARTUP: nolatexpreview"
719 :group 'org-startup
720 :version "24.4"
721 :package-version '(Org . "8.0")
722 :type 'boolean)
724 (defcustom org-insert-mode-line-in-empty-file nil
725 "Non-nil means insert the first line setting Org-mode in empty files.
726 When the function `org-mode' is called interactively in an empty file, this
727 normally means that the file name does not automatically trigger Org-mode.
728 To ensure that the file will always be in Org-mode in the future, a
729 line enforcing Org-mode will be inserted into the buffer, if this option
730 has been set."
731 :group 'org-startup
732 :type 'boolean)
734 (defcustom org-replace-disputed-keys nil
735 "Non-nil means use alternative key bindings for some keys.
736 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
737 These keys are also used by other packages like shift-selection-mode'
738 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
739 If you want to use Org-mode together with one of these other modes,
740 or more generally if you would like to move some Org-mode commands to
741 other keys, set this variable and configure the keys with the variable
742 `org-disputed-keys'.
744 This option is only relevant at load-time of Org-mode, and must be set
745 *before* org.el is loaded. Changing it requires a restart of Emacs to
746 become effective."
747 :group 'org-startup
748 :type 'boolean)
750 (defcustom org-use-extra-keys nil
751 "Non-nil means use extra key sequence definitions for certain commands.
752 This happens automatically if you run XEmacs or if `window-system'
753 is nil. This variable lets you do the same manually. You must
754 set it before loading org.
756 Example: on Carbon Emacs 22 running graphically, with an external
757 keyboard on a Powerbook, the default way of setting M-left might
758 not work for either Alt or ESC. Setting this variable will make
759 it work for ESC."
760 :group 'org-startup
761 :type 'boolean)
763 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
765 (defcustom org-disputed-keys
766 '(([(shift up)] . [(meta p)])
767 ([(shift down)] . [(meta n)])
768 ([(shift left)] . [(meta -)])
769 ([(shift right)] . [(meta +)])
770 ([(control shift right)] . [(meta shift +)])
771 ([(control shift left)] . [(meta shift -)]))
772 "Keys for which Org-mode and other modes compete.
773 This is an alist, cars are the default keys, second element specifies
774 the alternative to use when `org-replace-disputed-keys' is t.
776 Keys can be specified in any syntax supported by `define-key'.
777 The value of this option takes effect only at Org-mode's startup,
778 therefore you'll have to restart Emacs to apply it after changing."
779 :group 'org-startup
780 :type 'alist)
782 (defun org-key (key)
783 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
784 Or return the original if not disputed.
785 Also apply the translations defined in `org-xemacs-key-equivalents'."
786 (when org-replace-disputed-keys
787 (let* ((nkey (key-description key))
788 (x (org-find-if (lambda (x)
789 (equal (key-description (car x)) nkey))
790 org-disputed-keys)))
791 (setq key (if x (cdr x) key))))
792 (when (featurep 'xemacs)
793 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
794 key)
796 (defun org-find-if (predicate seq)
797 (catch 'exit
798 (while seq
799 (if (funcall predicate (car seq))
800 (throw 'exit (car seq))
801 (pop seq)))))
803 (defun org-defkey (keymap key def)
804 "Define a key, possibly translated, as returned by `org-key'."
805 (define-key keymap (org-key key) def))
807 (defcustom org-ellipsis nil
808 "The ellipsis to use in the Org-mode outline.
809 When nil, just use the standard three dots. When a string, use that instead,
810 When a face, use the standard 3 dots, but with the specified face.
811 The change affects only Org-mode (which will then use its own display table).
812 Changing this requires executing `M-x org-mode' in a buffer to become
813 effective."
814 :group 'org-startup
815 :type '(choice (const :tag "Default" nil)
816 (face :tag "Face" :value org-warning)
817 (string :tag "String" :value "...#")))
819 (defvar org-display-table nil
820 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
822 (defgroup org-keywords nil
823 "Keywords in Org-mode."
824 :tag "Org Keywords"
825 :group 'org)
827 (defcustom org-deadline-string "DEADLINE:"
828 "String to mark deadline entries.
829 A deadline is this string, followed by a time stamp. Should be a word,
830 terminated by a colon. You can insert a schedule keyword and
831 a timestamp with \\[org-deadline].
832 Changes become only effective after restarting Emacs."
833 :group 'org-keywords
834 :type 'string)
836 (defcustom org-scheduled-string "SCHEDULED:"
837 "String to mark scheduled TODO entries.
838 A schedule is this string, followed by a time stamp. Should be a word,
839 terminated by a colon. You can insert a schedule keyword and
840 a timestamp with \\[org-schedule].
841 Changes become only effective after restarting Emacs."
842 :group 'org-keywords
843 :type 'string)
845 (defcustom org-closed-string "CLOSED:"
846 "String used as the prefix for timestamps logging closing a TODO entry."
847 :group 'org-keywords
848 :type 'string)
850 (defcustom org-clock-string "CLOCK:"
851 "String used as prefix for timestamps clocking work hours on an item."
852 :group 'org-keywords
853 :type 'string)
855 (defcustom org-closed-keep-when-no-todo nil
856 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
857 :group 'org-todo
858 :group 'org-keywords
859 :version "24.4"
860 :package-version '(Org . "8.0")
861 :type 'boolean)
863 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
864 org-scheduled-string "\\|"
865 org-deadline-string "\\|"
866 org-closed-string "\\|"
867 org-clock-string "\\)")
868 "Matches a line with planning or clock info.")
870 (defcustom org-comment-string "COMMENT"
871 "Entries starting with this keyword will never be exported.
872 An entry can be toggled between COMMENT and normal with
873 \\[org-toggle-comment].
874 Changes become only effective after restarting Emacs."
875 :group 'org-keywords
876 :type 'string)
878 (defcustom org-quote-string "QUOTE"
879 "Entries starting with this keyword will be exported in fixed-width font.
880 Quoting applies only to the text in the entry following the headline, and does
881 not extend beyond the next headline, even if that is lower level.
882 An entry can be toggled between QUOTE and normal with
883 \\[org-toggle-fixed-width-section]."
884 :group 'org-keywords
885 :type 'string)
887 (defconst org-repeat-re
888 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
889 "Regular expression for specifying repeated events.
890 After a match, group 1 contains the repeat expression.")
892 (defgroup org-structure nil
893 "Options concerning the general structure of Org-mode files."
894 :tag "Org Structure"
895 :group 'org)
897 (defgroup org-reveal-location nil
898 "Options about how to make context of a location visible."
899 :tag "Org Reveal Location"
900 :group 'org-structure)
902 (defconst org-context-choice
903 '(choice
904 (const :tag "Always" t)
905 (const :tag "Never" nil)
906 (repeat :greedy t :tag "Individual contexts"
907 (cons
908 (choice :tag "Context"
909 (const agenda)
910 (const org-goto)
911 (const occur-tree)
912 (const tags-tree)
913 (const link-search)
914 (const mark-goto)
915 (const bookmark-jump)
916 (const isearch)
917 (const default))
918 (boolean))))
919 "Contexts for the reveal options.")
921 (defcustom org-show-hierarchy-above '((default . t))
922 "Non-nil means show full hierarchy when revealing a location.
923 Org-mode often shows locations in an org-mode file which might have
924 been invisible before. When this is set, the hierarchy of headings
925 above the exposed location is shown.
926 Turning this off for example for sparse trees makes them very compact.
927 Instead of t, this can also be an alist specifying this option for different
928 contexts. Valid contexts are
929 agenda when exposing an entry from the agenda
930 org-goto when using the command `org-goto' on key C-c C-j
931 occur-tree when using the command `org-occur' on key C-c /
932 tags-tree when constructing a sparse tree based on tags matches
933 link-search when exposing search matches associated with a link
934 mark-goto when exposing the jump goal of a mark
935 bookmark-jump when exposing a bookmark location
936 isearch when exiting from an incremental search
937 default default for all contexts not set explicitly"
938 :group 'org-reveal-location
939 :type org-context-choice)
941 (defcustom org-show-following-heading '((default . nil))
942 "Non-nil means show following heading when revealing a location.
943 Org-mode often shows locations in an org-mode file which might have
944 been invisible before. When this is set, the heading following the
945 match is shown.
946 Turning this off for example for sparse trees makes them very compact,
947 but makes it harder to edit the location of the match. In such a case,
948 use the command \\[org-reveal] to show more context.
949 Instead of t, this can also be an alist specifying this option for different
950 contexts. See `org-show-hierarchy-above' for valid contexts."
951 :group 'org-reveal-location
952 :type org-context-choice)
954 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
955 "Non-nil means show all sibling heading when revealing a location.
956 Org-mode often shows locations in an org-mode file which might have
957 been invisible before. When this is set, the sibling of the current entry
958 heading are all made visible. If `org-show-hierarchy-above' is t,
959 the same happens on each level of the hierarchy above the current entry.
961 By default this is on for the isearch context, off for all other contexts.
962 Turning this off for example for sparse trees makes them very compact,
963 but makes it harder to edit the location of the match. In such a case,
964 use the command \\[org-reveal] to show more context.
965 Instead of t, this can also be an alist specifying this option for different
966 contexts. See `org-show-hierarchy-above' for valid contexts."
967 :group 'org-reveal-location
968 :type org-context-choice
969 :version "24.4"
970 :package-version '(Org . "8.0"))
972 (defcustom org-show-entry-below '((default . nil))
973 "Non-nil means show the entry below a headline when revealing a location.
974 Org-mode often shows locations in an org-mode file which might have
975 been invisible before. When this is set, the text below the headline that is
976 exposed is also shown.
978 By default this is off for all contexts.
979 Instead of t, this can also be an alist specifying this option for different
980 contexts. See `org-show-hierarchy-above' for valid contexts."
981 :group 'org-reveal-location
982 :type org-context-choice)
984 (defcustom org-indirect-buffer-display 'other-window
985 "How should indirect tree buffers be displayed?
986 This applies to indirect buffers created with the commands
987 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
988 Valid values are:
989 current-window Display in the current window
990 other-window Just display in another window.
991 dedicated-frame Create one new frame, and re-use it each time.
992 new-frame Make a new frame each time. Note that in this case
993 previously-made indirect buffers are kept, and you need to
994 kill these buffers yourself."
995 :group 'org-structure
996 :group 'org-agenda-windows
997 :type '(choice
998 (const :tag "In current window" current-window)
999 (const :tag "In current frame, other window" other-window)
1000 (const :tag "Each time a new frame" new-frame)
1001 (const :tag "One dedicated frame" dedicated-frame)))
1003 (defcustom org-use-speed-commands nil
1004 "Non-nil means activate single letter commands at beginning of a headline.
1005 This may also be a function to test for appropriate locations where speed
1006 commands should be active."
1007 :group 'org-structure
1008 :type '(choice
1009 (const :tag "Never" nil)
1010 (const :tag "At beginning of headline stars" t)
1011 (function)))
1013 (defcustom org-speed-commands-user nil
1014 "Alist of additional speed commands.
1015 This list will be checked before `org-speed-commands-default'
1016 when the variable `org-use-speed-commands' is non-nil
1017 and when the cursor is at the beginning of a headline.
1018 The car if each entry is a string with a single letter, which must
1019 be assigned to `self-insert-command' in the global map.
1020 The cdr is either a command to be called interactively, a function
1021 to be called, or a form to be evaluated.
1022 An entry that is just a list with a single string will be interpreted
1023 as a descriptive headline that will be added when listing the speed
1024 commands in the Help buffer using the `?' speed command."
1025 :group 'org-structure
1026 :type '(repeat :value ("k" . ignore)
1027 (choice :value ("k" . ignore)
1028 (list :tag "Descriptive Headline" (string :tag "Headline"))
1029 (cons :tag "Letter and Command"
1030 (string :tag "Command letter")
1031 (choice
1032 (function)
1033 (sexp))))))
1035 (defgroup org-cycle nil
1036 "Options concerning visibility cycling in Org-mode."
1037 :tag "Org Cycle"
1038 :group 'org-structure)
1040 (defcustom org-cycle-skip-children-state-if-no-children t
1041 "Non-nil means skip CHILDREN state in entries that don't have any."
1042 :group 'org-cycle
1043 :type 'boolean)
1045 (defcustom org-cycle-max-level nil
1046 "Maximum level which should still be subject to visibility cycling.
1047 Levels higher than this will, for cycling, be treated as text, not a headline.
1048 When `org-odd-levels-only' is set, a value of N in this variable actually
1049 means 2N-1 stars as the limiting headline.
1050 When nil, cycle all levels.
1051 Note that the limiting level of cycling is also influenced by
1052 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1053 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1054 than its value."
1055 :group 'org-cycle
1056 :type '(choice
1057 (const :tag "No limit" nil)
1058 (integer :tag "Maximum level")))
1060 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1061 "Names of drawers. Drawers are not opened by cycling on the headline above.
1062 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1063 this:
1064 :DRAWERNAME:
1065 .....
1066 :END:
1067 The drawer \"PROPERTIES\" is special for capturing properties through
1068 the property API.
1070 Drawers can be defined on the per-file basis with a line like:
1072 #+DRAWERS: HIDDEN STATE PROPERTIES"
1073 :group 'org-structure
1074 :group 'org-cycle
1075 :type '(repeat (string :tag "Drawer Name")))
1077 (defcustom org-hide-block-startup nil
1078 "Non-nil means entering Org-mode will fold all blocks.
1079 This can also be set in on a per-file basis with
1081 #+STARTUP: hideblocks
1082 #+STARTUP: showblocks"
1083 :group 'org-startup
1084 :group 'org-cycle
1085 :type 'boolean)
1087 (defcustom org-cycle-global-at-bob nil
1088 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1089 This makes it possible to do global cycling without having to use S-TAB or
1090 \\[universal-argument] TAB. For this special case to work, the first line
1091 of the buffer must not be a headline -- it may be empty or some other text.
1092 When used in this way, `org-cycle-hook' is disabled temporarily to make
1093 sure the cursor stays at the beginning of the buffer. When this option is
1094 nil, don't do anything special at the beginning of the buffer."
1095 :group 'org-cycle
1096 :type 'boolean)
1098 (defcustom org-cycle-level-after-item/entry-creation t
1099 "Non-nil means cycle entry level or item indentation in new empty entries.
1101 When the cursor is at the end of an empty headline, i.e., with only stars
1102 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1103 and then all possible ancestor states, before returning to the original state.
1104 This makes data entry extremely fast: M-RET to create a new headline,
1105 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1107 When the cursor is at the end of an empty plain list item, one TAB will
1108 make it a subitem, two or more tabs will back up to make this an item
1109 higher up in the item hierarchy."
1110 :group 'org-cycle
1111 :type 'boolean)
1113 (defcustom org-cycle-emulate-tab t
1114 "Where should `org-cycle' emulate TAB.
1115 nil Never
1116 white Only in completely white lines
1117 whitestart Only at the beginning of lines, before the first non-white char
1118 t Everywhere except in headlines
1119 exc-hl-bol Everywhere except at the start of a headline
1120 If TAB is used in a place where it does not emulate TAB, the current subtree
1121 visibility is cycled."
1122 :group 'org-cycle
1123 :type '(choice (const :tag "Never" nil)
1124 (const :tag "Only in completely white lines" white)
1125 (const :tag "Before first char in a line" whitestart)
1126 (const :tag "Everywhere except in headlines" t)
1127 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1129 (defcustom org-cycle-separator-lines 2
1130 "Number of empty lines needed to keep an empty line between collapsed trees.
1131 If you leave an empty line between the end of a subtree and the following
1132 headline, this empty line is hidden when the subtree is folded.
1133 Org-mode will leave (exactly) one empty line visible if the number of
1134 empty lines is equal or larger to the number given in this variable.
1135 So the default 2 means at least 2 empty lines after the end of a subtree
1136 are needed to produce free space between a collapsed subtree and the
1137 following headline.
1139 If the number is negative, and the number of empty lines is at least -N,
1140 all empty lines are shown.
1142 Special case: when 0, never leave empty lines in collapsed view."
1143 :group 'org-cycle
1144 :type 'integer)
1145 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1147 (defcustom org-pre-cycle-hook nil
1148 "Hook that is run before visibility cycling is happening.
1149 The function(s) in this hook must accept a single argument which indicates
1150 the new state that will be set right after running this hook. The
1151 argument is a symbol. Before a global state change, it can have the values
1152 `overview', `content', or `all'. Before a local state change, it can have
1153 the values `folded', `children', or `subtree'."
1154 :group 'org-cycle
1155 :type 'hook)
1157 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1158 org-cycle-hide-drawers
1159 org-cycle-hide-inline-tasks
1160 org-cycle-show-empty-lines
1161 org-optimize-window-after-visibility-change)
1162 "Hook that is run after `org-cycle' has changed the buffer visibility.
1163 The function(s) in this hook must accept a single argument which indicates
1164 the new state that was set by the most recent `org-cycle' command. The
1165 argument is a symbol. After a global state change, it can have the values
1166 `overview', `contents', or `all'. After a local state change, it can have
1167 the values `folded', `children', or `subtree'."
1168 :group 'org-cycle
1169 :type 'hook)
1171 (defgroup org-edit-structure nil
1172 "Options concerning structure editing in Org-mode."
1173 :tag "Org Edit Structure"
1174 :group 'org-structure)
1176 (defcustom org-odd-levels-only nil
1177 "Non-nil means skip even levels and only use odd levels for the outline.
1178 This has the effect that two stars are being added/taken away in
1179 promotion/demotion commands. It also influences how levels are
1180 handled by the exporters.
1181 Changing it requires restart of `font-lock-mode' to become effective
1182 for fontification also in regions already fontified.
1183 You may also set this on a per-file basis by adding one of the following
1184 lines to the buffer:
1186 #+STARTUP: odd
1187 #+STARTUP: oddeven"
1188 :group 'org-edit-structure
1189 :group 'org-appearance
1190 :type 'boolean)
1192 (defcustom org-adapt-indentation t
1193 "Non-nil means adapt indentation to outline node level.
1195 When this variable is set, Org assumes that you write outlines by
1196 indenting text in each node to align with the headline (after the stars).
1197 The following issues are influenced by this variable:
1199 - When this is set and the *entire* text in an entry is indented, the
1200 indentation is increased by one space in a demotion command, and
1201 decreased by one in a promotion command. If any line in the entry
1202 body starts with text at column 0, indentation is not changed at all.
1204 - Property drawers and planning information is inserted indented when
1205 this variable s set. When nil, they will not be indented.
1207 - TAB indents a line relative to context. The lines below a headline
1208 will be indented when this variable is set.
1210 Note that this is all about true indentation, by adding and removing
1211 space characters. See also `org-indent.el' which does level-dependent
1212 indentation in a virtual way, i.e. at display time in Emacs."
1213 :group 'org-edit-structure
1214 :type 'boolean)
1216 (defcustom org-special-ctrl-a/e nil
1217 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1219 When t, `C-a' will bring back the cursor to the beginning of the
1220 headline text, i.e. after the stars and after a possible TODO
1221 keyword. In an item, this will be the position after bullet and
1222 check-box, if any. When the cursor is already at that position,
1223 another `C-a' will bring it to the beginning of the line.
1225 `C-e' will jump to the end of the headline, ignoring the presence
1226 of tags in the headline. A second `C-e' will then jump to the
1227 true end of the line, after any tags. This also means that, when
1228 this variable is non-nil, `C-e' also will never jump beyond the
1229 end of the heading of a folded section, i.e. not after the
1230 ellipses.
1232 When set to the symbol `reversed', the first `C-a' or `C-e' works
1233 normally, going to the true line boundary first. Only a directly
1234 following, identical keypress will bring the cursor to the
1235 special positions.
1237 This may also be a cons cell where the behavior for `C-a' and
1238 `C-e' is set separately."
1239 :group 'org-edit-structure
1240 :type '(choice
1241 (const :tag "off" nil)
1242 (const :tag "on: after stars/bullet and before tags first" t)
1243 (const :tag "reversed: true line boundary first" reversed)
1244 (cons :tag "Set C-a and C-e separately"
1245 (choice :tag "Special C-a"
1246 (const :tag "off" nil)
1247 (const :tag "on: after stars/bullet first" t)
1248 (const :tag "reversed: before stars/bullet first" reversed))
1249 (choice :tag "Special C-e"
1250 (const :tag "off" nil)
1251 (const :tag "on: before tags first" t)
1252 (const :tag "reversed: after tags first" reversed)))))
1253 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1255 (defcustom org-special-ctrl-k nil
1256 "Non-nil means `C-k' will behave specially in headlines.
1257 When nil, `C-k' will call the default `kill-line' command.
1258 When t, the following will happen while the cursor is in the headline:
1260 - When the cursor is at the beginning of a headline, kill the entire
1261 line and possible the folded subtree below the line.
1262 - When in the middle of the headline text, kill the headline up to the tags.
1263 - When after the headline text, kill the tags."
1264 :group 'org-edit-structure
1265 :type 'boolean)
1267 (defcustom org-ctrl-k-protect-subtree nil
1268 "Non-nil means, do not delete a hidden subtree with C-k.
1269 When set to the symbol `error', simply throw an error when C-k is
1270 used to kill (part-of) a headline that has hidden text behind it.
1271 Any other non-nil value will result in a query to the user, if it is
1272 OK to kill that hidden subtree. When nil, kill without remorse."
1273 :group 'org-edit-structure
1274 :version "24.1"
1275 :type '(choice
1276 (const :tag "Do not protect hidden subtrees" nil)
1277 (const :tag "Protect hidden subtrees with a security query" t)
1278 (const :tag "Never kill a hidden subtree with C-k" error)))
1280 (defcustom org-catch-invisible-edits nil
1281 "Check if in invisible region before inserting or deleting a character.
1282 Valid values are:
1284 nil Do not check, so just do invisible edits.
1285 error Throw an error and do nothing.
1286 show Make point visible, and do the requested edit.
1287 show-and-error Make point visible, then throw an error and abort the edit.
1288 smart Make point visible, and do insertion/deletion if it is
1289 adjacent to visible text and the change feels predictable.
1290 Never delete a previously invisible character or add in the
1291 middle or right after an invisible region. Basically, this
1292 allows insertion and backward-delete right before ellipses.
1293 FIXME: maybe in this case we should not even show?"
1294 :group 'org-edit-structure
1295 :version "24.1"
1296 :type '(choice
1297 (const :tag "Do not check" nil)
1298 (const :tag "Throw error when trying to edit" error)
1299 (const :tag "Unhide, but do not do the edit" show-and-error)
1300 (const :tag "Show invisible part and do the edit" show)
1301 (const :tag "Be smart and do the right thing" smart)))
1303 (defcustom org-yank-folded-subtrees t
1304 "Non-nil means when yanking subtrees, fold them.
1305 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1306 it starts with a heading and all other headings in it are either children
1307 or siblings, then fold all the subtrees. However, do this only if no
1308 text after the yank would be swallowed into a folded tree by this action."
1309 :group 'org-edit-structure
1310 :type 'boolean)
1312 (defcustom org-yank-adjusted-subtrees nil
1313 "Non-nil means when yanking subtrees, adjust the level.
1314 With this setting, `org-paste-subtree' is used to insert the subtree, see
1315 this function for details."
1316 :group 'org-edit-structure
1317 :type 'boolean)
1319 (defcustom org-M-RET-may-split-line '((default . t))
1320 "Non-nil means M-RET will split the line at the cursor position.
1321 When nil, it will go to the end of the line before making a
1322 new line.
1323 You may also set this option in a different way for different
1324 contexts. Valid contexts are:
1326 headline when creating a new headline
1327 item when creating a new item
1328 table in a table field
1329 default the value to be used for all contexts not explicitly
1330 customized"
1331 :group 'org-structure
1332 :group 'org-table
1333 :type '(choice
1334 (const :tag "Always" t)
1335 (const :tag "Never" nil)
1336 (repeat :greedy t :tag "Individual contexts"
1337 (cons
1338 (choice :tag "Context"
1339 (const headline)
1340 (const item)
1341 (const table)
1342 (const default))
1343 (boolean)))))
1346 (defcustom org-insert-heading-respect-content nil
1347 "Non-nil means insert new headings after the current subtree.
1348 When nil, the new heading is created directly after the current line.
1349 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1350 this variable on for the duration of the command."
1351 :group 'org-structure
1352 :type 'boolean)
1354 (defcustom org-blank-before-new-entry '((heading . auto)
1355 (plain-list-item . auto))
1356 "Should `org-insert-heading' leave a blank line before new heading/item?
1357 The value is an alist, with `heading' and `plain-list-item' as CAR,
1358 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1359 which case Org will look at the surrounding headings/items and try to
1360 make an intelligent decision whether to insert a blank line or not.
1362 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1363 the setting here is ignored and no empty line is inserted to avoid breaking
1364 the list structure."
1365 :group 'org-edit-structure
1366 :type '(list
1367 (cons (const heading)
1368 (choice (const :tag "Never" nil)
1369 (const :tag "Always" t)
1370 (const :tag "Auto" auto)))
1371 (cons (const plain-list-item)
1372 (choice (const :tag "Never" nil)
1373 (const :tag "Always" t)
1374 (const :tag "Auto" auto)))))
1376 (defcustom org-insert-heading-hook nil
1377 "Hook being run after inserting a new heading."
1378 :group 'org-edit-structure
1379 :type 'hook)
1381 (defcustom org-enable-fixed-width-editor t
1382 "Non-nil means lines starting with \":\" are treated as fixed-width.
1383 This currently only means they are never auto-wrapped.
1384 When nil, such lines will be treated like ordinary lines.
1385 See also the QUOTE keyword."
1386 :group 'org-edit-structure
1387 :type 'boolean)
1389 (defcustom org-goto-auto-isearch t
1390 "Non-nil means typing characters in `org-goto' starts incremental search.
1391 When nil, you can use these keybindings to navigate the buffer:
1393 q Quit the org-goto interface
1394 n Go to the next visible heading
1395 p Go to the previous visible heading
1396 f Go one heading forward on same level
1397 b Go one heading backward on same level
1398 u Go one heading up"
1399 :group 'org-edit-structure
1400 :type 'boolean)
1402 (defgroup org-sparse-trees nil
1403 "Options concerning sparse trees in Org-mode."
1404 :tag "Org Sparse Trees"
1405 :group 'org-structure)
1407 (defcustom org-highlight-sparse-tree-matches t
1408 "Non-nil means highlight all matches that define a sparse tree.
1409 The highlights will automatically disappear the next time the buffer is
1410 changed by an edit command."
1411 :group 'org-sparse-trees
1412 :type 'boolean)
1414 (defcustom org-remove-highlights-with-change t
1415 "Non-nil means any change to the buffer will remove temporary highlights.
1416 Such highlights are created by `org-occur' and `org-clock-display'.
1417 When nil, `C-c C-c needs to be used to get rid of the highlights.
1418 The highlights created by `org-preview-latex-fragment' always need
1419 `C-c C-c' to be removed."
1420 :group 'org-sparse-trees
1421 :group 'org-time
1422 :type 'boolean)
1425 (defcustom org-occur-hook '(org-first-headline-recenter)
1426 "Hook that is run after `org-occur' has constructed a sparse tree.
1427 This can be used to recenter the window to show as much of the structure
1428 as possible."
1429 :group 'org-sparse-trees
1430 :type 'hook)
1432 (defgroup org-imenu-and-speedbar nil
1433 "Options concerning imenu and speedbar in Org-mode."
1434 :tag "Org Imenu and Speedbar"
1435 :group 'org-structure)
1437 (defcustom org-imenu-depth 2
1438 "The maximum level for Imenu access to Org-mode headlines.
1439 This also applied for speedbar access."
1440 :group 'org-imenu-and-speedbar
1441 :type 'integer)
1443 (defgroup org-table nil
1444 "Options concerning tables in Org-mode."
1445 :tag "Org Table"
1446 :group 'org)
1448 (defcustom org-enable-table-editor 'optimized
1449 "Non-nil means lines starting with \"|\" are handled by the table editor.
1450 When nil, such lines will be treated like ordinary lines.
1452 When equal to the symbol `optimized', the table editor will be optimized to
1453 do the following:
1454 - Automatic overwrite mode in front of whitespace in table fields.
1455 This makes the structure of the table stay in tact as long as the edited
1456 field does not exceed the column width.
1457 - Minimize the number of realigns. Normally, the table is aligned each time
1458 TAB or RET are pressed to move to another field. With optimization this
1459 happens only if changes to a field might have changed the column width.
1460 Optimization requires replacing the functions `self-insert-command',
1461 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1462 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1463 very good at guessing when a re-align will be necessary, but you can always
1464 force one with \\[org-ctrl-c-ctrl-c].
1466 If you would like to use the optimized version in Org-mode, but the
1467 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1469 This variable can be used to turn on and off the table editor during a session,
1470 but in order to toggle optimization, a restart is required.
1472 See also the variable `org-table-auto-blank-field'."
1473 :group 'org-table
1474 :type '(choice
1475 (const :tag "off" nil)
1476 (const :tag "on" t)
1477 (const :tag "on, optimized" optimized)))
1479 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1480 (version<= emacs-version "24.1"))
1481 "Non-nil means cluster self-insert commands for undo when possible.
1482 If this is set, then, like in the Emacs command loop, 20 consecutive
1483 characters will be undone together.
1484 This is configurable, because there is some impact on typing performance."
1485 :group 'org-table
1486 :type 'boolean)
1488 (defcustom org-table-tab-recognizes-table.el t
1489 "Non-nil means TAB will automatically notice a table.el table.
1490 When it sees such a table, it moves point into it and - if necessary -
1491 calls `table-recognize-table'."
1492 :group 'org-table-editing
1493 :type 'boolean)
1495 (defgroup org-link nil
1496 "Options concerning links in Org-mode."
1497 :tag "Org Link"
1498 :group 'org)
1500 (defvar org-link-abbrev-alist-local nil
1501 "Buffer-local version of `org-link-abbrev-alist', which see.
1502 The value of this is taken from the #+LINK lines.")
1503 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1505 (defcustom org-link-abbrev-alist nil
1506 "Alist of link abbreviations.
1507 The car of each element is a string, to be replaced at the start of a link.
1508 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1509 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1511 [[linkkey:tag][description]]
1513 The 'linkkey' must be a word word, starting with a letter, followed
1514 by letters, numbers, '-' or '_'.
1516 If REPLACE is a string, the tag will simply be appended to create the link.
1517 If the string contains \"%s\", the tag will be inserted there. If the string
1518 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1519 at that point (see the function `url-hexify-string'). If the string contains
1520 the specifier \"%(my-function)\", then the custom function `my-function' will
1521 be invoked: this function takes the tag as its only argument and must return
1522 a string.
1524 REPLACE may also be a function that will be called with the tag as the
1525 only argument to create the link, which should be returned as a string.
1527 See the manual for examples."
1528 :group 'org-link
1529 :type '(repeat
1530 (cons
1531 (string :tag "Protocol")
1532 (choice
1533 (string :tag "Format")
1534 (function)))))
1536 (defcustom org-descriptive-links t
1537 "Non-nil means Org will display descriptive links.
1538 E.g. [[http://orgmode.org][Org website]] will be displayed as
1539 \"Org Website\", hiding the link itself and just displaying its
1540 description. When set to `nil', Org will display the full links
1541 literally.
1543 You can interactively set the value of this variable by calling
1544 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1545 :group 'org-link
1546 :type 'boolean)
1548 (defcustom org-link-file-path-type 'adaptive
1549 "How the path name in file links should be stored.
1550 Valid values are:
1552 relative Relative to the current directory, i.e. the directory of the file
1553 into which the link is being inserted.
1554 absolute Absolute path, if possible with ~ for home directory.
1555 noabbrev Absolute path, no abbreviation of home directory.
1556 adaptive Use relative path for files in the current directory and sub-
1557 directories of it. For other files, use an absolute path."
1558 :group 'org-link
1559 :type '(choice
1560 (const relative)
1561 (const absolute)
1562 (const noabbrev)
1563 (const adaptive)))
1565 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1566 "Types of links that should be activated in Org-mode files.
1567 This is a list of symbols, each leading to the activation of a certain link
1568 type. In principle, it does not hurt to turn on most link types - there may
1569 be a small gain when turning off unused link types. The types are:
1571 bracket The recommended [[link][description]] or [[link]] links with hiding.
1572 angle Links in angular brackets that may contain whitespace like
1573 <bbdb:Carsten Dominik>.
1574 plain Plain links in normal text, no whitespace, like http://google.com.
1575 radio Text that is matched by a radio target, see manual for details.
1576 tag Tag settings in a headline (link to tag search).
1577 date Time stamps (link to calendar).
1578 footnote Footnote labels.
1580 Changing this variable requires a restart of Emacs to become effective."
1581 :group 'org-link
1582 :type '(set :greedy t
1583 (const :tag "Double bracket links" bracket)
1584 (const :tag "Angular bracket links" angle)
1585 (const :tag "Plain text links" plain)
1586 (const :tag "Radio target matches" radio)
1587 (const :tag "Tags" tag)
1588 (const :tag "Timestamps" date)
1589 (const :tag "Footnotes" footnote)))
1591 (defcustom org-make-link-description-function nil
1592 "Function to use for generating link descriptions from links.
1593 When nil, the link location will be used. This function must take
1594 two parameters: the first one is the link, the second one is the
1595 description generated by `org-insert-link'. The function should
1596 return the description to use."
1597 :group 'org-link
1598 :type 'function)
1600 (defgroup org-link-store nil
1601 "Options concerning storing links in Org-mode."
1602 :tag "Org Store Link"
1603 :group 'org-link)
1605 (defcustom org-url-hexify-p t
1606 "When non-nil, hexify URL when creating a link."
1607 :type 'boolean
1608 :version "24.3"
1609 :group 'org-link-store)
1611 (defcustom org-email-link-description-format "Email %c: %.30s"
1612 "Format of the description part of a link to an email or usenet message.
1613 The following %-escapes will be replaced by corresponding information:
1615 %F full \"From\" field
1616 %f name, taken from \"From\" field, address if no name
1617 %T full \"To\" field
1618 %t first name in \"To\" field, address if no name
1619 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1620 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1621 %s subject
1622 %d date
1623 %m message-id.
1625 You may use normal field width specification between the % and the letter.
1626 This is for example useful to limit the length of the subject.
1628 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1629 :group 'org-link-store
1630 :type 'string)
1632 (defcustom org-from-is-user-regexp
1633 (let (r1 r2)
1634 (when (and user-mail-address (not (string= user-mail-address "")))
1635 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1636 (when (and user-full-name (not (string= user-full-name "")))
1637 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1638 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1639 "Regexp matched against the \"From:\" header of an email or usenet message.
1640 It should match if the message is from the user him/herself."
1641 :group 'org-link-store
1642 :type 'regexp)
1644 (defcustom org-context-in-file-links t
1645 "Non-nil means file links from `org-store-link' contain context.
1646 A search string will be added to the file name with :: as separator and
1647 used to find the context when the link is activated by the command
1648 `org-open-at-point'. When this option is t, the entire active region
1649 will be placed in the search string of the file link. If set to a
1650 positive integer, only the first n lines of context will be stored.
1652 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1653 negates this setting for the duration of the command."
1654 :group 'org-link-store
1655 :type '(choice boolean integer))
1657 (defcustom org-keep-stored-link-after-insertion nil
1658 "Non-nil means keep link in list for entire session.
1660 The command `org-store-link' adds a link pointing to the current
1661 location to an internal list. These links accumulate during a session.
1662 The command `org-insert-link' can be used to insert links into any
1663 Org-mode file (offering completion for all stored links). When this
1664 option is nil, every link which has been inserted once using \\[org-insert-link]
1665 will be removed from the list, to make completing the unused links
1666 more efficient."
1667 :group 'org-link-store
1668 :type 'boolean)
1670 (defgroup org-link-follow nil
1671 "Options concerning following links in Org-mode."
1672 :tag "Org Follow Link"
1673 :group 'org-link)
1675 (defcustom org-link-translation-function nil
1676 "Function to translate links with different syntax to Org syntax.
1677 This can be used to translate links created for example by the Planner
1678 or emacs-wiki packages to Org syntax.
1679 The function must accept two parameters, a TYPE containing the link
1680 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1681 which is everything after the link protocol. It should return a cons
1682 with possibly modified values of type and path.
1683 Org contains a function for this, so if you set this variable to
1684 `org-translate-link-from-planner', you should be able follow many
1685 links created by planner."
1686 :group 'org-link-follow
1687 :type 'function)
1689 (defcustom org-follow-link-hook nil
1690 "Hook that is run after a link has been followed."
1691 :group 'org-link-follow
1692 :type 'hook)
1694 (defcustom org-tab-follows-link nil
1695 "Non-nil means on links TAB will follow the link.
1696 Needs to be set before org.el is loaded.
1697 This really should not be used, it does not make sense, and the
1698 implementation is bad."
1699 :group 'org-link-follow
1700 :type 'boolean)
1702 (defcustom org-return-follows-link nil
1703 "Non-nil means on links RET will follow the link.
1704 In tables, the special behavior of RET has precedence."
1705 :group 'org-link-follow
1706 :type 'boolean)
1708 (defcustom org-mouse-1-follows-link
1709 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1710 "Non-nil means mouse-1 on a link will follow the link.
1711 A longer mouse click will still set point. Does not work on XEmacs.
1712 Needs to be set before org.el is loaded."
1713 :group 'org-link-follow
1714 :type 'boolean)
1716 (defcustom org-mark-ring-length 4
1717 "Number of different positions to be recorded in the ring.
1718 Changing this requires a restart of Emacs to work correctly."
1719 :group 'org-link-follow
1720 :type 'integer)
1722 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1723 "Non-nil means internal links in Org files must exactly match a headline.
1724 When nil, the link search tries to match a phrase with all words
1725 in the search text."
1726 :group 'org-link-follow
1727 :version "24.1"
1728 :type '(choice
1729 (const :tag "Use fuzzy text search" nil)
1730 (const :tag "Match only exact headline" t)
1731 (const :tag "Match exact headline or query to create it"
1732 query-to-create)))
1734 (defcustom org-link-frame-setup
1735 '((vm . vm-visit-folder-other-frame)
1736 (vm-imap . vm-visit-imap-folder-other-frame)
1737 (gnus . org-gnus-no-new-news)
1738 (file . find-file-other-window)
1739 (wl . wl-other-frame))
1740 "Setup the frame configuration for following links.
1741 When following a link with Emacs, it may often be useful to display
1742 this link in another window or frame. This variable can be used to
1743 set this up for the different types of links.
1744 For VM, use any of
1745 `vm-visit-folder'
1746 `vm-visit-folder-other-window'
1747 `vm-visit-folder-other-frame'
1748 For Gnus, use any of
1749 `gnus'
1750 `gnus-other-frame'
1751 `org-gnus-no-new-news'
1752 For FILE, use any of
1753 `find-file'
1754 `find-file-other-window'
1755 `find-file-other-frame'
1756 For Wanderlust use any of
1757 `wl'
1758 `wl-other-frame'
1759 For the calendar, use the variable `calendar-setup'.
1760 For BBDB, it is currently only possible to display the matches in
1761 another window."
1762 :group 'org-link-follow
1763 :type '(list
1764 (cons (const vm)
1765 (choice
1766 (const vm-visit-folder)
1767 (const vm-visit-folder-other-window)
1768 (const vm-visit-folder-other-frame)))
1769 (cons (const gnus)
1770 (choice
1771 (const gnus)
1772 (const gnus-other-frame)
1773 (const org-gnus-no-new-news)))
1774 (cons (const file)
1775 (choice
1776 (const find-file)
1777 (const find-file-other-window)
1778 (const find-file-other-frame)))
1779 (cons (const wl)
1780 (choice
1781 (const wl)
1782 (const wl-other-frame)))))
1784 (defcustom org-display-internal-link-with-indirect-buffer nil
1785 "Non-nil means use indirect buffer to display infile links.
1786 Activating internal links (from one location in a file to another location
1787 in the same file) normally just jumps to the location. When the link is
1788 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1789 is displayed in
1790 another window. When this option is set, the other window actually displays
1791 an indirect buffer clone of the current buffer, to avoid any visibility
1792 changes to the current buffer."
1793 :group 'org-link-follow
1794 :type 'boolean)
1796 (defcustom org-open-non-existing-files nil
1797 "Non-nil means `org-open-file' will open non-existing files.
1798 When nil, an error will be generated.
1799 This variable applies only to external applications because they
1800 might choke on non-existing files. If the link is to a file that
1801 will be opened in Emacs, the variable is ignored."
1802 :group 'org-link-follow
1803 :type 'boolean)
1805 (defcustom org-open-directory-means-index-dot-org nil
1806 "Non-nil means a link to a directory really means to index.org.
1807 When nil, following a directory link will run dired or open a finder/explorer
1808 window on that directory."
1809 :group 'org-link-follow
1810 :type 'boolean)
1812 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1813 "Function and arguments to call for following mailto links.
1814 This is a list with the first element being a Lisp function, and the
1815 remaining elements being arguments to the function. In string arguments,
1816 %a will be replaced by the address, and %s will be replaced by the subject
1817 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1818 :group 'org-link-follow
1819 :type '(choice
1820 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1821 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1822 (const :tag "message-mail" (message-mail "%a" "%s"))
1823 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1825 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1826 "Non-nil means ask for confirmation before executing shell links.
1827 Shell links can be dangerous: just think about a link
1829 [[shell:rm -rf ~/*][Google Search]]
1831 This link would show up in your Org-mode document as \"Google Search\",
1832 but really it would remove your entire home directory.
1833 Therefore we advise against setting this variable to nil.
1834 Just change it to `y-or-n-p' if you want to confirm with a
1835 single keystroke rather than having to type \"yes\"."
1836 :group 'org-link-follow
1837 :type '(choice
1838 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1839 (const :tag "with y-or-n (faster)" y-or-n-p)
1840 (const :tag "no confirmation (dangerous)" nil)))
1841 (put 'org-confirm-shell-link-function
1842 'safe-local-variable
1843 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1845 (defcustom org-confirm-shell-link-not-regexp ""
1846 "A regexp to skip confirmation for shell links."
1847 :group 'org-link-follow
1848 :version "24.1"
1849 :type 'regexp)
1851 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1852 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1853 Elisp links can be dangerous: just think about a link
1855 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1857 This link would show up in your Org-mode document as \"Google Search\",
1858 but really it would remove your entire home directory.
1859 Therefore we advise against setting this variable to nil.
1860 Just change it to `y-or-n-p' if you want to confirm with a
1861 single keystroke rather than having to type \"yes\"."
1862 :group 'org-link-follow
1863 :type '(choice
1864 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1865 (const :tag "with y-or-n (faster)" y-or-n-p)
1866 (const :tag "no confirmation (dangerous)" nil)))
1867 (put 'org-confirm-shell-link-function
1868 'safe-local-variable
1869 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1871 (defcustom org-confirm-elisp-link-not-regexp ""
1872 "A regexp to skip confirmation for Elisp links."
1873 :group 'org-link-follow
1874 :version "24.1"
1875 :type 'regexp)
1877 (defconst org-file-apps-defaults-gnu
1878 '((remote . emacs)
1879 (system . mailcap)
1880 (t . mailcap))
1881 "Default file applications on a UNIX or GNU/Linux system.
1882 See `org-file-apps'.")
1884 (defconst org-file-apps-defaults-macosx
1885 '((remote . emacs)
1886 (t . "open %s")
1887 (system . "open %s")
1888 ("ps.gz" . "gv %s")
1889 ("eps.gz" . "gv %s")
1890 ("dvi" . "xdvi %s")
1891 ("fig" . "xfig %s"))
1892 "Default file applications on a MacOS X system.
1893 The system \"open\" is known as a default, but we use X11 applications
1894 for some files for which the OS does not have a good default.
1895 See `org-file-apps'.")
1897 (defconst org-file-apps-defaults-windowsnt
1898 (list
1899 '(remote . emacs)
1900 (cons t
1901 (list (if (featurep 'xemacs)
1902 'mswindows-shell-execute
1903 'w32-shell-execute)
1904 "open" 'file))
1905 (cons 'system
1906 (list (if (featurep 'xemacs)
1907 'mswindows-shell-execute
1908 'w32-shell-execute)
1909 "open" 'file)))
1910 "Default file applications on a Windows NT system.
1911 The system \"open\" is used for most files.
1912 See `org-file-apps'.")
1914 (defcustom org-file-apps
1915 '((auto-mode . emacs)
1916 ("\\.mm\\'" . default)
1917 ("\\.x?html?\\'" . default)
1918 ("\\.pdf\\'" . default))
1919 "External applications for opening `file:path' items in a document.
1920 Org-mode uses system defaults for different file types, but
1921 you can use this variable to set the application for a given file
1922 extension. The entries in this list are cons cells where the car identifies
1923 files and the cdr the corresponding command. Possible values for the
1924 file identifier are
1925 \"string\" A string as a file identifier can be interpreted in different
1926 ways, depending on its contents:
1928 - Alphanumeric characters only:
1929 Match links with this file extension.
1930 Example: (\"pdf\" . \"evince %s\")
1931 to open PDFs with evince.
1933 - Regular expression: Match links where the
1934 filename matches the regexp. If you want to
1935 use groups here, use shy groups.
1937 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1938 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1939 to open *.html and *.xhtml with firefox.
1941 - Regular expression which contains (non-shy) groups:
1942 Match links where the whole link, including \"::\", and
1943 anything after that, matches the regexp.
1944 In a custom command string, %1, %2, etc. are replaced with
1945 the parts of the link that were matched by the groups.
1946 For backwards compatibility, if a command string is given
1947 that does not use any of the group matches, this case is
1948 handled identically to the second one (i.e. match against
1949 file name only).
1950 In a custom lisp form, you can access the group matches with
1951 (match-string n link).
1953 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1954 to open [[file:document.pdf::5]] with evince at page 5.
1956 `directory' Matches a directory
1957 `remote' Matches a remote file, accessible through tramp or efs.
1958 Remote files most likely should be visited through Emacs
1959 because external applications cannot handle such paths.
1960 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1961 so all files Emacs knows how to handle. Using this with
1962 command `emacs' will open most files in Emacs. Beware that this
1963 will also open html files inside Emacs, unless you add
1964 (\"html\" . default) to the list as well.
1965 t Default for files not matched by any of the other options.
1966 `system' The system command to open files, like `open' on Windows
1967 and Mac OS X, and mailcap under GNU/Linux. This is the command
1968 that will be selected if you call `C-c C-o' with a double
1969 \\[universal-argument] \\[universal-argument] prefix.
1971 Possible values for the command are:
1972 `emacs' The file will be visited by the current Emacs process.
1973 `default' Use the default application for this file type, which is the
1974 association for t in the list, most likely in the system-specific
1975 part.
1976 This can be used to overrule an unwanted setting in the
1977 system-specific variable.
1978 `system' Use the system command for opening files, like \"open\".
1979 This command is specified by the entry whose car is `system'.
1980 Most likely, the system-specific version of this variable
1981 does define this command, but you can overrule/replace it
1982 here.
1983 string A command to be executed by a shell; %s will be replaced
1984 by the path to the file.
1985 sexp A Lisp form which will be evaluated. The file path will
1986 be available in the Lisp variable `file'.
1987 For more examples, see the system specific constants
1988 `org-file-apps-defaults-macosx'
1989 `org-file-apps-defaults-windowsnt'
1990 `org-file-apps-defaults-gnu'."
1991 :group 'org-link-follow
1992 :type '(repeat
1993 (cons (choice :value ""
1994 (string :tag "Extension")
1995 (const :tag "System command to open files" system)
1996 (const :tag "Default for unrecognized files" t)
1997 (const :tag "Remote file" remote)
1998 (const :tag "Links to a directory" directory)
1999 (const :tag "Any files that have Emacs modes"
2000 auto-mode))
2001 (choice :value ""
2002 (const :tag "Visit with Emacs" emacs)
2003 (const :tag "Use default" default)
2004 (const :tag "Use the system command" system)
2005 (string :tag "Command")
2006 (sexp :tag "Lisp form")))))
2008 (defcustom org-doi-server-url "http://dx.doi.org/"
2009 "The URL of the DOI server."
2010 :type 'string
2011 :version "24.3"
2012 :group 'org-link-follow)
2014 (defgroup org-refile nil
2015 "Options concerning refiling entries in Org-mode."
2016 :tag "Org Refile"
2017 :group 'org)
2019 (defcustom org-directory "~/org"
2020 "Directory with org files.
2021 This is just a default location to look for Org files. There is no need
2022 at all to put your files into this directory. It is only used in the
2023 following situations:
2025 1. When a capture template specifies a target file that is not an
2026 absolute path. The path will then be interpreted relative to
2027 `org-directory'
2028 2. When a capture note is filed away in an interactive way (when exiting the
2029 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2030 with `org-directory' as the default path."
2031 :group 'org-refile
2032 :group 'org-remember
2033 :group 'org-capture
2034 :type 'directory)
2036 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2037 "Default target for storing notes.
2038 Used as a fall back file for org-remember.el and org-capture.el, for
2039 templates that do not specify a target file."
2040 :group 'org-refile
2041 :group 'org-remember
2042 :group 'org-capture
2043 :type '(choice
2044 (const :tag "Default from remember-data-file" nil)
2045 file))
2047 (defcustom org-goto-interface 'outline
2048 "The default interface to be used for `org-goto'.
2049 Allowed values are:
2050 outline The interface shows an outline of the relevant file
2051 and the correct heading is found by moving through
2052 the outline or by searching with incremental search.
2053 outline-path-completion Headlines in the current buffer are offered via
2054 completion. This is the interface also used by
2055 the refile command."
2056 :group 'org-refile
2057 :type '(choice
2058 (const :tag "Outline" outline)
2059 (const :tag "Outline-path-completion" outline-path-completion)))
2061 (defcustom org-goto-max-level 5
2062 "Maximum target level when running `org-goto' with refile interface."
2063 :group 'org-refile
2064 :type 'integer)
2066 (defcustom org-reverse-note-order nil
2067 "Non-nil means store new notes at the beginning of a file or entry.
2068 When nil, new notes will be filed to the end of a file or entry.
2069 This can also be a list with cons cells of regular expressions that
2070 are matched against file names, and values."
2071 :group 'org-remember
2072 :group 'org-capture
2073 :group 'org-refile
2074 :type '(choice
2075 (const :tag "Reverse always" t)
2076 (const :tag "Reverse never" nil)
2077 (repeat :tag "By file name regexp"
2078 (cons regexp boolean))))
2080 (defcustom org-log-refile nil
2081 "Information to record when a task is refiled.
2083 Possible values are:
2085 nil Don't add anything
2086 time Add a time stamp to the task
2087 note Prompt for a note and add it with template `org-log-note-headings'
2089 This option can also be set with on a per-file-basis with
2091 #+STARTUP: nologrefile
2092 #+STARTUP: logrefile
2093 #+STARTUP: lognoterefile
2095 You can have local logging settings for a subtree by setting the LOGGING
2096 property to one or more of these keywords.
2098 When bulk-refiling from the agenda, the value `note' is forbidden and
2099 will temporarily be changed to `time'."
2100 :group 'org-refile
2101 :group 'org-progress
2102 :version "24.1"
2103 :type '(choice
2104 (const :tag "No logging" nil)
2105 (const :tag "Record timestamp" time)
2106 (const :tag "Record timestamp with note." note)))
2108 (defcustom org-refile-targets nil
2109 "Targets for refiling entries with \\[org-refile].
2110 This is a list of cons cells. Each cell contains:
2111 - a specification of the files to be considered, either a list of files,
2112 or a symbol whose function or variable value will be used to retrieve
2113 a file name or a list of file names. If you use `org-agenda-files' for
2114 that, all agenda files will be scanned for targets. Nil means consider
2115 headings in the current buffer.
2116 - A specification of how to find candidate refile targets. This may be
2117 any of:
2118 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2119 This tag has to be present in all target headlines, inheritance will
2120 not be considered.
2121 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2122 todo keyword.
2123 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2124 headlines that are refiling targets.
2125 - a cons cell (:level . N). Any headline of level N is considered a target.
2126 Note that, when `org-odd-levels-only' is set, level corresponds to
2127 order in hierarchy, not to the number of stars.
2128 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2129 Note that, when `org-odd-levels-only' is set, level corresponds to
2130 order in hierarchy, not to the number of stars.
2132 Each element of this list generates a set of possible targets.
2133 The union of these sets is presented (with completion) to
2134 the user by `org-refile'.
2136 You can set the variable `org-refile-target-verify-function' to a function
2137 to verify each headline found by the simple criteria above.
2139 When this variable is nil, all top-level headlines in the current buffer
2140 are used, equivalent to the value `((nil . (:level . 1))'."
2141 :group 'org-refile
2142 :type '(repeat
2143 (cons
2144 (choice :value org-agenda-files
2145 (const :tag "All agenda files" org-agenda-files)
2146 (const :tag "Current buffer" nil)
2147 (function) (variable) (file))
2148 (choice :tag "Identify target headline by"
2149 (cons :tag "Specific tag" (const :value :tag) (string))
2150 (cons :tag "TODO keyword" (const :value :todo) (string))
2151 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2152 (cons :tag "Level number" (const :value :level) (integer))
2153 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2155 (defcustom org-refile-target-verify-function nil
2156 "Function to verify if the headline at point should be a refile target.
2157 The function will be called without arguments, with point at the
2158 beginning of the headline. It should return t and leave point
2159 where it is if the headline is a valid target for refiling.
2161 If the target should not be selected, the function must return nil.
2162 In addition to this, it may move point to a place from where the search
2163 should be continued. For example, the function may decide that the entire
2164 subtree of the current entry should be excluded and move point to the end
2165 of the subtree."
2166 :group 'org-refile
2167 :type 'function)
2169 (defcustom org-refile-use-cache nil
2170 "Non-nil means cache refile targets to speed up the process.
2171 The cache for a particular file will be updated automatically when
2172 the buffer has been killed, or when any of the marker used for flagging
2173 refile targets no longer points at a live buffer.
2174 If you have added new entries to a buffer that might themselves be targets,
2175 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2176 find that easier, `C-u C-u C-u C-c C-w'."
2177 :group 'org-refile
2178 :version "24.1"
2179 :type 'boolean)
2181 (defcustom org-refile-use-outline-path nil
2182 "Non-nil means provide refile targets as paths.
2183 So a level 3 headline will be available as level1/level2/level3.
2185 When the value is `file', also include the file name (without directory)
2186 into the path. In this case, you can also stop the completion after
2187 the file name, to get entries inserted as top level in the file.
2189 When `full-file-path', include the full file path."
2190 :group 'org-refile
2191 :type '(choice
2192 (const :tag "Not" nil)
2193 (const :tag "Yes" t)
2194 (const :tag "Start with file name" file)
2195 (const :tag "Start with full file path" full-file-path)))
2197 (defcustom org-outline-path-complete-in-steps t
2198 "Non-nil means complete the outline path in hierarchical steps.
2199 When Org-mode uses the refile interface to select an outline path
2200 \(see variable `org-refile-use-outline-path'), the completion of
2201 the path can be done is a single go, or if can be done in steps down
2202 the headline hierarchy. Going in steps is probably the best if you
2203 do not use a special completion package like `ido' or `icicles'.
2204 However, when using these packages, going in one step can be very
2205 fast, while still showing the whole path to the entry."
2206 :group 'org-refile
2207 :type 'boolean)
2209 (defcustom org-refile-allow-creating-parent-nodes nil
2210 "Non-nil means allow to create new nodes as refile targets.
2211 New nodes are then created by adding \"/new node name\" to the completion
2212 of an existing node. When the value of this variable is `confirm',
2213 new node creation must be confirmed by the user (recommended)
2214 When nil, the completion must match an existing entry.
2216 Note that, if the new heading is not seen by the criteria
2217 listed in `org-refile-targets', multiple instances of the same
2218 heading would be created by trying again to file under the new
2219 heading."
2220 :group 'org-refile
2221 :type '(choice
2222 (const :tag "Never" nil)
2223 (const :tag "Always" t)
2224 (const :tag "Prompt for confirmation" confirm)))
2226 (defcustom org-refile-active-region-within-subtree nil
2227 "Non-nil means also refile active region within a subtree.
2229 By default `org-refile' doesn't allow refiling regions if they
2230 don't contain a set of subtrees, but it might be convenient to
2231 do so sometimes: in that case, the first line of the region is
2232 converted to a headline before refiling."
2233 :group 'org-refile
2234 :version "24.1"
2235 :type 'boolean)
2237 (defgroup org-todo nil
2238 "Options concerning TODO items in Org-mode."
2239 :tag "Org TODO"
2240 :group 'org)
2242 (defgroup org-progress nil
2243 "Options concerning Progress logging in Org-mode."
2244 :tag "Org Progress"
2245 :group 'org-time)
2247 (defvar org-todo-interpretation-widgets
2248 '((:tag "Sequence (cycling hits every state)" sequence)
2249 (:tag "Type (cycling directly to DONE)" type))
2250 "The available interpretation symbols for customizing `org-todo-keywords'.
2251 Interested libraries should add to this list.")
2253 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2254 "List of TODO entry keyword sequences and their interpretation.
2255 \\<org-mode-map>This is a list of sequences.
2257 Each sequence starts with a symbol, either `sequence' or `type',
2258 indicating if the keywords should be interpreted as a sequence of
2259 action steps, or as different types of TODO items. The first
2260 keywords are states requiring action - these states will select a headline
2261 for inclusion into the global TODO list Org-mode produces. If one of
2262 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2263 signify that no further action is necessary. If \"|\" is not found,
2264 the last keyword is treated as the only DONE state of the sequence.
2266 The command \\[org-todo] cycles an entry through these states, and one
2267 additional state where no keyword is present. For details about this
2268 cycling, see the manual.
2270 TODO keywords and interpretation can also be set on a per-file basis with
2271 the special #+SEQ_TODO and #+TYP_TODO lines.
2273 Each keyword can optionally specify a character for fast state selection
2274 \(in combination with the variable `org-use-fast-todo-selection')
2275 and specifiers for state change logging, using the same syntax that
2276 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2277 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2278 indicates to record a time stamp each time this state is selected.
2280 Each keyword may also specify if a timestamp or a note should be
2281 recorded when entering or leaving the state, by adding additional
2282 characters in the parenthesis after the keyword. This looks like this:
2283 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2284 record only the time of the state change. With X and Y being either
2285 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2286 Y when leaving the state if and only if the *target* state does not
2287 define X. You may omit any of the fast-selection key or X or /Y,
2288 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2290 For backward compatibility, this variable may also be just a list
2291 of keywords. In this case the interpretation (sequence or type) will be
2292 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2293 :group 'org-todo
2294 :group 'org-keywords
2295 :type '(choice
2296 (repeat :tag "Old syntax, just keywords"
2297 (string :tag "Keyword"))
2298 (repeat :tag "New syntax"
2299 (cons
2300 (choice
2301 :tag "Interpretation"
2302 ;;Quick and dirty way to see
2303 ;;`org-todo-interpretations'. This takes the
2304 ;;place of item arguments
2305 :convert-widget
2306 (lambda (widget)
2307 (widget-put widget
2308 :args (mapcar
2309 #'(lambda (x)
2310 (widget-convert
2311 (cons 'const x)))
2312 org-todo-interpretation-widgets))
2313 widget))
2314 (repeat
2315 (string :tag "Keyword"))))))
2317 (defvar org-todo-keywords-1 nil
2318 "All TODO and DONE keywords active in a buffer.")
2319 (make-variable-buffer-local 'org-todo-keywords-1)
2320 (defvar org-todo-keywords-for-agenda nil)
2321 (defvar org-done-keywords-for-agenda nil)
2322 (defvar org-drawers-for-agenda nil)
2323 (defvar org-todo-keyword-alist-for-agenda nil)
2324 (defvar org-tag-alist-for-agenda nil
2325 "Alist of all tags from all agenda files.")
2326 (defvar org-tag-groups-alist-for-agenda nil
2327 "Alist of all groups tags from all current agenda files.")
2328 (defvar org-tag-groups-alist nil)
2329 (make-variable-buffer-local 'org-tag-groups-alist)
2330 (defvar org-agenda-contributing-files nil)
2331 (defvar org-not-done-keywords nil)
2332 (make-variable-buffer-local 'org-not-done-keywords)
2333 (defvar org-done-keywords nil)
2334 (make-variable-buffer-local 'org-done-keywords)
2335 (defvar org-todo-heads nil)
2336 (make-variable-buffer-local 'org-todo-heads)
2337 (defvar org-todo-sets nil)
2338 (make-variable-buffer-local 'org-todo-sets)
2339 (defvar org-todo-log-states nil)
2340 (make-variable-buffer-local 'org-todo-log-states)
2341 (defvar org-todo-kwd-alist nil)
2342 (make-variable-buffer-local 'org-todo-kwd-alist)
2343 (defvar org-todo-key-alist nil)
2344 (make-variable-buffer-local 'org-todo-key-alist)
2345 (defvar org-todo-key-trigger nil)
2346 (make-variable-buffer-local 'org-todo-key-trigger)
2348 (defcustom org-todo-interpretation 'sequence
2349 "Controls how TODO keywords are interpreted.
2350 This variable is in principle obsolete and is only used for
2351 backward compatibility, if the interpretation of todo keywords is
2352 not given already in `org-todo-keywords'. See that variable for
2353 more information."
2354 :group 'org-todo
2355 :group 'org-keywords
2356 :type '(choice (const sequence)
2357 (const type)))
2359 (defcustom org-use-fast-todo-selection t
2360 "Non-nil means use the fast todo selection scheme with C-c C-t.
2361 This variable describes if and under what circumstances the cycling
2362 mechanism for TODO keywords will be replaced by a single-key, direct
2363 selection scheme.
2365 When nil, fast selection is never used.
2367 When the symbol `prefix', it will be used when `org-todo' is called
2368 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2369 `C-u t' in an agenda buffer.
2371 When t, fast selection is used by default. In this case, the prefix
2372 argument forces cycling instead.
2374 In all cases, the special interface is only used if access keys have
2375 actually been assigned by the user, i.e. if keywords in the configuration
2376 are followed by a letter in parenthesis, like TODO(t)."
2377 :group 'org-todo
2378 :type '(choice
2379 (const :tag "Never" nil)
2380 (const :tag "By default" t)
2381 (const :tag "Only with C-u C-c C-t" prefix)))
2383 (defcustom org-provide-todo-statistics t
2384 "Non-nil means update todo statistics after insert and toggle.
2385 ALL-HEADLINES means update todo statistics by including headlines
2386 with no TODO keyword as well, counting them as not done.
2387 A list of TODO keywords means the same, but skip keywords that are
2388 not in this list.
2390 When this is set, todo statistics is updated in the parent of the
2391 current entry each time a todo state is changed."
2392 :group 'org-todo
2393 :type '(choice
2394 (const :tag "Yes, only for TODO entries" t)
2395 (const :tag "Yes, including all entries" 'all-headlines)
2396 (repeat :tag "Yes, for TODOs in this list"
2397 (string :tag "TODO keyword"))
2398 (other :tag "No TODO statistics" nil)))
2400 (defcustom org-hierarchical-todo-statistics t
2401 "Non-nil means TODO statistics covers just direct children.
2402 When nil, all entries in the subtree are considered.
2403 This has only an effect if `org-provide-todo-statistics' is set.
2404 To set this to nil for only a single subtree, use a COOKIE_DATA
2405 property and include the word \"recursive\" into the value."
2406 :group 'org-todo
2407 :type 'boolean)
2409 (defcustom org-after-todo-state-change-hook nil
2410 "Hook which is run after the state of a TODO item was changed.
2411 The new state (a string with a TODO keyword, or nil) is available in the
2412 Lisp variable `org-state'."
2413 :group 'org-todo
2414 :type 'hook)
2416 (defvar org-blocker-hook nil
2417 "Hook for functions that are allowed to block a state change.
2419 Functions in this hook should not modify the buffer.
2420 Each function gets as its single argument a property list,
2421 see `org-trigger-hook' for more information about this list.
2423 If any of the functions in this hook returns nil, the state change
2424 is blocked.")
2426 (defvar org-trigger-hook nil
2427 "Hook for functions that are triggered by a state change.
2429 Each function gets as its single argument a property list with at
2430 least the following elements:
2432 (:type type-of-change :position pos-at-entry-start
2433 :from old-state :to new-state)
2435 Depending on the type, more properties may be present.
2437 This mechanism is currently implemented for:
2439 TODO state changes
2440 ------------------
2441 :type todo-state-change
2442 :from previous state (keyword as a string), or nil, or a symbol
2443 'todo' or 'done', to indicate the general type of state.
2444 :to new state, like in :from")
2446 (defcustom org-enforce-todo-dependencies nil
2447 "Non-nil means undone TODO entries will block switching the parent to DONE.
2448 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2449 be blocked if any prior sibling is not yet done.
2450 Finally, if the parent is blocked because of ordered siblings of its own,
2451 the child will also be blocked."
2452 :set (lambda (var val)
2453 (set var val)
2454 (if val
2455 (add-hook 'org-blocker-hook
2456 'org-block-todo-from-children-or-siblings-or-parent)
2457 (remove-hook 'org-blocker-hook
2458 'org-block-todo-from-children-or-siblings-or-parent)))
2459 :group 'org-todo
2460 :type 'boolean)
2462 (defcustom org-enforce-todo-checkbox-dependencies nil
2463 "Non-nil means unchecked boxes will block switching the parent to DONE.
2464 When this is nil, checkboxes have no influence on switching TODO states.
2465 When non-nil, you first need to check off all check boxes before the TODO
2466 entry can be switched to DONE.
2467 This variable needs to be set before org.el is loaded, and you need to
2468 restart Emacs after a change to make the change effective. The only way
2469 to change is while Emacs is running is through the customize interface."
2470 :set (lambda (var val)
2471 (set var val)
2472 (if val
2473 (add-hook 'org-blocker-hook
2474 'org-block-todo-from-checkboxes)
2475 (remove-hook 'org-blocker-hook
2476 'org-block-todo-from-checkboxes)))
2477 :group 'org-todo
2478 :type 'boolean)
2480 (defcustom org-treat-insert-todo-heading-as-state-change nil
2481 "Non-nil means inserting a TODO heading is treated as state change.
2482 So when the command \\[org-insert-todo-heading] is used, state change
2483 logging will apply if appropriate. When nil, the new TODO item will
2484 be inserted directly, and no logging will take place."
2485 :group 'org-todo
2486 :type 'boolean)
2488 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2489 "Non-nil means switching TODO states with S-cursor counts as state change.
2490 This is the default behavior. However, setting this to nil allows a
2491 convenient way to select a TODO state and bypass any logging associated
2492 with that."
2493 :group 'org-todo
2494 :type 'boolean)
2496 (defcustom org-todo-state-tags-triggers nil
2497 "Tag changes that should be triggered by TODO state changes.
2498 This is a list. Each entry is
2500 (state-change (tag . flag) .......)
2502 State-change can be a string with a state, and empty string to indicate the
2503 state that has no TODO keyword, or it can be one of the symbols `todo'
2504 or `done', meaning any not-done or done state, respectively."
2505 :group 'org-todo
2506 :group 'org-tags
2507 :type '(repeat
2508 (cons (choice :tag "When changing to"
2509 (const :tag "Not-done state" todo)
2510 (const :tag "Done state" done)
2511 (string :tag "State"))
2512 (repeat
2513 (cons :tag "Tag action"
2514 (string :tag "Tag")
2515 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2517 (defcustom org-log-done nil
2518 "Information to record when a task moves to the DONE state.
2520 Possible values are:
2522 nil Don't add anything, just change the keyword
2523 time Add a time stamp to the task
2524 note Prompt for a note and add it with template `org-log-note-headings'
2526 This option can also be set with on a per-file-basis with
2528 #+STARTUP: nologdone
2529 #+STARTUP: logdone
2530 #+STARTUP: lognotedone
2532 You can have local logging settings for a subtree by setting the LOGGING
2533 property to one or more of these keywords."
2534 :group 'org-todo
2535 :group 'org-progress
2536 :type '(choice
2537 (const :tag "No logging" nil)
2538 (const :tag "Record CLOSED timestamp" time)
2539 (const :tag "Record CLOSED timestamp with note." note)))
2541 ;; Normalize old uses of org-log-done.
2542 (cond
2543 ((eq org-log-done t) (setq org-log-done 'time))
2544 ((and (listp org-log-done) (memq 'done org-log-done))
2545 (setq org-log-done 'note)))
2547 (defcustom org-log-reschedule nil
2548 "Information to record when the scheduling date of a tasks is modified.
2550 Possible values are:
2552 nil Don't add anything, just change the date
2553 time Add a time stamp to the task
2554 note Prompt for a note and add it with template `org-log-note-headings'
2556 This option can also be set with on a per-file-basis with
2558 #+STARTUP: nologreschedule
2559 #+STARTUP: logreschedule
2560 #+STARTUP: lognotereschedule"
2561 :group 'org-todo
2562 :group 'org-progress
2563 :type '(choice
2564 (const :tag "No logging" nil)
2565 (const :tag "Record timestamp" time)
2566 (const :tag "Record timestamp with note." note)))
2568 (defcustom org-log-redeadline nil
2569 "Information to record when the deadline date of a tasks is modified.
2571 Possible values are:
2573 nil Don't add anything, just change the date
2574 time Add a time stamp to the task
2575 note Prompt for a note and add it with template `org-log-note-headings'
2577 This option can also be set with on a per-file-basis with
2579 #+STARTUP: nologredeadline
2580 #+STARTUP: logredeadline
2581 #+STARTUP: lognoteredeadline
2583 You can have local logging settings for a subtree by setting the LOGGING
2584 property to one or more of these keywords."
2585 :group 'org-todo
2586 :group 'org-progress
2587 :type '(choice
2588 (const :tag "No logging" nil)
2589 (const :tag "Record timestamp" time)
2590 (const :tag "Record timestamp with note." note)))
2592 (defcustom org-log-note-clock-out nil
2593 "Non-nil means record a note when clocking out of an item.
2594 This can also be configured on a per-file basis by adding one of
2595 the following lines anywhere in the buffer:
2597 #+STARTUP: lognoteclock-out
2598 #+STARTUP: nolognoteclock-out"
2599 :group 'org-todo
2600 :group 'org-progress
2601 :type 'boolean)
2603 (defcustom org-log-done-with-time t
2604 "Non-nil means the CLOSED time stamp will contain date and time.
2605 When nil, only the date will be recorded."
2606 :group 'org-progress
2607 :type 'boolean)
2609 (defcustom org-log-note-headings
2610 '((done . "CLOSING NOTE %t")
2611 (state . "State %-12s from %-12S %t")
2612 (note . "Note taken on %t")
2613 (reschedule . "Rescheduled from %S on %t")
2614 (delschedule . "Not scheduled, was %S on %t")
2615 (redeadline . "New deadline from %S on %t")
2616 (deldeadline . "Removed deadline, was %S on %t")
2617 (refile . "Refiled on %t")
2618 (clock-out . ""))
2619 "Headings for notes added to entries.
2620 The value is an alist, with the car being a symbol indicating the note
2621 context, and the cdr is the heading to be used. The heading may also be the
2622 empty string.
2623 %t in the heading will be replaced by a time stamp.
2624 %T will be an active time stamp instead the default inactive one
2625 %d will be replaced by a short-format time stamp.
2626 %D will be replaced by an active short-format time stamp.
2627 %s will be replaced by the new TODO state, in double quotes.
2628 %S will be replaced by the old TODO state, in double quotes.
2629 %u will be replaced by the user name.
2630 %U will be replaced by the full user name.
2632 In fact, it is not a good idea to change the `state' entry, because
2633 agenda log mode depends on the format of these entries."
2634 :group 'org-todo
2635 :group 'org-progress
2636 :type '(list :greedy t
2637 (cons (const :tag "Heading when closing an item" done) string)
2638 (cons (const :tag
2639 "Heading when changing todo state (todo sequence only)"
2640 state) string)
2641 (cons (const :tag "Heading when just taking a note" note) string)
2642 (cons (const :tag "Heading when clocking out" clock-out) string)
2643 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2644 (cons (const :tag "Heading when rescheduling" reschedule) string)
2645 (cons (const :tag "Heading when changing deadline" redeadline) string)
2646 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2647 (cons (const :tag "Heading when refiling" refile) string)))
2649 (unless (assq 'note org-log-note-headings)
2650 (push '(note . "%t") org-log-note-headings))
2652 (defcustom org-log-into-drawer nil
2653 "Non-nil means insert state change notes and time stamps into a drawer.
2654 When nil, state changes notes will be inserted after the headline and
2655 any scheduling and clock lines, but not inside a drawer.
2657 The value of this variable should be the name of the drawer to use.
2658 LOGBOOK is proposed as the default drawer for this purpose, you can
2659 also set this to a string to define the drawer of your choice.
2661 A value of t is also allowed, representing \"LOGBOOK\".
2663 A value of t or nil can also be set with on a per-file-basis with
2665 #+STARTUP: logdrawer
2666 #+STARTUP: nologdrawer
2668 If this variable is set, `org-log-state-notes-insert-after-drawers'
2669 will be ignored.
2671 You can set the property LOG_INTO_DRAWER to overrule this setting for
2672 a subtree."
2673 :group 'org-todo
2674 :group 'org-progress
2675 :type '(choice
2676 (const :tag "Not into a drawer" nil)
2677 (const :tag "LOGBOOK" t)
2678 (string :tag "Other")))
2680 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2682 (defun org-log-into-drawer ()
2683 "Return the value of `org-log-into-drawer', but let properties overrule.
2684 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2685 used instead of the default value."
2686 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2687 (cond
2688 ((not p) org-log-into-drawer)
2689 ((equal p "nil") nil)
2690 ((equal p "t") "LOGBOOK")
2691 (t p))))
2693 (defcustom org-log-state-notes-insert-after-drawers nil
2694 "Non-nil means insert state change notes after any drawers in entry.
2695 Only the drawers that *immediately* follow the headline and the
2696 deadline/scheduled line are skipped.
2697 When nil, insert notes right after the heading and perhaps the line
2698 with deadline/scheduling if present.
2700 This variable will have no effect if `org-log-into-drawer' is
2701 set."
2702 :group 'org-todo
2703 :group 'org-progress
2704 :type 'boolean)
2706 (defcustom org-log-states-order-reversed t
2707 "Non-nil means the latest state note will be directly after heading.
2708 When nil, the state change notes will be ordered according to time.
2710 This option can also be set with on a per-file-basis with
2712 #+STARTUP: logstatesreversed
2713 #+STARTUP: nologstatesreversed"
2714 :group 'org-todo
2715 :group 'org-progress
2716 :type 'boolean)
2718 (defcustom org-todo-repeat-to-state nil
2719 "The TODO state to which a repeater should return the repeating task.
2720 By default this is the first task in a TODO sequence, or the previous state
2721 in a TODO_TYP set. But you can specify another task here.
2722 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2723 :group 'org-todo
2724 :version "24.1"
2725 :type '(choice (const :tag "Head of sequence" nil)
2726 (string :tag "Specific state")))
2728 (defcustom org-log-repeat 'time
2729 "Non-nil means record moving through the DONE state when triggering repeat.
2730 An auto-repeating task is immediately switched back to TODO when
2731 marked DONE. If you are not logging state changes (by adding \"@\"
2732 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2733 record a closing note, there will be no record of the task moving
2734 through DONE. This variable forces taking a note anyway.
2736 nil Don't force a record
2737 time Record a time stamp
2738 note Prompt for a note and add it with template `org-log-note-headings'
2740 This option can also be set with on a per-file-basis with
2742 #+STARTUP: nologrepeat
2743 #+STARTUP: logrepeat
2744 #+STARTUP: lognoterepeat
2746 You can have local logging settings for a subtree by setting the LOGGING
2747 property to one or more of these keywords."
2748 :group 'org-todo
2749 :group 'org-progress
2750 :type '(choice
2751 (const :tag "Don't force a record" nil)
2752 (const :tag "Force recording the DONE state" time)
2753 (const :tag "Force recording a note with the DONE state" note)))
2756 (defgroup org-priorities nil
2757 "Priorities in Org-mode."
2758 :tag "Org Priorities"
2759 :group 'org-todo)
2761 (defcustom org-enable-priority-commands t
2762 "Non-nil means priority commands are active.
2763 When nil, these commands will be disabled, so that you never accidentally
2764 set a priority."
2765 :group 'org-priorities
2766 :type 'boolean)
2768 (defcustom org-highest-priority ?A
2769 "The highest priority of TODO items. A character like ?A, ?B etc.
2770 Must have a smaller ASCII number than `org-lowest-priority'."
2771 :group 'org-priorities
2772 :type 'character)
2774 (defcustom org-lowest-priority ?C
2775 "The lowest priority of TODO items. A character like ?A, ?B etc.
2776 Must have a larger ASCII number than `org-highest-priority'."
2777 :group 'org-priorities
2778 :type 'character)
2780 (defcustom org-default-priority ?B
2781 "The default priority of TODO items.
2782 This is the priority an item gets if no explicit priority is given.
2783 When starting to cycle on an empty priority the first step in the cycle
2784 depends on `org-priority-start-cycle-with-default'. The resulting first
2785 step priority must not exceed the range from `org-highest-priority' to
2786 `org-lowest-priority' which means that `org-default-priority' has to be
2787 in this range exclusive or inclusive the range boundaries. Else the
2788 first step refuses to set the default and the second will fall back
2789 to (depending on the command used) the highest or lowest priority."
2790 :group 'org-priorities
2791 :type 'character)
2793 (defcustom org-priority-start-cycle-with-default t
2794 "Non-nil means start with default priority when starting to cycle.
2795 When this is nil, the first step in the cycle will be (depending on the
2796 command used) one higher or lower than the default priority.
2797 See also `org-default-priority'."
2798 :group 'org-priorities
2799 :type 'boolean)
2801 (defcustom org-get-priority-function nil
2802 "Function to extract the priority from a string.
2803 The string is normally the headline. If this is nil Org computes the
2804 priority from the priority cookie like [#A] in the headline. It returns
2805 an integer, increasing by 1000 for each priority level.
2806 The user can set a different function here, which should take a string
2807 as an argument and return the numeric priority."
2808 :group 'org-priorities
2809 :version "24.1"
2810 :type 'function)
2812 (defgroup org-time nil
2813 "Options concerning time stamps and deadlines in Org-mode."
2814 :tag "Org Time"
2815 :group 'org)
2817 (defcustom org-insert-labeled-timestamps-at-point nil
2818 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2819 When nil, these labeled time stamps are forces into the second line of an
2820 entry, just after the headline. When scheduling from the global TODO list,
2821 the time stamp will always be forced into the second line."
2822 :group 'org-time
2823 :type 'boolean)
2825 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2826 "Formats for `format-time-string' which are used for time stamps.
2827 It is not recommended to change this constant.")
2829 (defcustom org-time-stamp-rounding-minutes '(0 5)
2830 "Number of minutes to round time stamps to.
2831 These are two values, the first applies when first creating a time stamp.
2832 The second applies when changing it with the commands `S-up' and `S-down'.
2833 When changing the time stamp, this means that it will change in steps
2834 of N minutes, as given by the second value.
2836 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2837 numbers should be factors of 60, so for example 5, 10, 15.
2839 When this is larger than 1, you can still force an exact time stamp by using
2840 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2841 and by using a prefix arg to `S-up/down' to specify the exact number
2842 of minutes to shift."
2843 :group 'org-time
2844 :get #'(lambda (var) ; Make sure both elements are there
2845 (if (integerp (default-value var))
2846 (list (default-value var) 5)
2847 (default-value var)))
2848 :type '(list
2849 (integer :tag "when inserting times")
2850 (integer :tag "when modifying times")))
2852 ;; Normalize old customizations of this variable.
2853 (when (integerp org-time-stamp-rounding-minutes)
2854 (setq org-time-stamp-rounding-minutes
2855 (list org-time-stamp-rounding-minutes
2856 org-time-stamp-rounding-minutes)))
2858 (defcustom org-display-custom-times nil
2859 "Non-nil means overlay custom formats over all time stamps.
2860 The formats are defined through the variable `org-time-stamp-custom-formats'.
2861 To turn this on on a per-file basis, insert anywhere in the file:
2862 #+STARTUP: customtime"
2863 :group 'org-time
2864 :set 'set-default
2865 :type 'sexp)
2866 (make-variable-buffer-local 'org-display-custom-times)
2868 (defcustom org-time-stamp-custom-formats
2869 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2870 "Custom formats for time stamps. See `format-time-string' for the syntax.
2871 These are overlaid over the default ISO format if the variable
2872 `org-display-custom-times' is set. Time like %H:%M should be at the
2873 end of the second format. The custom formats are also honored by export
2874 commands, if custom time display is turned on at the time of export."
2875 :group 'org-time
2876 :type 'sexp)
2878 (defun org-time-stamp-format (&optional long inactive)
2879 "Get the right format for a time string."
2880 (let ((f (if long (cdr org-time-stamp-formats)
2881 (car org-time-stamp-formats))))
2882 (if inactive
2883 (concat "[" (substring f 1 -1) "]")
2884 f)))
2886 (defcustom org-time-clocksum-format
2887 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2888 "The format string used when creating CLOCKSUM lines.
2889 This is also used when Org mode generates a time duration.
2891 The value can be a single format string containing two
2892 %-sequences, which will be filled with the number of hours and
2893 minutes in that order.
2895 Alternatively, the value can be a plist associating any of the
2896 keys :years, :months, :weeks, :days, :hours or :minutes with
2897 format strings. The time duration is formatted using only the
2898 time components that are needed and concatenating the results.
2899 If a time unit in absent, it falls back to the next smallest
2900 unit.
2902 The keys :require-years, :require-months, :require-days,
2903 :require-weeks, :require-hours, :require-minutes are also
2904 meaningful. A non-nil value for these keys indicates that the
2905 corresponding time component should always be included, even if
2906 its value is 0.
2909 For example,
2911 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2912 :require-minutes t)
2914 means durations longer than a day will be expressed in days,
2915 hours and minutes, and durations less than a day will always be
2916 expressed in hours and minutes (even for durations less than an
2917 hour).
2919 The value
2921 \(:days \"%dd\" :minutes \"%dm\")
2923 means durations longer than a day will be expressed in days and
2924 minutes, and durations less than a day will be expressed entirely
2925 in minutes (even for durations longer than an hour)."
2926 :group 'org-time
2927 :group 'org-clock
2928 :version "24.4"
2929 :package-version '(Org . "8.0")
2930 :type '(choice (string :tag "Format string")
2931 (set :tag "Plist"
2932 (group :inline t (const :tag "Years" :years)
2933 (string :tag "Format string"))
2934 (group :inline t
2935 (const :tag "Always show years" :require-years)
2936 (const t))
2937 (group :inline t (const :tag "Months" :months)
2938 (string :tag "Format string"))
2939 (group :inline t
2940 (const :tag "Always show months" :require-months)
2941 (const t))
2942 (group :inline t (const :tag "Weeks" :weeks)
2943 (string :tag "Format string"))
2944 (group :inline t
2945 (const :tag "Always show weeks" :require-weeks)
2946 (const t))
2947 (group :inline t (const :tag "Days" :days)
2948 (string :tag "Format string"))
2949 (group :inline t
2950 (const :tag "Always show days" :require-days)
2951 (const t))
2952 (group :inline t (const :tag "Hours" :hours)
2953 (string :tag "Format string"))
2954 (group :inline t
2955 (const :tag "Always show hours" :require-hours)
2956 (const t))
2957 (group :inline t (const :tag "Minutes" :minutes)
2958 (string :tag "Format string"))
2959 (group :inline t
2960 (const :tag "Always show minutes" :require-minutes)
2961 (const t)))))
2963 (defcustom org-time-clocksum-use-fractional nil
2964 "When non-nil, \\[org-clock-display] uses fractional times.
2965 See `org-time-clocksum-format' for more on time clock formats."
2966 :group 'org-time
2967 :group 'org-clock
2968 :version "24.3"
2969 :type 'boolean)
2971 (defcustom org-time-clocksum-use-effort-durations nil
2972 "When non-nil, \\[org-clock-display] uses effort durations.
2973 E.g. by default, one day is considered to be a 8 hours effort,
2974 so a task that has been clocked for 16 hours will be displayed
2975 as during 2 days in the clock display or in the clocktable.
2977 See `org-effort-durations' on how to set effort durations
2978 and `org-time-clocksum-format' for more on time clock formats."
2979 :group 'org-time
2980 :group 'org-clock
2981 :version "24.4"
2982 :package-version '(Org . "8.0")
2983 :type 'boolean)
2985 (defcustom org-time-clocksum-fractional-format "%.2f"
2986 "The format string used when creating CLOCKSUM lines,
2987 or when Org mode generates a time duration, if
2988 `org-time-clocksum-use-fractional' is enabled.
2990 The value can be a single format string containing one
2991 %-sequence, which will be filled with the number of hours as
2992 a float.
2994 Alternatively, the value can be a plist associating any of the
2995 keys :years, :months, :weeks, :days, :hours or :minutes with
2996 a format string. The time duration is formatted using the
2997 largest time unit which gives a non-zero integer part. If all
2998 specified formats have zero integer part, the smallest time unit
2999 is used."
3000 :group 'org-time
3001 :type '(choice (string :tag "Format string")
3002 (set (group :inline t (const :tag "Years" :years)
3003 (string :tag "Format string"))
3004 (group :inline t (const :tag "Months" :months)
3005 (string :tag "Format string"))
3006 (group :inline t (const :tag "Weeks" :weeks)
3007 (string :tag "Format string"))
3008 (group :inline t (const :tag "Days" :days)
3009 (string :tag "Format string"))
3010 (group :inline t (const :tag "Hours" :hours)
3011 (string :tag "Format string"))
3012 (group :inline t (const :tag "Minutes" :minutes)
3013 (string :tag "Format string")))))
3015 (defcustom org-deadline-warning-days 14
3016 "Number of days before expiration during which a deadline becomes active.
3017 This variable governs the display in sparse trees and in the agenda.
3018 When 0 or negative, it means use this number (the absolute value of it)
3019 even if a deadline has a different individual lead time specified.
3021 Custom commands can set this variable in the options section."
3022 :group 'org-time
3023 :group 'org-agenda-daily/weekly
3024 :type 'integer)
3026 (defcustom org-scheduled-delay-days 0
3027 "Number of days before a scheduled item becomes active.
3028 This variable governs the display in sparse trees and in the agenda.
3029 The default value (i.e. 0) means: don't delay scheduled item.
3030 When negative, it means use this number (the absolute value of it)
3031 even if a scheduled item has a different individual delay time
3032 specified.
3034 Custom commands can set this variable in the options section."
3035 :group 'org-time
3036 :group 'org-agenda-daily/weekly
3037 :version "24.4"
3038 :package-version '(Org . "8.0")
3039 :type 'integer)
3041 (defcustom org-read-date-prefer-future t
3042 "Non-nil means assume future for incomplete date input from user.
3043 This affects the following situations:
3044 1. The user gives a month but not a year.
3045 For example, if it is April and you enter \"feb 2\", this will be read
3046 as Feb 2, *next* year. \"May 5\", however, will be this year.
3047 2. The user gives a day, but no month.
3048 For example, if today is the 15th, and you enter \"3\", Org-mode will
3049 read this as the third of *next* month. However, if you enter \"17\",
3050 it will be considered as *this* month.
3052 If you set this variable to the symbol `time', then also the following
3053 will work:
3055 3. If the user gives a time.
3056 If the time is before now, it will be interpreted as tomorrow.
3058 Currently none of this works for ISO week specifications.
3060 When this option is nil, the current day, month and year will always be
3061 used as defaults.
3063 See also `org-agenda-jump-prefer-future'."
3064 :group 'org-time
3065 :type '(choice
3066 (const :tag "Never" nil)
3067 (const :tag "Check month and day" t)
3068 (const :tag "Check month, day, and time" time)))
3070 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3071 "Should the agenda jump command prefer the future for incomplete dates?
3072 The default is to do the same as configured in `org-read-date-prefer-future'.
3073 But you can also set a deviating value here.
3074 This may t or nil, or the symbol `org-read-date-prefer-future'."
3075 :group 'org-agenda
3076 :group 'org-time
3077 :version "24.1"
3078 :type '(choice
3079 (const :tag "Use org-read-date-prefer-future"
3080 org-read-date-prefer-future)
3081 (const :tag "Never" nil)
3082 (const :tag "Always" t)))
3084 (defcustom org-read-date-force-compatible-dates t
3085 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3087 Depending on the system Emacs is running on, certain dates cannot
3088 be represented with the type used internally to represent time.
3089 Dates between 1970-1-1 and 2038-1-1 can always be represented
3090 correctly. Some systems allow for earlier dates, some for later,
3091 some for both. One way to find out it to insert any date into an
3092 Org buffer, putting the cursor on the year and hitting S-up and
3093 S-down to test the range.
3095 When this variable is set to t, the date/time prompt will not let
3096 you specify dates outside the 1970-2037 range, so it is certain that
3097 these dates will work in whatever version of Emacs you are
3098 running, and also that you can move a file from one Emacs implementation
3099 to another. WHenever Org is forcing the year for you, it will display
3100 a message and beep.
3102 When this variable is nil, Org will check if the date is
3103 representable in the specific Emacs implementation you are using.
3104 If not, it will force a year, usually the current year, and beep
3105 to remind you. Currently this setting is not recommended because
3106 the likelihood that you will open your Org files in an Emacs that
3107 has limited date range is not negligible.
3109 A workaround for this problem is to use diary sexp dates for time
3110 stamps outside of this range."
3111 :group 'org-time
3112 :version "24.1"
3113 :type 'boolean)
3115 (defcustom org-read-date-display-live t
3116 "Non-nil means display current interpretation of date prompt live.
3117 This display will be in an overlay, in the minibuffer."
3118 :group 'org-time
3119 :type 'boolean)
3121 (defcustom org-read-date-popup-calendar t
3122 "Non-nil means pop up a calendar when prompting for a date.
3123 In the calendar, the date can be selected with mouse-1. However, the
3124 minibuffer will also be active, and you can simply enter the date as well.
3125 When nil, only the minibuffer will be available."
3126 :group 'org-time
3127 :type 'boolean)
3128 (org-defvaralias 'org-popup-calendar-for-date-prompt
3129 'org-read-date-popup-calendar)
3131 (make-obsolete-variable
3132 'org-read-date-minibuffer-setup-hook
3133 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3134 (defcustom org-read-date-minibuffer-setup-hook nil
3135 "Hook to be used to set up keys for the date/time interface.
3136 Add key definitions to `minibuffer-local-map', which will be a
3137 temporary copy.
3139 WARNING: This option is obsolete, you should use
3140 `org-read-date-minibuffer-local-map' to set up keys."
3141 :group 'org-time
3142 :type 'hook)
3144 (defcustom org-extend-today-until 0
3145 "The hour when your day really ends. Must be an integer.
3146 This has influence for the following applications:
3147 - When switching the agenda to \"today\". It it is still earlier than
3148 the time given here, the day recognized as TODAY is actually yesterday.
3149 - When a date is read from the user and it is still before the time given
3150 here, the current date and time will be assumed to be yesterday, 23:59.
3151 Also, timestamps inserted in capture templates follow this rule.
3153 IMPORTANT: This is a feature whose implementation is and likely will
3154 remain incomplete. Really, it is only here because past midnight seems to
3155 be the favorite working time of John Wiegley :-)"
3156 :group 'org-time
3157 :type 'integer)
3159 (defcustom org-use-effective-time nil
3160 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3161 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3162 \"effective time\" of any timestamps between midnight and 8am will be
3163 23:59 of the previous day."
3164 :group 'org-time
3165 :version "24.1"
3166 :type 'boolean)
3168 (defcustom org-use-last-clock-out-time-as-effective-time nil
3169 "When non-nil, use the last clock out time for `org-todo'.
3170 Note that this option has precedence over the combined use of
3171 `org-use-effective-time' and `org-extend-today-until'."
3172 :group 'org-time
3173 :version "24.4"
3174 :package-version '(Org . "8.0")
3175 :type 'boolean)
3177 (defcustom org-edit-timestamp-down-means-later nil
3178 "Non-nil means S-down will increase the time in a time stamp.
3179 When nil, S-up will increase."
3180 :group 'org-time
3181 :type 'boolean)
3183 (defcustom org-calendar-follow-timestamp-change t
3184 "Non-nil means make the calendar window follow timestamp changes.
3185 When a timestamp is modified and the calendar window is visible, it will be
3186 moved to the new date."
3187 :group 'org-time
3188 :type 'boolean)
3190 (defgroup org-tags nil
3191 "Options concerning tags in Org-mode."
3192 :tag "Org Tags"
3193 :group 'org)
3195 (defcustom org-tag-alist nil
3196 "List of tags allowed in Org-mode files.
3197 When this list is nil, Org-mode will base TAG input on what is already in the
3198 buffer.
3199 The value of this variable is an alist, the car of each entry must be a
3200 keyword as a string, the cdr may be a character that is used to select
3201 that tag through the fast-tag-selection interface.
3202 See the manual for details."
3203 :group 'org-tags
3204 :type '(repeat
3205 (choice
3206 (cons (string :tag "Tag name")
3207 (character :tag "Access char"))
3208 (list :tag "Start radio group"
3209 (const :startgroup)
3210 (option (string :tag "Group description")))
3211 (list :tag "Group tags delimiter"
3212 (const :grouptags))
3213 (list :tag "End radio group"
3214 (const :endgroup)
3215 (option (string :tag "Group description")))
3216 (const :tag "New line" (:newline)))))
3218 (defcustom org-tag-persistent-alist nil
3219 "List of tags that will always appear in all Org-mode files.
3220 This is in addition to any in buffer settings or customizations
3221 of `org-tag-alist'.
3222 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3223 The value of this variable is an alist, the car of each entry must be a
3224 keyword as a string, the cdr may be a character that is used to select
3225 that tag through the fast-tag-selection interface.
3226 See the manual for details.
3227 To disable these tags on a per-file basis, insert anywhere in the file:
3228 #+STARTUP: noptag"
3229 :group 'org-tags
3230 :type '(repeat
3231 (choice
3232 (cons (string :tag "Tag name")
3233 (character :tag "Access char"))
3234 (const :tag "Start radio group" (:startgroup))
3235 (const :tag "Group tags delimiter" (:grouptags))
3236 (const :tag "End radio group" (:endgroup))
3237 (const :tag "New line" (:newline)))))
3239 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3240 "If non-nil, always offer completion for all tags of all agenda files.
3241 Instead of customizing this variable directly, you might want to
3242 set it locally for capture buffers, because there no list of
3243 tags in that file can be created dynamically (there are none).
3245 (add-hook 'org-capture-mode-hook
3246 (lambda ()
3247 (set (make-local-variable
3248 'org-complete-tags-always-offer-all-agenda-tags)
3249 t)))"
3250 :group 'org-tags
3251 :version "24.1"
3252 :type 'boolean)
3254 (defvar org-file-tags nil
3255 "List of tags that can be inherited by all entries in the file.
3256 The tags will be inherited if the variable `org-use-tag-inheritance'
3257 says they should be.
3258 This variable is populated from #+FILETAGS lines.")
3260 (defcustom org-use-fast-tag-selection 'auto
3261 "Non-nil means use fast tag selection scheme.
3262 This is a special interface to select and deselect tags with single keys.
3263 When nil, fast selection is never used.
3264 When the symbol `auto', fast selection is used if and only if selection
3265 characters for tags have been configured, either through the variable
3266 `org-tag-alist' or through a #+TAGS line in the buffer.
3267 When t, fast selection is always used and selection keys are assigned
3268 automatically if necessary."
3269 :group 'org-tags
3270 :type '(choice
3271 (const :tag "Always" t)
3272 (const :tag "Never" nil)
3273 (const :tag "When selection characters are configured" 'auto)))
3275 (defcustom org-fast-tag-selection-single-key nil
3276 "Non-nil means fast tag selection exits after first change.
3277 When nil, you have to press RET to exit it.
3278 During fast tag selection, you can toggle this flag with `C-c'.
3279 This variable can also have the value `expert'. In this case, the window
3280 displaying the tags menu is not even shown, until you press C-c again."
3281 :group 'org-tags
3282 :type '(choice
3283 (const :tag "No" nil)
3284 (const :tag "Yes" t)
3285 (const :tag "Expert" expert)))
3287 (defvar org-fast-tag-selection-include-todo nil
3288 "Non-nil means fast tags selection interface will also offer TODO states.
3289 This is an undocumented feature, you should not rely on it.")
3291 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3292 "The column to which tags should be indented in a headline.
3293 If this number is positive, it specifies the column. If it is negative,
3294 it means that the tags should be flushright to that column. For example,
3295 -80 works well for a normal 80 character screen.
3296 When 0, place tags directly after headline text, with only one space in
3297 between."
3298 :group 'org-tags
3299 :type 'integer)
3301 (defcustom org-auto-align-tags t
3302 "Non-nil keeps tags aligned when modifying headlines.
3303 Some operations (i.e. demoting) change the length of a headline and
3304 therefore shift the tags around. With this option turned on, after
3305 each such operation the tags are again aligned to `org-tags-column'."
3306 :group 'org-tags
3307 :type 'boolean)
3309 (defcustom org-use-tag-inheritance t
3310 "Non-nil means tags in levels apply also for sublevels.
3311 When nil, only the tags directly given in a specific line apply there.
3312 This may also be a list of tags that should be inherited, or a regexp that
3313 matches tags that should be inherited. Additional control is possible
3314 with the variable `org-tags-exclude-from-inheritance' which gives an
3315 explicit list of tags to be excluded from inheritance, even if the value of
3316 `org-use-tag-inheritance' would select it for inheritance.
3318 If this option is t, a match early-on in a tree can lead to a large
3319 number of matches in the subtree when constructing the agenda or creating
3320 a sparse tree. If you only want to see the first match in a tree during
3321 a search, check out the variable `org-tags-match-list-sublevels'."
3322 :group 'org-tags
3323 :type '(choice
3324 (const :tag "Not" nil)
3325 (const :tag "Always" t)
3326 (repeat :tag "Specific tags" (string :tag "Tag"))
3327 (regexp :tag "Tags matched by regexp")))
3329 (defcustom org-tags-exclude-from-inheritance nil
3330 "List of tags that should never be inherited.
3331 This is a way to exclude a few tags from inheritance. For way to do
3332 the opposite, to actively allow inheritance for selected tags,
3333 see the variable `org-use-tag-inheritance'."
3334 :group 'org-tags
3335 :type '(repeat (string :tag "Tag")))
3337 (defun org-tag-inherit-p (tag)
3338 "Check if TAG is one that should be inherited."
3339 (cond
3340 ((member tag org-tags-exclude-from-inheritance) nil)
3341 ((eq org-use-tag-inheritance t) t)
3342 ((not org-use-tag-inheritance) nil)
3343 ((stringp org-use-tag-inheritance)
3344 (string-match org-use-tag-inheritance tag))
3345 ((listp org-use-tag-inheritance)
3346 (member tag org-use-tag-inheritance))
3347 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3349 (defcustom org-tags-match-list-sublevels t
3350 "Non-nil means list also sublevels of headlines matching a search.
3351 This variable applies to tags/property searches, and also to stuck
3352 projects because this search is based on a tags match as well.
3354 When set to the symbol `indented', sublevels are indented with
3355 leading dots.
3357 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3358 the sublevels of a headline matching a tag search often also match
3359 the same search. Listing all of them can create very long lists.
3360 Setting this variable to nil causes subtrees of a match to be skipped.
3362 This variable is semi-obsolete and probably should always be true. It
3363 is better to limit inheritance to certain tags using the variables
3364 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3365 :group 'org-tags
3366 :type '(choice
3367 (const :tag "No, don't list them" nil)
3368 (const :tag "Yes, do list them" t)
3369 (const :tag "List them, indented with leading dots" indented)))
3371 (defcustom org-tags-sort-function nil
3372 "When set, tags are sorted using this function as a comparator."
3373 :group 'org-tags
3374 :type '(choice
3375 (const :tag "No sorting" nil)
3376 (const :tag "Alphabetical" string<)
3377 (const :tag "Reverse alphabetical" string>)
3378 (function :tag "Custom function" nil)))
3380 (defvar org-tags-history nil
3381 "History of minibuffer reads for tags.")
3382 (defvar org-last-tags-completion-table nil
3383 "The last used completion table for tags.")
3384 (defvar org-after-tags-change-hook nil
3385 "Hook that is run after the tags in a line have changed.")
3387 (defgroup org-properties nil
3388 "Options concerning properties in Org-mode."
3389 :tag "Org Properties"
3390 :group 'org)
3392 (defcustom org-property-format "%-10s %s"
3393 "How property key/value pairs should be formatted by `indent-line'.
3394 When `indent-line' hits a property definition, it will format the line
3395 according to this format, mainly to make sure that the values are
3396 lined-up with respect to each other."
3397 :group 'org-properties
3398 :type 'string)
3400 (defcustom org-properties-postprocess-alist nil
3401 "Alist of properties and functions to adjust inserted values.
3402 Elements of this alist must be of the form
3404 ([string] [function])
3406 where [string] must be a property name and [function] must be a
3407 lambda expression: this lambda expression must take one argument,
3408 the value to adjust, and return the new value as a string.
3410 For example, this element will allow the property \"Remaining\"
3411 to be updated wrt the relation between the \"Effort\" property
3412 and the clock summary:
3414 ((\"Remaining\" (lambda(value)
3415 (let ((clocksum (org-clock-sum-current-item))
3416 (effort (org-duration-string-to-minutes
3417 (org-entry-get (point) \"Effort\"))))
3418 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3419 :group 'org-properties
3420 :version "24.1"
3421 :type '(alist :key-type (string :tag "Property")
3422 :value-type (function :tag "Function")))
3424 (defcustom org-use-property-inheritance nil
3425 "Non-nil means properties apply also for sublevels.
3427 This setting is chiefly used during property searches. Turning it on can
3428 cause significant overhead when doing a search, which is why it is not
3429 on by default.
3431 When nil, only the properties directly given in the current entry count.
3432 When t, every property is inherited. The value may also be a list of
3433 properties that should have inheritance, or a regular expression matching
3434 properties that should be inherited.
3436 However, note that some special properties use inheritance under special
3437 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3438 and the properties ending in \"_ALL\" when they are used as descriptor
3439 for valid values of a property.
3441 Note for programmers:
3442 When querying an entry with `org-entry-get', you can control if inheritance
3443 should be used. By default, `org-entry-get' looks only at the local
3444 properties. You can request inheritance by setting the inherit argument
3445 to t (to force inheritance) or to `selective' (to respect the setting
3446 in this variable)."
3447 :group 'org-properties
3448 :type '(choice
3449 (const :tag "Not" nil)
3450 (const :tag "Always" t)
3451 (repeat :tag "Specific properties" (string :tag "Property"))
3452 (regexp :tag "Properties matched by regexp")))
3454 (defun org-property-inherit-p (property)
3455 "Check if PROPERTY is one that should be inherited."
3456 (cond
3457 ((eq org-use-property-inheritance t) t)
3458 ((not org-use-property-inheritance) nil)
3459 ((stringp org-use-property-inheritance)
3460 (string-match org-use-property-inheritance property))
3461 ((listp org-use-property-inheritance)
3462 (member property org-use-property-inheritance))
3463 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3465 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3466 "The default column format, if no other format has been defined.
3467 This variable can be set on the per-file basis by inserting a line
3469 #+COLUMNS: %25ITEM ....."
3470 :group 'org-properties
3471 :type 'string)
3473 (defcustom org-columns-ellipses ".."
3474 "The ellipses to be used when a field in column view is truncated.
3475 When this is the empty string, as many characters as possible are shown,
3476 but then there will be no visual indication that the field has been truncated.
3477 When this is a string of length N, the last N characters of a truncated
3478 field are replaced by this string. If the column is narrower than the
3479 ellipses string, only part of the ellipses string will be shown."
3480 :group 'org-properties
3481 :type 'string)
3483 (defcustom org-columns-modify-value-for-display-function nil
3484 "Function that modifies values for display in column view.
3485 For example, it can be used to cut out a certain part from a time stamp.
3486 The function must take 2 arguments:
3488 column-title The title of the column (*not* the property name)
3489 value The value that should be modified.
3491 The function should return the value that should be displayed,
3492 or nil if the normal value should be used."
3493 :group 'org-properties
3494 :type 'function)
3496 (defcustom org-effort-property "Effort"
3497 "The property that is being used to keep track of effort estimates.
3498 Effort estimates given in this property need to have the format H:MM."
3499 :group 'org-properties
3500 :group 'org-progress
3501 :type '(string :tag "Property"))
3503 (defconst org-global-properties-fixed
3504 '(("VISIBILITY_ALL" . "folded children content all")
3505 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3506 "List of property/value pairs that can be inherited by any entry.
3508 These are fixed values, for the preset properties. The user variable
3509 that can be used to add to this list is `org-global-properties'.
3511 The entries in this list are cons cells where the car is a property
3512 name and cdr is a string with the value. If the value represents
3513 multiple items like an \"_ALL\" property, separate the items by
3514 spaces.")
3516 (defcustom org-global-properties nil
3517 "List of property/value pairs that can be inherited by any entry.
3519 This list will be combined with the constant `org-global-properties-fixed'.
3521 The entries in this list are cons cells where the car is a property
3522 name and cdr is a string with the value.
3524 You can set buffer-local values for the same purpose in the variable
3525 `org-file-properties' this by adding lines like
3527 #+PROPERTY: NAME VALUE"
3528 :group 'org-properties
3529 :type '(repeat
3530 (cons (string :tag "Property")
3531 (string :tag "Value"))))
3533 (defvar org-file-properties nil
3534 "List of property/value pairs that can be inherited by any entry.
3535 Valid for the current buffer.
3536 This variable is populated from #+PROPERTY lines.")
3537 (make-variable-buffer-local 'org-file-properties)
3539 (defgroup org-agenda nil
3540 "Options concerning agenda views in Org-mode."
3541 :tag "Org Agenda"
3542 :group 'org)
3544 (defvar org-category nil
3545 "Variable used by org files to set a category for agenda display.
3546 Such files should use a file variable to set it, for example
3548 # -*- mode: org; org-category: \"ELisp\"
3550 or contain a special line
3552 #+CATEGORY: ELisp
3554 If the file does not specify a category, then file's base name
3555 is used instead.")
3556 (make-variable-buffer-local 'org-category)
3557 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3559 (defcustom org-agenda-files nil
3560 "The files to be used for agenda display.
3561 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3562 \\[org-remove-file]. You can also use customize to edit the list.
3564 If an entry is a directory, all files in that directory that are matched by
3565 `org-agenda-file-regexp' will be part of the file list.
3567 If the value of the variable is not a list but a single file name, then
3568 the list of agenda files is actually stored and maintained in that file, one
3569 agenda file per line. In this file paths can be given relative to
3570 `org-directory'. Tilde expansion and environment variable substitution
3571 are also made."
3572 :group 'org-agenda
3573 :type '(choice
3574 (repeat :tag "List of files and directories" file)
3575 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3577 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3578 "Regular expression to match files for `org-agenda-files'.
3579 If any element in the list in that variable contains a directory instead
3580 of a normal file, all files in that directory that are matched by this
3581 regular expression will be included."
3582 :group 'org-agenda
3583 :type 'regexp)
3585 (defcustom org-agenda-text-search-extra-files nil
3586 "List of extra files to be searched by text search commands.
3587 These files will be search in addition to the agenda files by the
3588 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3589 Note that these files will only be searched for text search commands,
3590 not for the other agenda views like todo lists, tag searches or the weekly
3591 agenda. This variable is intended to list notes and possibly archive files
3592 that should also be searched by these two commands.
3593 In fact, if the first element in the list is the symbol `agenda-archives',
3594 than all archive files of all agenda files will be added to the search
3595 scope."
3596 :group 'org-agenda
3597 :type '(set :greedy t
3598 (const :tag "Agenda Archives" agenda-archives)
3599 (repeat :inline t (file))))
3601 (org-defvaralias 'org-agenda-multi-occur-extra-files
3602 'org-agenda-text-search-extra-files)
3604 (defcustom org-agenda-skip-unavailable-files nil
3605 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3606 A nil value means to remove them, after a query, from the list."
3607 :group 'org-agenda
3608 :type 'boolean)
3610 (defcustom org-calendar-to-agenda-key [?c]
3611 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3612 The command `org-calendar-goto-agenda' will be bound to this key. The
3613 default is the character `c' because then `c' can be used to switch back and
3614 forth between agenda and calendar."
3615 :group 'org-agenda
3616 :type 'sexp)
3618 (defcustom org-calendar-insert-diary-entry-key [?i]
3619 "The key to be installed in `calendar-mode-map' for adding diary entries.
3620 This option is irrelevant until `org-agenda-diary-file' has been configured
3621 to point to an Org-mode file. When that is the case, the command
3622 `org-agenda-diary-entry' will be bound to the key given here, by default
3623 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3624 if you want to continue doing this, you need to change this to a different
3625 key."
3626 :group 'org-agenda
3627 :type 'sexp)
3629 (defcustom org-agenda-diary-file 'diary-file
3630 "File to which to add new entries with the `i' key in agenda and calendar.
3631 When this is the symbol `diary-file', the functionality in the Emacs
3632 calendar will be used to add entries to the `diary-file'. But when this
3633 points to a file, `org-agenda-diary-entry' will be used instead."
3634 :group 'org-agenda
3635 :type '(choice
3636 (const :tag "The standard Emacs diary file" diary-file)
3637 (file :tag "Special Org file diary entries")))
3639 (eval-after-load "calendar"
3640 '(progn
3641 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3642 'org-calendar-goto-agenda)
3643 (add-hook 'calendar-mode-hook
3644 (lambda ()
3645 (unless (eq org-agenda-diary-file 'diary-file)
3646 (define-key calendar-mode-map
3647 org-calendar-insert-diary-entry-key
3648 'org-agenda-diary-entry))))))
3650 (defgroup org-latex nil
3651 "Options for embedding LaTeX code into Org-mode."
3652 :tag "Org LaTeX"
3653 :group 'org)
3655 (defcustom org-format-latex-options
3656 '(:foreground default :background default :scale 1.0
3657 :html-foreground "Black" :html-background "Transparent"
3658 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3659 "Options for creating images from LaTeX fragments.
3660 This is a property list with the following properties:
3661 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3662 `default' means use the foreground of the default face.
3663 `auto' means use the foreground from the text face.
3664 :background the background color, or \"Transparent\".
3665 `default' means use the background of the default face.
3666 `auto' means use the background from the text face.
3667 :scale a scaling factor for the size of the images, to get more pixels
3668 :html-foreground, :html-background, :html-scale
3669 the same numbers for HTML export.
3670 :matchers a list indicating which matchers should be used to
3671 find LaTeX fragments. Valid members of this list are:
3672 \"begin\" find environments
3673 \"$1\" find single characters surrounded by $.$
3674 \"$\" find math expressions surrounded by $...$
3675 \"$$\" find math expressions surrounded by $$....$$
3676 \"\\(\" find math expressions surrounded by \\(...\\)
3677 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3678 :group 'org-latex
3679 :type 'plist)
3681 (defcustom org-format-latex-signal-error t
3682 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3683 When nil, just push out a message."
3684 :group 'org-latex
3685 :version "24.1"
3686 :type 'boolean)
3688 (defcustom org-latex-to-mathml-jar-file nil
3689 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3690 Use this to specify additional executable file say a jar file.
3692 When using MathToWeb as the converter, specify the full-path to
3693 your mathtoweb.jar file."
3694 :group 'org-latex
3695 :version "24.1"
3696 :type '(choice
3697 (const :tag "None" nil)
3698 (file :tag "JAR file" :must-match t)))
3700 (defcustom org-latex-to-mathml-convert-command nil
3701 "Command to convert LaTeX fragments to MathML.
3702 Replace format-specifiers in the command as noted below and use
3703 `shell-command' to convert LaTeX to MathML.
3704 %j: Executable file in fully expanded form as specified by
3705 `org-latex-to-mathml-jar-file'.
3706 %I: Input LaTeX file in fully expanded form
3707 %o: Output MathML file
3708 This command is used by `org-create-math-formula'.
3710 When using MathToWeb as the converter, set this to
3711 \"java -jar %j -unicode -force -df %o %I\"."
3712 :group 'org-latex
3713 :version "24.1"
3714 :type '(choice
3715 (const :tag "None" nil)
3716 (string :tag "\nShell command")))
3718 (defcustom org-latex-create-formula-image-program 'dvipng
3719 "Program to convert LaTeX fragments with.
3721 dvipng Process the LaTeX fragments to dvi file, then convert
3722 dvi files to png files using dvipng.
3723 This will also include processing of non-math environments.
3724 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3725 to convert pdf files to png files"
3726 :group 'org-latex
3727 :version "24.1"
3728 :type '(choice
3729 (const :tag "dvipng" dvipng)
3730 (const :tag "imagemagick" imagemagick)))
3732 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3733 "Path to store latex preview images.
3734 A relative path here creates many directories relative to the
3735 processed org files paths. An absolute path puts all preview
3736 images at the same place."
3737 :group 'org-latex
3738 :version "24.3"
3739 :type 'string)
3741 (defun org-format-latex-mathml-available-p ()
3742 "Return t if `org-latex-to-mathml-convert-command' is usable."
3743 (save-match-data
3744 (when (and (boundp 'org-latex-to-mathml-convert-command)
3745 org-latex-to-mathml-convert-command)
3746 (let ((executable (car (split-string
3747 org-latex-to-mathml-convert-command))))
3748 (when (executable-find executable)
3749 (if (string-match
3750 "%j" org-latex-to-mathml-convert-command)
3751 (file-readable-p org-latex-to-mathml-jar-file)
3752 t))))))
3754 (defcustom org-format-latex-header "\\documentclass{article}
3755 \\usepackage[usenames]{color}
3756 \\usepackage{amsmath}
3757 \\usepackage[mathscr]{eucal}
3758 \\pagestyle{empty} % do not remove
3759 \[PACKAGES]
3760 \[DEFAULT-PACKAGES]
3761 % The settings below are copied from fullpage.sty
3762 \\setlength{\\textwidth}{\\paperwidth}
3763 \\addtolength{\\textwidth}{-3cm}
3764 \\setlength{\\oddsidemargin}{1.5cm}
3765 \\addtolength{\\oddsidemargin}{-2.54cm}
3766 \\setlength{\\evensidemargin}{\\oddsidemargin}
3767 \\setlength{\\textheight}{\\paperheight}
3768 \\addtolength{\\textheight}{-\\headheight}
3769 \\addtolength{\\textheight}{-\\headsep}
3770 \\addtolength{\\textheight}{-\\footskip}
3771 \\addtolength{\\textheight}{-3cm}
3772 \\setlength{\\topmargin}{1.5cm}
3773 \\addtolength{\\topmargin}{-2.54cm}"
3774 "The document header used for processing LaTeX fragments.
3775 It is imperative that this header make sure that no page number
3776 appears on the page. The package defined in the variables
3777 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3778 will either replace the placeholder \"[PACKAGES]\" in this
3779 header, or they will be appended."
3780 :group 'org-latex
3781 :type 'string)
3783 (defun org-set-packages-alist (var val)
3784 "Set the packages alist and make sure it has 3 elements per entry."
3785 (set var (mapcar (lambda (x)
3786 (if (and (consp x) (= (length x) 2))
3787 (list (car x) (nth 1 x) t)
3789 val)))
3791 (defun org-get-packages-alist (var)
3792 "Get the packages alist and make sure it has 3 elements per entry."
3793 (mapcar (lambda (x)
3794 (if (and (consp x) (= (length x) 2))
3795 (list (car x) (nth 1 x) t)
3797 (default-value var)))
3799 (defcustom org-latex-default-packages-alist
3800 '(("AUTO" "inputenc" t)
3801 ("T1" "fontenc" t)
3802 ("" "fixltx2e" nil)
3803 ("" "graphicx" t)
3804 ("" "longtable" nil)
3805 ("" "float" nil)
3806 ("" "wrapfig" nil)
3807 ("" "soul" t)
3808 ("" "textcomp" t)
3809 ("" "marvosym" t)
3810 ("" "wasysym" t)
3811 ("" "latexsym" t)
3812 ("" "amssymb" t)
3813 ("" "hyperref" nil)
3814 "\\tolerance=1000")
3815 "Alist of default packages to be inserted in the header.
3817 Change this only if one of the packages here causes an
3818 incompatibility with another package you are using.
3820 The packages in this list are needed by one part or another of
3821 Org mode to function properly:
3823 - inputenc, fontenc: for basic font and character selection
3824 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3825 symbols used for interpreting the entities in `org-entities'.
3826 You can skip some of these packages if you don't use any of the
3827 symbols in it.
3828 - graphicx: for including images
3829 - float, wrapfig: for figure placement
3830 - longtable: for long tables
3831 - hyperref: for cross references
3833 Therefore you should not modify this variable unless you know
3834 what you are doing. The one reason to change it anyway is that
3835 you might be loading some other package that conflicts with one
3836 of the default packages. Each cell is of the format
3837 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3838 the package also needs to be included when compiling LaTeX
3839 snippets into images for inclusion into non-LaTeX output."
3840 :group 'org-latex
3841 :group 'org-export-latex
3842 :set 'org-set-packages-alist
3843 :get 'org-get-packages-alist
3844 :version "24.1"
3845 :type '(repeat
3846 (choice
3847 (list :tag "options/package pair"
3848 (string :tag "options")
3849 (string :tag "package")
3850 (boolean :tag "Snippet"))
3851 (string :tag "A line of LaTeX"))))
3853 (defcustom org-latex-packages-alist nil
3854 "Alist of packages to be inserted in every LaTeX header.
3856 These will be inserted after `org-latex-default-packages-alist'.
3857 Each cell is of the format:
3859 \(\"options\" \"package\" snippet-flag)
3861 SNIPPET-FLAG, when t, indicates that this package is also needed
3862 when turning LaTeX snippets into images for inclusion into
3863 non-LaTeX output.
3865 Make sure that you only list packages here which:
3867 - you want in every file
3868 - do not conflict with the setup in `org-format-latex-header'.
3869 - do not conflict with the default packages in
3870 `org-latex-default-packages-alist'."
3871 :group 'org-latex
3872 :group 'org-export-latex
3873 :set 'org-set-packages-alist
3874 :get 'org-get-packages-alist
3875 :type '(repeat
3876 (choice
3877 (list :tag "options/package pair"
3878 (string :tag "options")
3879 (string :tag "package")
3880 (boolean :tag "Snippet"))
3881 (string :tag "A line of LaTeX"))))
3883 (defgroup org-appearance nil
3884 "Settings for Org-mode appearance."
3885 :tag "Org Appearance"
3886 :group 'org)
3888 (defcustom org-level-color-stars-only nil
3889 "Non-nil means fontify only the stars in each headline.
3890 When nil, the entire headline is fontified.
3891 Changing it requires restart of `font-lock-mode' to become effective
3892 also in regions already fontified."
3893 :group 'org-appearance
3894 :type 'boolean)
3896 (defcustom org-hide-leading-stars nil
3897 "Non-nil means hide the first N-1 stars in a headline.
3898 This works by using the face `org-hide' for these stars. This
3899 face is white for a light background, and black for a dark
3900 background. You may have to customize the face `org-hide' to
3901 make this work.
3902 Changing it requires restart of `font-lock-mode' to become effective
3903 also in regions already fontified.
3904 You may also set this on a per-file basis by adding one of the following
3905 lines to the buffer:
3907 #+STARTUP: hidestars
3908 #+STARTUP: showstars"
3909 :group 'org-appearance
3910 :type 'boolean)
3912 (defcustom org-hidden-keywords nil
3913 "List of symbols corresponding to keywords to be hidden the org buffer.
3914 For example, a value '(title) for this list will make the document's title
3915 appear in the buffer without the initial #+TITLE: keyword."
3916 :group 'org-appearance
3917 :version "24.1"
3918 :type '(set (const :tag "#+AUTHOR" author)
3919 (const :tag "#+DATE" date)
3920 (const :tag "#+EMAIL" email)
3921 (const :tag "#+TITLE" title)))
3923 (defcustom org-custom-properties nil
3924 "List of properties (as strings) with a special meaning.
3925 The default use of these custom properties is to let the user
3926 hide them with `org-toggle-custom-properties-visibility'."
3927 :group 'org-properties
3928 :group 'org-appearance
3929 :version "24.3"
3930 :type '(repeat (string :tag "Property Name")))
3932 (defcustom org-fontify-done-headline nil
3933 "Non-nil means change the face of a headline if it is marked DONE.
3934 Normally, only the TODO/DONE keyword indicates the state of a headline.
3935 When this is non-nil, the headline after the keyword is set to the
3936 `org-headline-done' as an additional indication."
3937 :group 'org-appearance
3938 :type 'boolean)
3940 (defcustom org-fontify-emphasized-text t
3941 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3942 Changing this variable requires a restart of Emacs to take effect."
3943 :group 'org-appearance
3944 :type 'boolean)
3946 (defcustom org-fontify-whole-heading-line nil
3947 "Non-nil means fontify the whole line for headings.
3948 This is useful when setting a background color for the
3949 org-level-* faces."
3950 :group 'org-appearance
3951 :type 'boolean)
3953 (defcustom org-highlight-latex-and-related nil
3954 "Non-nil means highlight LaTeX related syntax in the buffer.
3955 When non nil, the value should be a list containing any of the
3956 following symbols:
3957 `latex' Highlight LaTeX snippets and environments.
3958 `script' Highlight subscript and superscript.
3959 `entities' Highlight entities."
3960 :group 'org-appearance
3961 :version "24.4"
3962 :package-version '(Org . "8.0")
3963 :type '(choice
3964 (const :tag "No highlighting" nil)
3965 (set :greedy t :tag "Highlight"
3966 (const :tag "LaTeX snippets and environments" latex)
3967 (const :tag "Subscript and superscript" script)
3968 (const :tag "Entities" entities))))
3970 (defcustom org-hide-emphasis-markers nil
3971 "Non-nil mean font-lock should hide the emphasis marker characters."
3972 :group 'org-appearance
3973 :type 'boolean)
3975 (defcustom org-pretty-entities nil
3976 "Non-nil means show entities as UTF8 characters.
3977 When nil, the \\name form remains in the buffer."
3978 :group 'org-appearance
3979 :version "24.1"
3980 :type 'boolean)
3982 (defcustom org-pretty-entities-include-sub-superscripts t
3983 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3984 :group 'org-appearance
3985 :version "24.1"
3986 :type 'boolean)
3988 (defvar org-emph-re nil
3989 "Regular expression for matching emphasis.
3990 After a match, the match groups contain these elements:
3991 0 The match of the full regular expression, including the characters
3992 before and after the proper match
3993 1 The character before the proper match, or empty at beginning of line
3994 2 The proper match, including the leading and trailing markers
3995 3 The leading marker like * or /, indicating the type of highlighting
3996 4 The text between the emphasis markers, not including the markers
3997 5 The character after the match, empty at the end of a line")
3998 (defvar org-verbatim-re nil
3999 "Regular expression for matching verbatim text.")
4000 (defvar org-emphasis-regexp-components) ; defined just below
4001 (defvar org-emphasis-alist) ; defined just below
4002 (defun org-set-emph-re (var val)
4003 "Set variable and compute the emphasis regular expression."
4004 (set var val)
4005 (when (and (boundp 'org-emphasis-alist)
4006 (boundp 'org-emphasis-regexp-components)
4007 org-emphasis-alist org-emphasis-regexp-components)
4008 (let* ((e org-emphasis-regexp-components)
4009 (pre (car e))
4010 (post (nth 1 e))
4011 (border (nth 2 e))
4012 (body (nth 3 e))
4013 (nl (nth 4 e))
4014 (body1 (concat body "*?"))
4015 (markers (mapconcat 'car org-emphasis-alist ""))
4016 (vmarkers (mapconcat
4017 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4018 org-emphasis-alist "")))
4019 ;; make sure special characters appear at the right position in the class
4020 (if (string-match "\\^" markers)
4021 (setq markers (concat (replace-match "" t t markers) "^")))
4022 (if (string-match "-" markers)
4023 (setq markers (concat (replace-match "" t t markers) "-")))
4024 (if (string-match "\\^" vmarkers)
4025 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4026 (if (string-match "-" vmarkers)
4027 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4028 (if (> nl 0)
4029 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4030 (int-to-string nl) "\\}")))
4031 ;; Make the regexp
4032 (setq org-emph-re
4033 (concat "\\([" pre "]\\|^\\)"
4034 "\\("
4035 "\\([" markers "]\\)"
4036 "\\("
4037 "[^" border "]\\|"
4038 "[^" border "]"
4039 body1
4040 "[^" border "]"
4041 "\\)"
4042 "\\3\\)"
4043 "\\([" post "]\\|$\\)"))
4044 (setq org-verbatim-re
4045 (concat "\\([" pre "]\\|^\\)"
4046 "\\("
4047 "\\([" vmarkers "]\\)"
4048 "\\("
4049 "[^" border "]\\|"
4050 "[^" border "]"
4051 body1
4052 "[^" border "]"
4053 "\\)"
4054 "\\3\\)"
4055 "\\([" post "]\\|$\\)")))))
4057 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4058 ;; set this option proved cumbersome. See this message/thread:
4059 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4060 (defvar org-emphasis-regexp-components
4061 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4062 "Components used to build the regular expression for emphasis.
4063 This is a list with five entries. Terminology: In an emphasis string
4064 like \" *strong word* \", we call the initial space PREMATCH, the final
4065 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4066 and \"trong wor\" is the body. The different components in this variable
4067 specify what is allowed/forbidden in each part:
4069 pre Chars allowed as prematch. Beginning of line will be allowed too.
4070 post Chars allowed as postmatch. End of line will be allowed too.
4071 border The chars *forbidden* as border characters.
4072 body-regexp A regexp like \".\" to match a body character. Don't use
4073 non-shy groups here, and don't allow newline here.
4074 newline The maximum number of newlines allowed in an emphasis exp.
4076 You need to reload Org or to restart Emacs after customizing this.")
4078 (defcustom org-emphasis-alist
4079 `(("*" bold)
4080 ("/" italic)
4081 ("_" underline)
4082 ("=" org-code verbatim)
4083 ("~" org-verbatim verbatim)
4084 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4085 "Alist of characters and faces to emphasize text.
4086 Text starting and ending with a special character will be emphasized,
4087 for example *bold*, _underlined_ and /italic/. This variable sets the
4088 marker characters and the face to be used by font-lock for highlighting
4089 in Org-mode Emacs buffers.
4091 You need to reload Org or to restart Emacs after customizing this."
4092 :group 'org-appearance
4093 :set 'org-set-emph-re
4094 :version "24.4"
4095 :package-version '(Org . "8.0")
4096 :type '(repeat
4097 (list
4098 (string :tag "Marker character")
4099 (choice
4100 (face :tag "Font-lock-face")
4101 (plist :tag "Face property list"))
4102 (option (const verbatim)))))
4104 (defvar org-protecting-blocks
4105 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4106 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4107 This is needed for font-lock setup.")
4109 ;;; Miscellaneous options
4111 (defgroup org-completion nil
4112 "Completion in Org-mode."
4113 :tag "Org Completion"
4114 :group 'org)
4116 (defcustom org-completion-use-ido nil
4117 "Non-nil means use ido completion wherever possible.
4118 Note that `ido-mode' must be active for this variable to be relevant.
4119 If you decide to turn this variable on, you might well want to turn off
4120 `org-outline-path-complete-in-steps'.
4121 See also `org-completion-use-iswitchb'."
4122 :group 'org-completion
4123 :type 'boolean)
4125 (defcustom org-completion-use-iswitchb nil
4126 "Non-nil means use iswitchb completion wherever possible.
4127 Note that `iswitchb-mode' must be active for this variable to be relevant.
4128 If you decide to turn this variable on, you might well want to turn off
4129 `org-outline-path-complete-in-steps'.
4130 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4131 :group 'org-completion
4132 :type 'boolean)
4134 (defcustom org-completion-fallback-command 'hippie-expand
4135 "The expansion command called by \\[pcomplete] in normal context.
4136 Normal means, no org-mode-specific context."
4137 :group 'org-completion
4138 :type 'function)
4140 ;;; Functions and variables from their packages
4141 ;; Declared here to avoid compiler warnings
4143 ;; XEmacs only
4144 (defvar outline-mode-menu-heading)
4145 (defvar outline-mode-menu-show)
4146 (defvar outline-mode-menu-hide)
4147 (defvar zmacs-regions) ; XEmacs regions
4149 ;; Emacs only
4150 (defvar mark-active)
4152 ;; Various packages
4153 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4154 (declare-function calendar-forward-day "cal-move" (arg))
4155 (declare-function calendar-goto-date "cal-move" (date))
4156 (declare-function calendar-goto-today "cal-move" ())
4157 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4158 (defvar calc-embedded-close-formula)
4159 (defvar calc-embedded-open-formula)
4160 (declare-function cdlatex-tab "ext:cdlatex" ())
4161 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4162 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4163 (defvar font-lock-unfontify-region-function)
4164 (declare-function iswitchb-read-buffer "iswitchb"
4165 (prompt &optional default require-match start matches-set))
4166 (defvar iswitchb-temp-buflist)
4167 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4168 (defvar org-agenda-tags-todo-honor-ignore-options)
4169 (declare-function org-agenda-skip "org-agenda" ())
4170 (declare-function
4171 org-agenda-format-item "org-agenda"
4172 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4173 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4174 (declare-function org-agenda-change-all-lines "org-agenda"
4175 (newhead hdmarker &optional fixface just-this))
4176 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4177 (declare-function org-agenda-maybe-redo "org-agenda" ())
4178 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4179 (beg end))
4180 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4181 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4182 "org-agenda" (&optional end))
4183 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4184 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4185 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4186 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4187 (declare-function org-indent-mode "org-indent" (&optional arg))
4188 (declare-function parse-time-string "parse-time" (string))
4189 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4190 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4191 (defvar remember-data-file)
4192 (defvar texmathp-why)
4193 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4194 (declare-function table--at-cell-p "table" (position &optional object at-column))
4196 (defvar org-latex-regexps)
4198 ;;; Autoload and prepare some org modules
4200 ;; Some table stuff that needs to be defined here, because it is used
4201 ;; by the functions setting up org-mode or checking for table context.
4203 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4204 "Detect an org-type or table-type table.")
4205 (defconst org-table-line-regexp "^[ \t]*|"
4206 "Detect an org-type table line.")
4207 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4208 "Detect an org-type table line.")
4209 (defconst org-table-hline-regexp "^[ \t]*|-"
4210 "Detect an org-type table hline.")
4211 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4212 "Detect a table-type table hline.")
4213 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4214 "Detect the first line outside a table when searching from within it.
4215 This works for both table types.")
4217 ;; Autoload the functions in org-table.el that are needed by functions here.
4219 (eval-and-compile
4220 (org-autoload "org-table"
4221 '(org-table-begin org-table-blank-field org-table-end)))
4223 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4224 "Detect a #+TBLFM line.")
4226 ;;;###autoload
4227 (defun turn-on-orgtbl ()
4228 "Unconditionally turn on `orgtbl-mode'."
4229 (require 'org-table)
4230 (orgtbl-mode 1))
4232 (defun org-at-table-p (&optional table-type)
4233 "Return t if the cursor is inside an org-type table.
4234 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4235 (if org-enable-table-editor
4236 (save-excursion
4237 (beginning-of-line 1)
4238 (looking-at (if table-type org-table-any-line-regexp
4239 org-table-line-regexp)))
4240 nil))
4241 (defsubst org-table-p () (org-at-table-p))
4243 (defun org-at-table.el-p ()
4244 "Return t if and only if we are at a table.el table."
4245 (and (org-at-table-p 'any)
4246 (save-excursion
4247 (goto-char (org-table-begin 'any))
4248 (looking-at org-table1-hline-regexp))))
4250 (defun org-table-recognize-table.el ()
4251 "If there is a table.el table nearby, recognize it and move into it."
4252 (if org-table-tab-recognizes-table.el
4253 (if (org-at-table.el-p)
4254 (progn
4255 (beginning-of-line 1)
4256 (if (looking-at org-table-dataline-regexp)
4258 (if (looking-at org-table1-hline-regexp)
4259 (progn
4260 (beginning-of-line 2)
4261 (if (looking-at org-table-any-border-regexp)
4262 (beginning-of-line -1)))))
4263 (if (re-search-forward "|" (org-table-end t) t)
4264 (progn
4265 (require 'table)
4266 (if (table--at-cell-p (point))
4268 (message "recognizing table.el table...")
4269 (table-recognize-table)
4270 (message "recognizing table.el table...done")))
4271 (error "This should not happen"))
4273 nil)
4274 nil))
4276 (defun org-at-table-hline-p ()
4277 "Return t if the cursor is inside a hline in a table."
4278 (if org-enable-table-editor
4279 (save-excursion
4280 (beginning-of-line 1)
4281 (looking-at org-table-hline-regexp))
4282 nil))
4284 (defvar org-table-clean-did-remove-column nil)
4285 (defun org-table-map-tables (function &optional quietly)
4286 "Apply FUNCTION to the start of all tables in the buffer."
4287 (save-excursion
4288 (save-restriction
4289 (widen)
4290 (goto-char (point-min))
4291 (while (re-search-forward org-table-any-line-regexp nil t)
4292 (unless quietly
4293 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4294 (beginning-of-line 1)
4295 (when (and (looking-at org-table-line-regexp)
4296 ;; Exclude tables in src/example/verbatim/clocktable blocks
4297 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4298 (save-excursion (funcall function))
4299 (or (looking-at org-table-line-regexp)
4300 (forward-char 1)))
4301 (re-search-forward org-table-any-border-regexp nil 1))))
4302 (unless quietly (message "Mapping tables: done")))
4304 ;; Declare and autoload functions from ox.el and al.
4306 (declare-function org-export-get-environment "ox"
4307 (&optional backend subtreep ext-plist))
4308 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4310 ;; Declare and autoload functions from org-agenda.el
4312 (eval-and-compile
4313 (org-autoload "org-agenda"
4314 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4316 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4317 (declare-function org-clock-update-mode-line "org-clock" ())
4318 (declare-function org-resolve-clocks "org-clock"
4319 (&optional also-non-dangling-p prompt last-valid))
4321 (defun org-at-TBLFM-p (&optional pos)
4322 "Return t when point (or POS) is in #+TBLFM line."
4323 (save-excursion
4324 (let ((pos pos)))
4325 (goto-char (or pos (point)))
4326 (beginning-of-line 1)
4327 (looking-at org-TBLFM-regexp)))
4329 (defvar org-clock-start-time)
4330 (defvar org-clock-marker (make-marker)
4331 "Marker recording the last clock-in.")
4332 (defvar org-clock-hd-marker (make-marker)
4333 "Marker recording the last clock-in, but the headline position.")
4334 (defvar org-clock-heading ""
4335 "The heading of the current clock entry.")
4336 (defun org-clock-is-active ()
4337 "Return non-nil if clock is currently running.
4338 The return value is actually the clock marker."
4339 (marker-buffer org-clock-marker))
4341 (eval-and-compile
4342 (org-autoload "org-clock" '(org-clock-remove-overlays
4343 org-clock-update-time-maybe
4344 org-clocktable-shift)))
4346 (defun org-check-running-clock ()
4347 "Check if the current buffer contains the running clock.
4348 If yes, offer to stop it and to save the buffer with the changes."
4349 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4350 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4351 (buffer-name))))
4352 (org-clock-out)
4353 (when (y-or-n-p "Save changed buffer?")
4354 (save-buffer))))
4356 (defun org-clocktable-try-shift (dir n)
4357 "Check if this line starts a clock table, if yes, shift the time block."
4358 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4359 (org-clocktable-shift dir n)))
4361 ;;;###autoload
4362 (defun org-clock-persistence-insinuate ()
4363 "Set up hooks for clock persistence."
4364 (require 'org-clock)
4365 (add-hook 'org-mode-hook 'org-clock-load)
4366 (add-hook 'kill-emacs-hook 'org-clock-save))
4368 ;; Define the variable already here, to make sure we have it.
4369 (defvar org-indent-mode nil
4370 "Non-nil if Org-Indent mode is enabled.
4371 Use the command `org-indent-mode' to change this variable.")
4373 ;; Autoload archiving code
4374 ;; The stuff that is needed for cycling and tags has to be defined here.
4376 (defgroup org-archive nil
4377 "Options concerning archiving in Org-mode."
4378 :tag "Org Archive"
4379 :group 'org-structure)
4381 (defcustom org-archive-location "%s_archive::"
4382 "The location where subtrees should be archived.
4384 The value of this variable is a string, consisting of two parts,
4385 separated by a double-colon. The first part is a filename and
4386 the second part is a headline.
4388 When the filename is omitted, archiving happens in the same file.
4389 %s in the filename will be replaced by the current file
4390 name (without the directory part). Archiving to a different file
4391 is useful to keep archived entries from contributing to the
4392 Org-mode Agenda.
4394 The archived entries will be filed as subtrees of the specified
4395 headline. When the headline is omitted, the subtrees are simply
4396 filed away at the end of the file, as top-level entries. Also in
4397 the heading you can use %s to represent the file name, this can be
4398 useful when using the same archive for a number of different files.
4400 Here are a few examples:
4401 \"%s_archive::\"
4402 If the current file is Projects.org, archive in file
4403 Projects.org_archive, as top-level trees. This is the default.
4405 \"::* Archived Tasks\"
4406 Archive in the current file, under the top-level headline
4407 \"* Archived Tasks\".
4409 \"~/org/archive.org::\"
4410 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4412 \"~/org/archive.org::* From %s\"
4413 Archive in file ~/org/archive.org (absolute path), under headlines
4414 \"From FILENAME\" where file name is the current file name.
4416 \"~/org/datetree.org::datetree/* Finished Tasks\"
4417 The \"datetree/\" string is special, signifying to archive
4418 items to the datetree. Items are placed in either the CLOSED
4419 date of the item, or the current date if there is no CLOSED date.
4420 The heading will be a subentry to the current date. There doesn't
4421 need to be a heading, but there always needs to be a slash after
4422 datetree. For example, to store archived items directly in the
4423 datetree, use \"~/org/datetree.org::datetree/\".
4425 \"basement::** Finished Tasks\"
4426 Archive in file ./basement (relative path), as level 3 trees
4427 below the level 2 heading \"** Finished Tasks\".
4429 You may set this option on a per-file basis by adding to the buffer a
4430 line like
4432 #+ARCHIVE: basement::** Finished Tasks
4434 You may also define it locally for a subtree by setting an ARCHIVE property
4435 in the entry. If such a property is found in an entry, or anywhere up
4436 the hierarchy, it will be used."
4437 :group 'org-archive
4438 :type 'string)
4440 (defcustom org-archive-tag "ARCHIVE"
4441 "The tag that marks a subtree as archived.
4442 An archived subtree does not open during visibility cycling, and does
4443 not contribute to the agenda listings.
4444 After changing this, font-lock must be restarted in the relevant buffers to
4445 get the proper fontification."
4446 :group 'org-archive
4447 :group 'org-keywords
4448 :type 'string)
4450 (defcustom org-agenda-skip-archived-trees t
4451 "Non-nil means the agenda will skip any items located in archived trees.
4452 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4453 variable is no longer recommended, you should leave it at the value t.
4454 Instead, use the key `v' to cycle the archives-mode in the agenda."
4455 :group 'org-archive
4456 :group 'org-agenda-skip
4457 :type 'boolean)
4459 (defcustom org-columns-skip-archived-trees t
4460 "Non-nil means ignore archived trees when creating column view."
4461 :group 'org-archive
4462 :group 'org-properties
4463 :type 'boolean)
4465 (defcustom org-cycle-open-archived-trees nil
4466 "Non-nil means `org-cycle' will open archived trees.
4467 An archived tree is a tree marked with the tag ARCHIVE.
4468 When nil, archived trees will stay folded. You can still open them with
4469 normal outline commands like `show-all', but not with the cycling commands."
4470 :group 'org-archive
4471 :group 'org-cycle
4472 :type 'boolean)
4474 (defcustom org-sparse-tree-open-archived-trees nil
4475 "Non-nil means sparse tree construction shows matches in archived trees.
4476 When nil, matches in these trees are highlighted, but the trees are kept in
4477 collapsed state."
4478 :group 'org-archive
4479 :group 'org-sparse-trees
4480 :type 'boolean)
4482 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4483 "The default date type when building a sparse tree.
4484 When this is nil, a date is a scheduled or a deadline timestamp.
4485 Otherwise, these types are allowed:
4487 all: all timestamps
4488 active: only active timestamps (<...>)
4489 inactive: only inactive timestamps (<...)
4490 scheduled: only scheduled timestamps
4491 deadline: only deadline timestamps"
4492 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4493 (const :tag "All timestamps" all)
4494 (const :tag "Only active timestamps" active)
4495 (const :tag "Only inactive timestamps" inactive)
4496 (const :tag "Only scheduled timestamps" scheduled)
4497 (const :tag "Only deadline timestamps" deadline)
4498 (const :tag "Only closed timestamps" closed))
4499 :version "24.3"
4500 :group 'org-sparse-trees)
4502 (defun org-cycle-hide-archived-subtrees (state)
4503 "Re-hide all archived subtrees after a visibility state change."
4504 (when (and (not org-cycle-open-archived-trees)
4505 (not (memq state '(overview folded))))
4506 (save-excursion
4507 (let* ((globalp (memq state '(contents all)))
4508 (beg (if globalp (point-min) (point)))
4509 (end (if globalp (point-max) (org-end-of-subtree t))))
4510 (org-hide-archived-subtrees beg end)
4511 (goto-char beg)
4512 (if (looking-at (concat ".*:" org-archive-tag ":"))
4513 (message "%s" (substitute-command-keys
4514 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4516 (defun org-force-cycle-archived ()
4517 "Cycle subtree even if it is archived."
4518 (interactive)
4519 (setq this-command 'org-cycle)
4520 (let ((org-cycle-open-archived-trees t))
4521 (call-interactively 'org-cycle)))
4523 (defun org-hide-archived-subtrees (beg end)
4524 "Re-hide all archived subtrees after a visibility state change."
4525 (save-excursion
4526 (let* ((re (concat ":" org-archive-tag ":")))
4527 (goto-char beg)
4528 (while (re-search-forward re end t)
4529 (when (org-at-heading-p)
4530 (org-flag-subtree t)
4531 (org-end-of-subtree t))))))
4533 (declare-function outline-end-of-heading "outline" ())
4534 (declare-function outline-flag-region "outline" (from to flag))
4535 (defun org-flag-subtree (flag)
4536 (save-excursion
4537 (org-back-to-heading t)
4538 (outline-end-of-heading)
4539 (outline-flag-region (point)
4540 (progn (org-end-of-subtree t) (point))
4541 flag)))
4543 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4545 (eval-and-compile
4546 (org-autoload "org-archive"
4547 '(org-add-archive-files)))
4549 ;; Autoload Column View Code
4551 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4552 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4553 (declare-function org-columns-compute "org-colview" (property))
4555 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4556 '(org-columns-number-to-string
4557 org-columns-get-format-and-top-level
4558 org-columns-compute
4559 org-columns-remove-overlays))
4561 ;; Autoload ID code
4563 (declare-function org-id-store-link "org-id")
4564 (declare-function org-id-locations-load "org-id")
4565 (declare-function org-id-locations-save "org-id")
4566 (defvar org-id-track-globally)
4567 (org-autoload "org-id"
4568 '(org-id-new
4569 org-id-copy
4570 org-id-get-with-outline-path-completion
4571 org-id-get-with-outline-drilling))
4573 ;;; Variables for pre-computed regular expressions, all buffer local
4575 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4576 "Matches first line of a hidden block.")
4577 (make-variable-buffer-local 'org-drawer-regexp)
4578 (defvar org-todo-regexp nil
4579 "Matches any of the TODO state keywords.")
4580 (make-variable-buffer-local 'org-todo-regexp)
4581 (defvar org-not-done-regexp nil
4582 "Matches any of the TODO state keywords except the last one.")
4583 (make-variable-buffer-local 'org-not-done-regexp)
4584 (defvar org-not-done-heading-regexp nil
4585 "Matches a TODO headline that is not done.")
4586 (make-variable-buffer-local 'org-not-done-regexp)
4587 (defvar org-todo-line-regexp nil
4588 "Matches a headline and puts TODO state into group 2 if present.")
4589 (make-variable-buffer-local 'org-todo-line-regexp)
4590 (defvar org-complex-heading-regexp nil
4591 "Matches a headline and puts everything into groups:
4592 group 1: the stars
4593 group 2: The todo keyword, maybe
4594 group 3: Priority cookie
4595 group 4: True headline
4596 group 5: Tags")
4597 (make-variable-buffer-local 'org-complex-heading-regexp)
4598 (defvar org-complex-heading-regexp-format nil
4599 "Printf format to make regexp to match an exact headline.
4600 This regexp will match the headline of any node which has the
4601 exact headline text that is put into the format, but may have any
4602 TODO state, priority and tags.")
4603 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4604 (defvar org-todo-line-tags-regexp nil
4605 "Matches a headline and puts TODO state into group 2 if present.
4606 Also put tags into group 4 if tags are present.")
4607 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4608 (defvar org-ds-keyword-length 12
4609 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4610 (make-variable-buffer-local 'org-ds-keyword-length)
4611 (defvar org-deadline-regexp nil
4612 "Matches the DEADLINE keyword.")
4613 (make-variable-buffer-local 'org-deadline-regexp)
4614 (defvar org-deadline-time-regexp nil
4615 "Matches the DEADLINE keyword together with a time stamp.")
4616 (make-variable-buffer-local 'org-deadline-time-regexp)
4617 (defvar org-deadline-time-hour-regexp nil
4618 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4619 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4620 (defvar org-deadline-line-regexp nil
4621 "Matches the DEADLINE keyword and the rest of the line.")
4622 (make-variable-buffer-local 'org-deadline-line-regexp)
4623 (defvar org-scheduled-regexp nil
4624 "Matches the SCHEDULED keyword.")
4625 (make-variable-buffer-local 'org-scheduled-regexp)
4626 (defvar org-scheduled-time-regexp nil
4627 "Matches the SCHEDULED keyword together with a time stamp.")
4628 (make-variable-buffer-local 'org-scheduled-time-regexp)
4629 (defvar org-scheduled-time-hour-regexp nil
4630 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4631 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4632 (defvar org-closed-time-regexp nil
4633 "Matches the CLOSED keyword together with a time stamp.")
4634 (make-variable-buffer-local 'org-closed-time-regexp)
4636 (defvar org-keyword-time-regexp nil
4637 "Matches any of the 4 keywords, together with the time stamp.")
4638 (make-variable-buffer-local 'org-keyword-time-regexp)
4639 (defvar org-keyword-time-not-clock-regexp nil
4640 "Matches any of the 3 keywords, together with the time stamp.")
4641 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4642 (defvar org-maybe-keyword-time-regexp nil
4643 "Matches a timestamp, possibly preceded by a keyword.")
4644 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4645 (defvar org-all-time-keywords nil
4646 "List of time keywords.")
4647 (make-variable-buffer-local 'org-all-time-keywords)
4649 (defconst org-plain-time-of-day-regexp
4650 (concat
4651 "\\(\\<[012]?[0-9]"
4652 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4653 "\\(--?"
4654 "\\(\\<[012]?[0-9]"
4655 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4656 "\\)?")
4657 "Regular expression to match a plain time or time range.
4658 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4659 groups carry important information:
4660 0 the full match
4661 1 the first time, range or not
4662 8 the second time, if it is a range.")
4664 (defconst org-plain-time-extension-regexp
4665 (concat
4666 "\\(\\<[012]?[0-9]"
4667 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4668 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4669 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4670 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4671 groups carry important information:
4672 0 the full match
4673 7 hours of duration
4674 9 minutes of duration")
4676 (defconst org-stamp-time-of-day-regexp
4677 (concat
4678 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4679 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4680 "\\(--?"
4681 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4682 "Regular expression to match a timestamp time or time range.
4683 After a match, the following groups carry important information:
4684 0 the full match
4685 1 date plus weekday, for back referencing to make sure both times are on the same day
4686 2 the first time, range or not
4687 4 the second time, if it is a range.")
4689 (defconst org-startup-options
4690 '(("fold" org-startup-folded t)
4691 ("overview" org-startup-folded t)
4692 ("nofold" org-startup-folded nil)
4693 ("showall" org-startup-folded nil)
4694 ("showeverything" org-startup-folded showeverything)
4695 ("content" org-startup-folded content)
4696 ("indent" org-startup-indented t)
4697 ("noindent" org-startup-indented nil)
4698 ("hidestars" org-hide-leading-stars t)
4699 ("showstars" org-hide-leading-stars nil)
4700 ("odd" org-odd-levels-only t)
4701 ("oddeven" org-odd-levels-only nil)
4702 ("align" org-startup-align-all-tables t)
4703 ("noalign" org-startup-align-all-tables nil)
4704 ("inlineimages" org-startup-with-inline-images t)
4705 ("noinlineimages" org-startup-with-inline-images nil)
4706 ("latexpreview" org-startup-with-latex-preview t)
4707 ("nolatexpreview" org-startup-with-latex-preview nil)
4708 ("customtime" org-display-custom-times t)
4709 ("logdone" org-log-done time)
4710 ("lognotedone" org-log-done note)
4711 ("nologdone" org-log-done nil)
4712 ("lognoteclock-out" org-log-note-clock-out t)
4713 ("nolognoteclock-out" org-log-note-clock-out nil)
4714 ("logrepeat" org-log-repeat state)
4715 ("lognoterepeat" org-log-repeat note)
4716 ("logdrawer" org-log-into-drawer t)
4717 ("nologdrawer" org-log-into-drawer nil)
4718 ("logstatesreversed" org-log-states-order-reversed t)
4719 ("nologstatesreversed" org-log-states-order-reversed nil)
4720 ("nologrepeat" org-log-repeat nil)
4721 ("logreschedule" org-log-reschedule time)
4722 ("lognotereschedule" org-log-reschedule note)
4723 ("nologreschedule" org-log-reschedule nil)
4724 ("logredeadline" org-log-redeadline time)
4725 ("lognoteredeadline" org-log-redeadline note)
4726 ("nologredeadline" org-log-redeadline nil)
4727 ("logrefile" org-log-refile time)
4728 ("lognoterefile" org-log-refile note)
4729 ("nologrefile" org-log-refile nil)
4730 ("fninline" org-footnote-define-inline t)
4731 ("nofninline" org-footnote-define-inline nil)
4732 ("fnlocal" org-footnote-section nil)
4733 ("fnauto" org-footnote-auto-label t)
4734 ("fnprompt" org-footnote-auto-label nil)
4735 ("fnconfirm" org-footnote-auto-label confirm)
4736 ("fnplain" org-footnote-auto-label plain)
4737 ("fnadjust" org-footnote-auto-adjust t)
4738 ("nofnadjust" org-footnote-auto-adjust nil)
4739 ("constcgs" constants-unit-system cgs)
4740 ("constSI" constants-unit-system SI)
4741 ("noptag" org-tag-persistent-alist nil)
4742 ("hideblocks" org-hide-block-startup t)
4743 ("nohideblocks" org-hide-block-startup nil)
4744 ("beamer" org-startup-with-beamer-mode t)
4745 ("entitiespretty" org-pretty-entities t)
4746 ("entitiesplain" org-pretty-entities nil))
4747 "Variable associated with STARTUP options for org-mode.
4748 Each element is a list of three items: the startup options (as written
4749 in the #+STARTUP line), the corresponding variable, and the value to set
4750 this variable to if the option is found. An optional forth element PUSH
4751 means to push this value onto the list in the variable.")
4753 (defun org-update-property-plist (key val props)
4754 "Update PROPS with KEY and VAL."
4755 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4756 (key (if appending (substring key 0 (- (length key) 1)) key))
4757 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4758 (previous (cdr (assoc key props))))
4759 (if appending
4760 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4761 (cons (cons key val) remainder))))
4763 (defconst org-block-regexp
4764 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4765 "Regular expression for hiding blocks.")
4766 (defconst org-heading-keyword-regexp-format
4767 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4768 "Printf format for a regexp matching a headline with some keyword.
4769 This regexp will match the headline of any node which has the
4770 exact keyword that is put into the format. The keyword isn't in
4771 any group by default, but the stars and the body are.")
4772 (defconst org-heading-keyword-maybe-regexp-format
4773 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4774 "Printf format for a regexp matching a headline, possibly with some keyword.
4775 This regexp can match any headline with the specified keyword, or
4776 without a keyword. The keyword isn't in any group by default,
4777 but the stars and the body are.")
4779 (defcustom org-group-tags t
4780 "When non-nil (the default), use group tags.
4781 This can be turned on/off through `org-toggle-tags-groups'."
4782 :group 'org-tags
4783 :group 'org-startup
4784 :type 'boolean)
4786 (defun org-toggle-tags-groups ()
4787 "Toggle support for group tags.
4788 Support for group tags is controlled by the option
4789 `org-group-tags', which is non-nil by default."
4790 (interactive)
4791 (setq org-group-tags (not org-group-tags))
4792 (cond ((and (derived-mode-p 'org-agenda-mode)
4793 org-group-tags)
4794 (org-agenda-redo))
4795 ((derived-mode-p 'org-mode)
4796 (let ((org-inhibit-startup t)) (org-mode))))
4797 (message "Groups tags support has been turned %s"
4798 (if org-group-tags "on" "off")))
4800 (defun org-set-regexps-and-options-for-tags ()
4801 "Precompute regular expressions used for tags in the current buffer."
4802 (when (derived-mode-p 'org-mode)
4803 (org-set-local 'org-file-tags nil)
4804 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4805 (splitre "[ \t]+")
4806 (start 0)
4807 tags ftags key value)
4808 (save-excursion
4809 (save-restriction
4810 (widen)
4811 (goto-char (point-min))
4812 (while (re-search-forward re nil t)
4813 (setq key (upcase (org-match-string-no-properties 1))
4814 value (org-match-string-no-properties 2))
4815 (if (stringp value) (setq value (org-trim value)))
4816 (cond
4817 ((equal key "TAGS")
4818 (setq tags (append tags (if tags '("\\n") nil)
4819 (org-split-string value splitre))))
4820 ((equal key "FILETAGS")
4821 (when (string-match "\\S-" value)
4822 (setq ftags
4823 (append
4824 ftags
4825 (apply 'append
4826 (mapcar (lambda (x) (org-split-string x ":"))
4827 (org-split-string value)))))))))))
4828 ;; Process the file tags.
4829 (and ftags (org-set-local 'org-file-tags
4830 (mapcar 'org-add-prop-inherited ftags)))
4831 (org-set-local 'org-tag-groups-alist nil)
4832 ;; Process the tags.
4833 ;; FIXME
4834 (when tags
4835 (let (e tgs g)
4836 (while (setq e (pop tags))
4837 (cond
4838 ((equal e "{")
4839 (progn (push '(:startgroup) tgs)
4840 (when (equal (nth 1 tags) ":")
4841 (push (list (replace-regexp-in-string
4842 "(.+)$" "" (nth 0 tags)))
4843 org-tag-groups-alist)
4844 (setq g 0))))
4845 ((equal e ":") (push '(:grouptags) tgs))
4846 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4847 ((equal e "\\n") (push '(:newline) tgs))
4848 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4849 (push (cons (match-string 1 e)
4850 (string-to-char (match-string 2 e))) tgs)
4851 (if (and g (> g 0))
4852 (setcar org-tag-groups-alist
4853 (append (car org-tag-groups-alist)
4854 (list (match-string 1 e)))))
4855 (if g (setq g (1+ g))))
4856 (t (push (list e) tgs)
4857 (if (and g (> g 0))
4858 (setcar org-tag-groups-alist
4859 (append (car org-tag-groups-alist) (list e))))
4860 (if g (setq g (1+ g))))))
4861 (org-set-local 'org-tag-alist nil)
4862 (while (setq e (pop tgs))
4863 (or (and (stringp (car e))
4864 (assoc (car e) org-tag-alist))
4865 (push e org-tag-alist))))))))
4867 (defun org-set-regexps-and-options ()
4868 "Precompute regular expressions used in the current buffer."
4869 (when (derived-mode-p 'org-mode)
4870 (org-set-local 'org-todo-kwd-alist nil)
4871 (org-set-local 'org-todo-key-alist nil)
4872 (org-set-local 'org-todo-key-trigger nil)
4873 (org-set-local 'org-todo-keywords-1 nil)
4874 (org-set-local 'org-done-keywords nil)
4875 (org-set-local 'org-todo-heads nil)
4876 (org-set-local 'org-todo-sets nil)
4877 (org-set-local 'org-todo-log-states nil)
4878 (org-set-local 'org-file-properties nil)
4879 (let ((re (org-make-options-regexp
4880 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4881 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4882 "SETUPFILE" "OPTIONS")
4883 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4884 (splitre "[ \t]+")
4885 (scripts org-use-sub-superscripts)
4886 kwds kws0 kwsa key log value cat arch const links hw dws
4887 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4888 (start 0))
4889 (save-excursion
4890 (save-restriction
4891 (widen)
4892 (goto-char (point-min))
4893 (while (or (and ext-setup-or-nil
4894 (let (ret)
4895 (with-temp-buffer
4896 (insert ext-setup-or-nil)
4897 (let ((major-mode 'org-mode))
4898 (org-set-regexps-and-options-for-tags)
4899 (setq ret (list org-file-tags org-tag-alist
4900 org-tag-groups-alist))))
4901 (setq org-file-tags (nth 0 ret)
4902 org-tag-alist (nth 1 ret)
4903 org-tag-groups-alist (nth 2 ret))))
4904 (and ext-setup-or-nil
4905 (string-match re ext-setup-or-nil start)
4906 (setq start (match-end 0)))
4907 (and (setq ext-setup-or-nil nil start 0)
4908 (re-search-forward re nil t)))
4909 (setq key (upcase (match-string 1 ext-setup-or-nil))
4910 value (org-match-string-no-properties 2 ext-setup-or-nil))
4911 (if (stringp value) (setq value (org-trim value)))
4912 (cond
4913 ((equal key "CATEGORY")
4914 (setq cat value))
4915 ((member key '("SEQ_TODO" "TODO"))
4916 (push (cons 'sequence (org-split-string value splitre)) kwds))
4917 ((equal key "TYP_TODO")
4918 (push (cons 'type (org-split-string value splitre)) kwds))
4919 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4920 ;; general TODO-like setup
4921 (push (cons (intern (downcase (match-string 1 key)))
4922 (org-split-string value splitre)) kwds))
4923 ((equal key "COLUMNS")
4924 (org-set-local 'org-columns-default-format value))
4925 ((equal key "LINK")
4926 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4927 (push (cons (match-string 1 value)
4928 (org-trim (match-string 2 value)))
4929 links)))
4930 ((equal key "PRIORITIES")
4931 (setq prio (org-split-string value " +")))
4932 ((equal key "PROPERTY")
4933 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4934 (setq props (org-update-property-plist (match-string 1 value)
4935 (match-string 2 value)
4936 props))))
4937 ((equal key "DRAWERS")
4938 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4939 ((equal key "CONSTANTS")
4940 (org-table-set-constants))
4941 ((equal key "STARTUP")
4942 (let ((opts (org-split-string value splitre))
4943 l var val)
4944 (while (setq l (pop opts))
4945 (when (setq l (assoc l org-startup-options))
4946 (setq var (nth 1 l) val (nth 2 l))
4947 (if (not (nth 3 l))
4948 (set (make-local-variable var) val)
4949 (if (not (listp (symbol-value var)))
4950 (set (make-local-variable var) nil))
4951 (set (make-local-variable var) (symbol-value var))
4952 (add-to-list var val))))))
4953 ((equal key "ARCHIVE")
4954 (setq arch value)
4955 (remove-text-properties 0 (length arch)
4956 '(face t fontified t) arch))
4957 ((equal key "OPTIONS")
4958 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4959 (setq scripts (read (match-string 2 value)))))
4960 ((and (equal key "SETUPFILE")
4961 ;; Prevent checking in Gnus messages
4962 (not buffer-read-only))
4963 (setq setup-contents (org-file-contents
4964 (expand-file-name
4965 (org-remove-double-quotes value))
4966 'noerror))
4967 (if (not ext-setup-or-nil)
4968 (setq ext-setup-or-nil setup-contents start 0)
4969 (setq ext-setup-or-nil
4970 (concat (substring ext-setup-or-nil 0 start)
4971 "\n" setup-contents "\n"
4972 (substring ext-setup-or-nil start)))))))
4973 ;; search for property blocks
4974 (goto-char (point-min))
4975 (while (re-search-forward org-block-regexp nil t)
4976 (when (equal "PROPERTY" (upcase (match-string 1)))
4977 (setq value (replace-regexp-in-string
4978 "[\n\r]" " " (match-string 4)))
4979 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4980 (setq props (org-update-property-plist (match-string 1 value)
4981 (match-string 2 value)
4982 props)))))))
4983 (org-set-local 'org-use-sub-superscripts scripts)
4984 (when cat
4985 (org-set-local 'org-category (intern cat))
4986 (push (cons "CATEGORY" cat) props))
4987 (when prio
4988 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4989 (setq prio (mapcar 'string-to-char prio))
4990 (org-set-local 'org-highest-priority (nth 0 prio))
4991 (org-set-local 'org-lowest-priority (nth 1 prio))
4992 (org-set-local 'org-default-priority (nth 2 prio)))
4993 (and props (org-set-local 'org-file-properties (nreverse props)))
4994 (and drawers (org-set-local 'org-drawers drawers))
4995 (and arch (org-set-local 'org-archive-location arch))
4996 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4997 ;; Process the TODO keywords
4998 (unless kwds
4999 ;; Use the global values as if they had been given locally.
5000 (setq kwds (default-value 'org-todo-keywords))
5001 (if (stringp (car kwds))
5002 (setq kwds (list (cons org-todo-interpretation
5003 (default-value 'org-todo-keywords)))))
5004 (setq kwds (reverse kwds)))
5005 (setq kwds (nreverse kwds))
5006 (let (inter kws kw)
5007 (while (setq kws (pop kwds))
5008 (let ((kws (or
5009 (run-hook-with-args-until-success
5010 'org-todo-setup-filter-hook kws)
5011 kws)))
5012 (setq inter (pop kws) sep (member "|" kws)
5013 kws0 (delete "|" (copy-sequence kws))
5014 kwsa nil
5015 kws1 (mapcar
5016 (lambda (x)
5017 ;; 1 2
5018 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5019 (progn
5020 (setq kw (match-string 1 x)
5021 key (and (match-end 2) (match-string 2 x))
5022 log (org-extract-log-state-settings x))
5023 (push (cons kw (and key (string-to-char key))) kwsa)
5024 (and log (push log org-todo-log-states))
5026 (error "Invalid TODO keyword %s" x)))
5027 kws0)
5028 kwsa (if kwsa (append '((:startgroup))
5029 (nreverse kwsa)
5030 '((:endgroup))))
5031 hw (car kws1)
5032 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5033 tail (list inter hw (car dws) (org-last dws))))
5034 (add-to-list 'org-todo-heads hw 'append)
5035 (push kws1 org-todo-sets)
5036 (setq org-done-keywords (append org-done-keywords dws nil))
5037 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5038 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5039 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5040 (setq org-todo-sets (nreverse org-todo-sets)
5041 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5042 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5043 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5044 ;; Compute the regular expressions and other local variables.
5045 ;; Using `org-outline-regexp-bol' would complicate them much,
5046 ;; because of the fixed white space at the end of that string.
5047 (if (not org-done-keywords)
5048 (setq org-done-keywords (and org-todo-keywords-1
5049 (list (org-last org-todo-keywords-1)))))
5050 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5051 (length org-scheduled-string)
5052 (length org-clock-string)
5053 (length org-closed-string)))
5054 org-drawer-regexp
5055 (concat "^[ \t]*:\\("
5056 (mapconcat 'regexp-quote org-drawers "\\|")
5057 "\\):[ \t]*$")
5058 org-not-done-keywords
5059 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5060 org-todo-regexp
5061 (concat "\\("
5062 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5063 "\\)")
5064 org-not-done-regexp
5065 (concat "\\("
5066 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5067 "\\)")
5068 org-not-done-heading-regexp
5069 (format org-heading-keyword-regexp-format org-not-done-regexp)
5070 org-todo-line-regexp
5071 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5072 org-complex-heading-regexp
5073 (concat "^\\(\\*+\\)"
5074 "\\(?: +" org-todo-regexp "\\)?"
5075 "\\(?: +\\(\\[#.\\]\\)\\)?"
5076 "\\(?: +\\(.*?\\)\\)??"
5077 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5078 "[ \t]*$")
5079 org-complex-heading-regexp-format
5080 (concat "^\\(\\*+\\)"
5081 "\\(?: +" org-todo-regexp "\\)?"
5082 "\\(?: +\\(\\[#.\\]\\)\\)?"
5083 "\\(?: +"
5084 ;; Stats cookies can be stuck to body.
5085 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5086 "\\(%s\\)"
5087 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5088 "\\)"
5089 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5090 "[ \t]*$")
5091 org-todo-line-tags-regexp
5092 (concat "^\\(\\*+\\)"
5093 "\\(?: +" org-todo-regexp "\\)?"
5094 "\\(?: +\\(.*?\\)\\)??"
5095 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5096 "[ \t]*$")
5097 org-deadline-regexp (concat "\\<" org-deadline-string)
5098 org-deadline-time-regexp
5099 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5100 org-deadline-time-hour-regexp
5101 (concat "\\<" org-deadline-string
5102 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5103 org-deadline-line-regexp
5104 (concat "\\<\\(" org-deadline-string "\\).*")
5105 org-scheduled-regexp
5106 (concat "\\<" org-scheduled-string)
5107 org-scheduled-time-regexp
5108 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5109 org-scheduled-time-hour-regexp
5110 (concat "\\<" org-scheduled-string
5111 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5112 org-closed-time-regexp
5113 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5114 org-keyword-time-regexp
5115 (concat "\\<\\(" org-scheduled-string
5116 "\\|" org-deadline-string
5117 "\\|" org-closed-string
5118 "\\|" org-clock-string "\\)"
5119 " *[[<]\\([^]>]+\\)[]>]")
5120 org-keyword-time-not-clock-regexp
5121 (concat "\\<\\(" org-scheduled-string
5122 "\\|" org-deadline-string
5123 "\\|" org-closed-string
5124 "\\)"
5125 " *[[<]\\([^]>]+\\)[]>]")
5126 org-maybe-keyword-time-regexp
5127 (concat "\\(\\<\\(" org-scheduled-string
5128 "\\|" org-deadline-string
5129 "\\|" org-closed-string
5130 "\\|" org-clock-string "\\)\\)?"
5131 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5132 org-all-time-keywords
5133 (mapcar (lambda (w) (substring w 0 -1))
5134 (list org-scheduled-string org-deadline-string
5135 org-clock-string org-closed-string)))
5136 (org-compute-latex-and-related-regexp)
5137 (org-set-font-lock-defaults))))
5139 (defun org-file-contents (file &optional noerror)
5140 "Return the contents of FILE, as a string."
5141 (if (or (not file)
5142 (not (file-readable-p file)))
5143 (if noerror
5144 (message "Cannot read file \"%s\"" file)
5145 (error "Cannot read file \"%s\"" file))
5146 (with-temp-buffer
5147 (insert-file-contents file)
5148 (buffer-string))))
5150 (defun org-extract-log-state-settings (x)
5151 "Extract the log state setting from a TODO keyword string.
5152 This will extract info from a string like \"WAIT(w@/!)\"."
5153 (let (kw key log1 log2)
5154 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5155 (setq kw (match-string 1 x)
5156 key (and (match-end 2) (match-string 2 x))
5157 log1 (and (match-end 3) (match-string 3 x))
5158 log2 (and (match-end 4) (match-string 4 x)))
5159 (and (or log1 log2)
5160 (list kw
5161 (and log1 (if (equal log1 "!") 'time 'note))
5162 (and log2 (if (equal log2 "!") 'time 'note)))))))
5164 (defun org-remove-keyword-keys (list)
5165 "Remove a pair of parenthesis at the end of each string in LIST."
5166 (mapcar (lambda (x)
5167 (if (string-match "(.*)$" x)
5168 (substring x 0 (match-beginning 0))
5170 list))
5172 (defun org-assign-fast-keys (alist)
5173 "Assign fast keys to a keyword-key alist.
5174 Respect keys that are already there."
5175 (let (new e (alt ?0))
5176 (while (setq e (pop alist))
5177 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5178 (cdr e)) ;; Key already assigned.
5179 (push e new)
5180 (let ((clist (string-to-list (downcase (car e))))
5181 (used (append new alist)))
5182 (when (= (car clist) ?@)
5183 (pop clist))
5184 (while (and clist (rassoc (car clist) used))
5185 (pop clist))
5186 (unless clist
5187 (while (rassoc alt used)
5188 (incf alt)))
5189 (push (cons (car e) (or (car clist) alt)) new))))
5190 (nreverse new)))
5192 ;;; Some variables used in various places
5194 (defvar org-window-configuration nil
5195 "Used in various places to store a window configuration.")
5196 (defvar org-selected-window nil
5197 "Used in various places to store a window configuration.")
5198 (defvar org-finish-function nil
5199 "Function to be called when `C-c C-c' is used.
5200 This is for getting out of special buffers like capture.")
5203 ;; FIXME: Occasionally check by commenting these, to make sure
5204 ;; no other functions uses these, forgetting to let-bind them.
5205 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5206 (defvar org-last-state)
5207 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5209 ;; Defined somewhere in this file, but used before definition.
5210 (defvar org-entities) ;; defined in org-entities.el
5211 (defvar org-struct-menu)
5212 (defvar org-org-menu)
5213 (defvar org-tbl-menu)
5215 ;;;; Define the Org-mode
5217 ;; We use a before-change function to check if a table might need
5218 ;; an update.
5219 (defvar org-table-may-need-update t
5220 "Indicates that a table might need an update.
5221 This variable is set by `org-before-change-function'.
5222 `org-table-align' sets it back to nil.")
5223 (defun org-before-change-function (beg end)
5224 "Every change indicates that a table might need an update."
5225 (setq org-table-may-need-update t))
5226 (defvar org-mode-map)
5227 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5228 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5229 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5230 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5231 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5232 (defvar org-table-buffer-is-an nil)
5234 (defvar bidi-paragraph-direction)
5235 (defvar buffer-face-mode-face)
5237 (require 'outline)
5238 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5239 (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"))
5240 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5242 ;; Other stuff we need.
5243 (require 'time-date)
5244 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5245 (require 'easymenu)
5246 (require 'overlay)
5248 ;; (require 'org-macs) moved higher up in the file before it is first used
5249 (require 'org-entities)
5250 ;; (require 'org-compat) moved higher up in the file before it is first used
5251 (require 'org-faces)
5252 (require 'org-list)
5253 (require 'org-pcomplete)
5254 (require 'org-src)
5255 (require 'org-footnote)
5256 (require 'org-macro)
5258 ;; babel
5259 (require 'ob)
5261 ;;;###autoload
5262 (define-derived-mode org-mode outline-mode "Org"
5263 "Outline-based notes management and organizer, alias
5264 \"Carsten's outline-mode for keeping track of everything.\"
5266 Org-mode develops organizational tasks around a NOTES file which
5267 contains information about projects as plain text. Org-mode is
5268 implemented on top of outline-mode, which is ideal to keep the content
5269 of large files well structured. It supports ToDo items, deadlines and
5270 time stamps, which magically appear in the diary listing of the Emacs
5271 calendar. Tables are easily created with a built-in table editor.
5272 Plain text URL-like links connect to websites, emails (VM), Usenet
5273 messages (Gnus), BBDB entries, and any files related to the project.
5274 For printing and sharing of notes, an Org-mode file (or a part of it)
5275 can be exported as a structured ASCII or HTML file.
5277 The following commands are available:
5279 \\{org-mode-map}"
5281 ;; Get rid of Outline menus, they are not needed
5282 ;; Need to do this here because define-derived-mode sets up
5283 ;; the keymap so late. Still, it is a waste to call this each time
5284 ;; we switch another buffer into org-mode.
5285 (if (featurep 'xemacs)
5286 (when (boundp 'outline-mode-menu-heading)
5287 ;; Assume this is Greg's port, it uses easymenu
5288 (easy-menu-remove outline-mode-menu-heading)
5289 (easy-menu-remove outline-mode-menu-show)
5290 (easy-menu-remove outline-mode-menu-hide))
5291 (define-key org-mode-map [menu-bar headings] 'undefined)
5292 (define-key org-mode-map [menu-bar hide] 'undefined)
5293 (define-key org-mode-map [menu-bar show] 'undefined))
5295 (org-load-modules-maybe)
5296 (easy-menu-add org-org-menu)
5297 (easy-menu-add org-tbl-menu)
5298 (org-install-agenda-files-menu)
5299 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5300 (add-to-invisibility-spec '(org-cwidth))
5301 (add-to-invisibility-spec '(org-hide-block . t))
5302 (when (featurep 'xemacs)
5303 (org-set-local 'line-move-ignore-invisible t))
5304 (org-set-local 'outline-regexp org-outline-regexp)
5305 (org-set-local 'outline-level 'org-outline-level)
5306 (setq bidi-paragraph-direction 'left-to-right)
5307 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5308 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5309 (when (and org-ellipsis
5310 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5311 (fboundp 'make-glyph-code))
5312 (unless org-display-table
5313 (setq org-display-table (make-display-table)))
5314 (set-display-table-slot
5315 org-display-table 4
5316 (vconcat (mapcar
5317 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5318 org-ellipsis)))
5319 (if (stringp org-ellipsis) org-ellipsis "..."))))
5320 (setq buffer-display-table org-display-table))
5321 (org-set-regexps-and-options-for-tags)
5322 (org-set-regexps-and-options)
5323 (when (and org-tag-faces (not org-tags-special-faces-re))
5324 ;; tag faces set outside customize.... force initialization.
5325 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5326 ;; Calc embedded
5327 (org-set-local 'calc-embedded-open-mode "# ")
5328 ;; Modify a few syntax entries
5329 (modify-syntax-entry ?@ "w")
5330 (modify-syntax-entry ?\" "\"")
5331 (if org-startup-truncated (setq truncate-lines t))
5332 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5333 (org-set-local 'font-lock-unfontify-region-function
5334 'org-unfontify-region)
5335 ;; Activate before-change-function
5336 (org-set-local 'org-table-may-need-update t)
5337 (org-add-hook 'before-change-functions 'org-before-change-function nil
5338 'local)
5339 ;; Check for running clock before killing a buffer
5340 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5341 ;; Initialize macros templates.
5342 (org-macro-initialize-templates)
5343 ;; Initialize radio targets.
5344 (org-update-radio-target-regexp)
5345 ;; Indentation.
5346 (org-set-local 'indent-line-function 'org-indent-line)
5347 (org-set-local 'indent-region-function 'org-indent-region)
5348 ;; Filling and auto-filling.
5349 (org-setup-filling)
5350 ;; Comments.
5351 (org-setup-comments-handling)
5352 ;; Beginning/end of defun
5353 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5354 (org-set-local 'end-of-defun-function 'org-forward-element)
5355 ;; Next error for sparse trees
5356 (org-set-local 'next-error-function 'org-occur-next-match)
5357 ;; Make sure dependence stuff works reliably, even for users who set it
5358 ;; too late :-(
5359 (if org-enforce-todo-dependencies
5360 (add-hook 'org-blocker-hook
5361 'org-block-todo-from-children-or-siblings-or-parent)
5362 (remove-hook 'org-blocker-hook
5363 'org-block-todo-from-children-or-siblings-or-parent))
5364 (if org-enforce-todo-checkbox-dependencies
5365 (add-hook 'org-blocker-hook
5366 'org-block-todo-from-checkboxes)
5367 (remove-hook 'org-blocker-hook
5368 'org-block-todo-from-checkboxes))
5370 ;; Align options lines
5371 (org-set-local
5372 'align-mode-rules-list
5373 '((org-in-buffer-settings
5374 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5375 (modes . '(org-mode)))))
5377 ;; Imenu
5378 (org-set-local 'imenu-create-index-function
5379 'org-imenu-get-tree)
5381 ;; Make isearch reveal context
5382 (if (or (featurep 'xemacs)
5383 (not (boundp 'outline-isearch-open-invisible-function)))
5384 ;; Emacs 21 and XEmacs make use of the hook
5385 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5386 ;; Emacs 22 deals with this through a special variable
5387 (org-set-local 'outline-isearch-open-invisible-function
5388 (lambda (&rest ignore) (org-show-context 'isearch)))
5389 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5391 ;; Setup the pcomplete hooks
5392 (set (make-local-variable 'pcomplete-command-completion-function)
5393 'org-pcomplete-initial)
5394 (set (make-local-variable 'pcomplete-command-name-function)
5395 'org-command-at-point)
5396 (set (make-local-variable 'pcomplete-default-completion-function)
5397 'ignore)
5398 (set (make-local-variable 'pcomplete-parse-arguments-function)
5399 'org-parse-arguments)
5400 (set (make-local-variable 'pcomplete-termination-string) "")
5401 (when (>= emacs-major-version 23)
5402 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5404 ;; If empty file that did not turn on org-mode automatically, make it to.
5405 (if (and org-insert-mode-line-in-empty-file
5406 (org-called-interactively-p 'any)
5407 (= (point-min) (point-max)))
5408 (insert "# -*- mode: org -*-\n\n"))
5409 (unless org-inhibit-startup
5410 (org-unmodified
5411 (and org-startup-with-beamer-mode (org-beamer-mode))
5412 (when org-startup-align-all-tables
5413 (org-table-map-tables 'org-table-align 'quietly))
5414 (when org-startup-with-inline-images
5415 (org-display-inline-images))
5416 (when org-startup-with-latex-preview
5417 (org-preview-latex-fragment))
5418 (unless org-inhibit-startup-visibility-stuff
5419 (org-set-startup-visibility))))
5420 ;; Try to set org-hide correctly
5421 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5423 ;; Update `customize-package-emacs-version-alist'
5424 (add-to-list 'customize-package-emacs-version-alist
5425 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5426 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5427 ("8.0" . "24.4")))
5429 (defvar org-mode-transpose-word-syntax-table
5430 (let ((st (make-syntax-table)))
5431 (mapc (lambda(c) (modify-syntax-entry
5432 (string-to-char (car c)) "w p" st))
5433 org-emphasis-alist)
5434 st))
5436 (when (fboundp 'abbrev-table-put)
5437 (abbrev-table-put org-mode-abbrev-table
5438 :parents (list text-mode-abbrev-table)))
5440 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5442 (defsubst org-fix-ellipsis-at-bol ()
5443 (save-excursion (goto-char (window-start)) (recenter 0)))
5445 (defun org-find-invisible-foreground ()
5446 (let ((candidates (remove
5447 "unspecified-bg"
5448 (nconc
5449 (list (face-background 'default)
5450 (face-background 'org-default))
5451 (mapcar
5452 (lambda (alist)
5453 (when (boundp alist)
5454 (cdr (assoc 'background-color (symbol-value alist)))))
5455 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5456 (list (face-foreground 'org-hide))))))
5457 (car (remove nil candidates))))
5459 (defun org-current-time (&optional rounding-minutes past)
5460 "Current time, possibly rounded to ROUNDING-MINUTES.
5461 When ROUNDING-MINUTES is not an integer, fall back on the car of
5462 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5463 the rounding returns a past time."
5464 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5465 (car org-time-stamp-rounding-minutes)))
5466 (time (decode-time)) res)
5467 (if (< r 1)
5468 (current-time)
5469 (setq res
5470 (apply 'encode-time
5471 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5472 (nthcdr 2 time))))
5473 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5474 (seconds-to-time (- (org-float-time res) (* r 60)))
5475 res))))
5477 (defun org-today ()
5478 "Return today date, considering `org-extend-today-until'."
5479 (time-to-days
5480 (time-subtract (current-time)
5481 (list 0 (* 3600 org-extend-today-until) 0))))
5483 ;;;; Font-Lock stuff, including the activators
5485 (defvar org-mouse-map (make-sparse-keymap))
5486 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5487 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5488 (when org-mouse-1-follows-link
5489 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5490 (when org-tab-follows-link
5491 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5492 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5494 (require 'font-lock)
5496 (defconst org-non-link-chars "]\t\n\r<>")
5497 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5498 "shell" "elisp" "doi" "message"))
5499 (defvar org-link-types-re nil
5500 "Matches a link that has a url-like prefix like \"http:\"")
5501 (defvar org-link-re-with-space nil
5502 "Matches a link with spaces, optional angular brackets around it.")
5503 (defvar org-link-re-with-space2 nil
5504 "Matches a link with spaces, optional angular brackets around it.")
5505 (defvar org-link-re-with-space3 nil
5506 "Matches a link with spaces, only for internal part in bracket links.")
5507 (defvar org-angle-link-re nil
5508 "Matches link with angular brackets, spaces are allowed.")
5509 (defvar org-plain-link-re nil
5510 "Matches plain link, without spaces.")
5511 (defvar org-bracket-link-regexp nil
5512 "Matches a link in double brackets.")
5513 (defvar org-bracket-link-analytic-regexp nil
5514 "Regular expression used to analyze links.
5515 Here is what the match groups contain after a match:
5516 1: http:
5517 2: http
5518 3: path
5519 4: [desc]
5520 5: desc")
5521 (defvar org-bracket-link-analytic-regexp++ nil
5522 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5523 (defvar org-any-link-re nil
5524 "Regular expression matching any link.")
5526 (defconst org-match-sexp-depth 3
5527 "Number of stacked braces for sub/superscript matching.")
5529 (defun org-create-multibrace-regexp (left right n)
5530 "Create a regular expression which will match a balanced sexp.
5531 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5532 as single character strings.
5533 The regexp returned will match the entire expression including the
5534 delimiters. It will also define a single group which contains the
5535 match except for the outermost delimiters. The maximum depth of
5536 stacked delimiters is N. Escaping delimiters is not possible."
5537 (let* ((nothing (concat "[^" left right "]*?"))
5538 (or "\\|")
5539 (re nothing)
5540 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5541 (while (> n 1)
5542 (setq n (1- n)
5543 re (concat re or next)
5544 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5545 (concat left "\\(" re "\\)" right)))
5547 (defvar org-match-substring-regexp
5548 (concat
5549 "\\(\\S-\\)\\([_^]\\)\\("
5550 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5551 "\\|"
5552 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5553 "\\|"
5554 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5555 "The regular expression matching a sub- or superscript.")
5557 (defvar org-match-substring-with-braces-regexp
5558 (concat
5559 "\\(\\S-\\)\\([_^]\\)\\("
5560 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5561 "\\)")
5562 "The regular expression matching a sub- or superscript, forcing braces.")
5564 (defun org-make-link-regexps ()
5565 "Update the link regular expressions.
5566 This should be called after the variable `org-link-types' has changed."
5567 (setq org-link-types-re
5568 (concat
5569 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5570 org-link-re-with-space
5571 (concat
5572 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5573 "\\([^" org-non-link-chars " ]"
5574 "[^" org-non-link-chars "]*"
5575 "[^" org-non-link-chars " ]\\)>?")
5576 org-link-re-with-space2
5577 (concat
5578 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5579 "\\([^" org-non-link-chars " ]"
5580 "[^\t\n\r]*"
5581 "[^" org-non-link-chars " ]\\)>?")
5582 org-link-re-with-space3
5583 (concat
5584 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5585 "\\([^" org-non-link-chars " ]"
5586 "[^\t\n\r]*\\)")
5587 org-angle-link-re
5588 (concat
5589 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5590 "\\([^" org-non-link-chars " ]"
5591 "[^" org-non-link-chars "]*"
5592 "\\)>")
5593 org-plain-link-re
5594 (concat
5595 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5596 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5597 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5598 org-bracket-link-regexp
5599 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5600 org-bracket-link-analytic-regexp
5601 (concat
5602 "\\[\\["
5603 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5604 "\\([^]]+\\)"
5605 "\\]"
5606 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5607 "\\]")
5608 org-bracket-link-analytic-regexp++
5609 (concat
5610 "\\[\\["
5611 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5612 "\\([^]]+\\)"
5613 "\\]"
5614 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5615 "\\]")
5616 org-any-link-re
5617 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5618 org-angle-link-re "\\)\\|\\("
5619 org-plain-link-re "\\)")))
5621 (org-make-link-regexps)
5623 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5624 "Regular expression for fast time stamp matching.")
5625 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5626 "Regular expression for fast time stamp matching.")
5627 (defconst org-ts-regexp0
5628 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5629 "Regular expression matching time strings for analysis.
5630 This one does not require the space after the date, so it can be used
5631 on a string that terminates immediately after the date.")
5632 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5633 "Regular expression matching time strings for analysis.")
5634 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5635 "Regular expression matching time stamps, with groups.")
5636 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5637 "Regular expression matching time stamps (also [..]), with groups.")
5638 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5639 "Regular expression matching a time stamp range.")
5640 (defconst org-tr-regexp-both
5641 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5642 "Regular expression matching a time stamp range.")
5643 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5644 org-ts-regexp "\\)?")
5645 "Regular expression matching a time stamp or time stamp range.")
5646 (defconst org-tsr-regexp-both
5647 (concat org-ts-regexp-both "\\(--?-?"
5648 org-ts-regexp-both "\\)?")
5649 "Regular expression matching a time stamp or time stamp range.
5650 The time stamps may be either active or inactive.")
5652 (defvar org-emph-face nil)
5654 (defun org-do-emphasis-faces (limit)
5655 "Run through the buffer and add overlays to emphasized strings."
5656 (let (rtn a)
5657 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5658 (if (not (= (char-after (match-beginning 3))
5659 (char-after (match-beginning 4))))
5660 (progn
5661 (setq rtn t)
5662 (setq a (assoc (match-string 3) org-emphasis-alist))
5663 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5664 'face
5665 (nth 1 a))
5666 (and (nth 4 a)
5667 (org-remove-flyspell-overlays-in
5668 (match-beginning 0) (match-end 0)))
5669 (add-text-properties (match-beginning 2) (match-end 2)
5670 '(font-lock-multiline t org-emphasis t))
5671 (when org-hide-emphasis-markers
5672 (add-text-properties (match-end 4) (match-beginning 5)
5673 '(invisible org-link))
5674 (add-text-properties (match-beginning 3) (match-end 3)
5675 '(invisible org-link)))))
5676 (backward-char 1))
5677 rtn))
5679 (defun org-emphasize (&optional char)
5680 "Insert or change an emphasis, i.e. a font like bold or italic.
5681 If there is an active region, change that region to a new emphasis.
5682 If there is no region, just insert the marker characters and position
5683 the cursor between them.
5684 CHAR should be the marker character. If it is a space, it means to
5685 remove the emphasis of the selected region.
5686 If CHAR is not given (for example in an interactive call) it will be
5687 prompted for."
5688 (interactive)
5689 (let ((erc org-emphasis-regexp-components)
5690 (prompt "")
5691 (string "") beg end move c s)
5692 (if (org-region-active-p)
5693 (setq beg (region-beginning) end (region-end)
5694 string (buffer-substring beg end))
5695 (setq move t))
5697 (unless char
5698 (message "Emphasis marker or tag: [%s]"
5699 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5700 (setq char (read-char-exclusive)))
5701 (if (equal char ?\ )
5702 (setq s "" move nil)
5703 (unless (assoc (char-to-string char) org-emphasis-alist)
5704 (user-error "No such emphasis marker: \"%c\"" char))
5705 (setq s (char-to-string char)))
5706 (while (and (> (length string) 1)
5707 (equal (substring string 0 1) (substring string -1))
5708 (assoc (substring string 0 1) org-emphasis-alist))
5709 (setq string (substring string 1 -1)))
5710 (setq string (concat s string s))
5711 (if beg (delete-region beg end))
5712 (unless (or (bolp)
5713 (string-match (concat "[" (nth 0 erc) "\n]")
5714 (char-to-string (char-before (point)))))
5715 (insert " "))
5716 (unless (or (eobp)
5717 (string-match (concat "[" (nth 1 erc) "\n]")
5718 (char-to-string (char-after (point)))))
5719 (insert " ") (backward-char 1))
5720 (insert string)
5721 (and move (backward-char 1))))
5723 (defconst org-nonsticky-props
5724 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5726 (defsubst org-rear-nonsticky-at (pos)
5727 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5729 (defun org-activate-plain-links (limit)
5730 "Run through the buffer and add overlays to links."
5731 (let (f hl)
5732 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5733 (not (org-in-src-block-p)))
5734 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5735 (setq f (get-text-property (match-beginning 0) 'face))
5736 (setq hl (org-match-string-no-properties 0))
5737 (if (or (eq f 'org-tag)
5738 (and (listp f) (memq 'org-tag f)))
5740 (add-text-properties (match-beginning 0) (match-end 0)
5741 (list 'mouse-face 'highlight
5742 'face 'org-link
5743 'htmlize-link `(:uri ,hl)
5744 'keymap org-mouse-map))
5745 (org-rear-nonsticky-at (match-end 0)))
5746 t)))
5748 (defun org-activate-code (limit)
5749 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5750 (progn
5751 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5752 (remove-text-properties (match-beginning 0) (match-end 0)
5753 '(display t invisible t intangible t))
5754 t)))
5756 (defcustom org-src-fontify-natively nil
5757 "When non-nil, fontify code in code blocks."
5758 :type 'boolean
5759 :version "24.1"
5760 :group 'org-appearance
5761 :group 'org-babel)
5763 (defcustom org-allow-promoting-top-level-subtree nil
5764 "When non-nil, allow promoting a top level subtree.
5765 The leading star of the top level headline will be replaced
5766 by a #."
5767 :type 'boolean
5768 :version "24.1"
5769 :group 'org-appearance)
5771 (defun org-fontify-meta-lines-and-blocks (limit)
5772 (condition-case nil
5773 (org-fontify-meta-lines-and-blocks-1 limit)
5774 (error (message "org-mode fontification error"))))
5776 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5777 "Fontify #+ lines and blocks."
5778 (let ((case-fold-search t))
5779 (if (re-search-forward
5780 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5781 limit t)
5782 (let ((beg (match-beginning 0))
5783 (block-start (match-end 0))
5784 (block-end nil)
5785 (lang (match-string 7))
5786 (beg1 (line-beginning-position 2))
5787 (dc1 (downcase (match-string 2)))
5788 (dc3 (downcase (match-string 3)))
5789 end end1 quoting block-type ovl)
5790 (cond
5791 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5792 ;; a single line of backend-specific content
5793 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5794 (remove-text-properties (match-beginning 0) (match-end 0)
5795 '(display t invisible t intangible t))
5796 (add-text-properties (match-beginning 1) (match-end 3)
5797 '(font-lock-fontified t face org-meta-line))
5798 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5799 '(font-lock-fontified t face org-block))
5800 ; for backend-specific code
5802 ((and (match-end 4) (equal dc3 "+begin"))
5803 ;; Truly a block
5804 (setq block-type (downcase (match-string 5))
5805 quoting (member block-type org-protecting-blocks))
5806 (when (re-search-forward
5807 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5808 nil t) ;; on purpose, we look further than LIMIT
5809 (setq end (min (point-max) (match-end 0))
5810 end1 (min (point-max) (1- (match-beginning 0))))
5811 (setq block-end (match-beginning 0))
5812 (when quoting
5813 (remove-text-properties beg end
5814 '(display t invisible t intangible t)))
5815 (add-text-properties
5816 beg end
5817 '(font-lock-fontified t font-lock-multiline t))
5818 (add-text-properties beg beg1 '(face org-meta-line))
5819 (add-text-properties end1 (min (point-max) (1+ end))
5820 '(face org-meta-line)) ; for end_src
5821 (cond
5822 ((and lang (not (string= lang "")) org-src-fontify-natively)
5823 (org-src-font-lock-fontify-block lang block-start block-end)
5824 ;; remove old background overlays
5825 (mapc (lambda (ov)
5826 (if (eq (overlay-get ov 'face) 'org-block-background)
5827 (delete-overlay ov)))
5828 (overlays-at (/ (+ beg1 block-end) 2)))
5829 ;; add a background overlay
5830 (setq ovl (make-overlay beg1 block-end))
5831 (overlay-put ovl 'face 'org-block-background)
5832 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5833 (quoting
5834 (add-text-properties beg1 (min (point-max) (1+ end1))
5835 '(face org-block))) ; end of source block
5836 ((not org-fontify-quote-and-verse-blocks))
5837 ((string= block-type "quote")
5838 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5839 ((string= block-type "verse")
5840 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5841 (add-text-properties beg beg1 '(face org-block-begin-line))
5842 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5843 '(face org-block-end-line))
5845 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5846 (add-text-properties
5847 beg (match-end 3)
5848 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5849 '(font-lock-fontified t invisible t)
5850 '(font-lock-fontified t face org-document-info-keyword)))
5851 (add-text-properties
5852 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5853 (if (string-equal dc1 "+title:")
5854 '(font-lock-fontified t face org-document-title)
5855 '(font-lock-fontified t face org-document-info))))
5856 ((or (equal dc1 "+results")
5857 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5858 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5859 "+call:" "+header:" "+headers:" "+name:"))
5860 (and (match-end 4) (equal dc3 "+attr")))
5861 (add-text-properties
5862 beg (match-end 0)
5863 '(font-lock-fontified t face org-meta-line))
5865 ((member dc3 '(" " ""))
5866 (add-text-properties
5867 beg (match-end 0)
5868 '(font-lock-fontified t face font-lock-comment-face)))
5869 ((not (member (char-after beg) '(?\ ?\t)))
5870 ;; just any other in-buffer setting, but not indented
5871 (add-text-properties
5872 beg (match-end 0)
5873 '(font-lock-fontified t face org-meta-line))
5875 (t nil))))))
5877 (defun org-activate-angle-links (limit)
5878 "Run through the buffer and add overlays to links."
5879 (if (and (re-search-forward org-angle-link-re limit t)
5880 (not (org-in-src-block-p)))
5881 (progn
5882 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5883 (add-text-properties (match-beginning 0) (match-end 0)
5884 (list 'mouse-face 'highlight
5885 'keymap org-mouse-map))
5886 (org-rear-nonsticky-at (match-end 0))
5887 t)))
5889 (defun org-activate-footnote-links (limit)
5890 "Run through the buffer and add overlays to footnotes."
5891 (let ((fn (org-footnote-next-reference-or-definition limit)))
5892 (when fn
5893 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5894 (org-remove-flyspell-overlays-in beg end)
5895 (add-text-properties beg end
5896 (list 'mouse-face 'highlight
5897 'keymap org-mouse-map
5898 'help-echo
5899 (if (= (point-at-bol) beg)
5900 "Footnote definition"
5901 "Footnote reference")
5902 'font-lock-fontified t
5903 'font-lock-multiline t
5904 'face 'org-footnote))))))
5906 (defun org-activate-bracket-links (limit)
5907 "Run through the buffer and add overlays to bracketed links."
5908 (if (and (re-search-forward org-bracket-link-regexp limit t)
5909 (not (org-in-src-block-p)))
5910 (let* ((hl (org-match-string-no-properties 1))
5911 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5912 (ip (org-maybe-intangible
5913 (list 'invisible 'org-link
5914 'keymap org-mouse-map 'mouse-face 'highlight
5915 'font-lock-multiline t 'help-echo help
5916 'htmlize-link `(:uri ,hl))))
5917 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5918 'font-lock-multiline t 'help-echo help
5919 'htmlize-link `(:uri ,hl))))
5920 ;; We need to remove the invisible property here. Table narrowing
5921 ;; may have made some of this invisible.
5922 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5923 (remove-text-properties (match-beginning 0) (match-end 0)
5924 '(invisible nil))
5925 (if (match-end 3)
5926 (progn
5927 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5928 (org-rear-nonsticky-at (match-beginning 3))
5929 (add-text-properties (match-beginning 3) (match-end 3) vp)
5930 (org-rear-nonsticky-at (match-end 3))
5931 (add-text-properties (match-end 3) (match-end 0) ip)
5932 (org-rear-nonsticky-at (match-end 0)))
5933 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5934 (org-rear-nonsticky-at (match-beginning 1))
5935 (add-text-properties (match-beginning 1) (match-end 1) vp)
5936 (org-rear-nonsticky-at (match-end 1))
5937 (add-text-properties (match-end 1) (match-end 0) ip)
5938 (org-rear-nonsticky-at (match-end 0)))
5939 t)))
5941 (defun org-activate-dates (limit)
5942 "Run through the buffer and add overlays to dates."
5943 (if (and (re-search-forward org-tsr-regexp-both limit t)
5944 (not (equal (char-before (match-beginning 0)) 91)))
5945 (progn
5946 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5947 (add-text-properties (match-beginning 0) (match-end 0)
5948 (list 'mouse-face 'highlight
5949 'keymap org-mouse-map))
5950 (org-rear-nonsticky-at (match-end 0))
5951 (when org-display-custom-times
5952 (if (match-end 3)
5953 (org-display-custom-time (match-beginning 3) (match-end 3)))
5954 (org-display-custom-time (match-beginning 1) (match-end 1)))
5955 t)))
5957 (defvar org-target-link-regexp nil
5958 "Regular expression matching radio targets in plain text.")
5959 (make-variable-buffer-local 'org-target-link-regexp)
5960 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5961 "Regular expression matching a link target.")
5962 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5963 "Regular expression matching a radio target.")
5964 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5965 "Regular expression matching any target.")
5967 (defun org-activate-target-links (limit)
5968 "Run through the buffer and add overlays to target matches."
5969 (when org-target-link-regexp
5970 (let ((case-fold-search t))
5971 (if (re-search-forward org-target-link-regexp limit t)
5972 (progn
5973 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5974 (add-text-properties (match-beginning 0) (match-end 0)
5975 (list 'mouse-face 'highlight
5976 'keymap org-mouse-map
5977 'help-echo "Radio target link"
5978 'org-linked-text t))
5979 (org-rear-nonsticky-at (match-end 0))
5980 t)))))
5982 (defun org-update-radio-target-regexp ()
5983 "Find all radio targets in this file and update the regular expression."
5984 (interactive)
5985 (when (memq 'radio org-activate-links)
5986 (setq org-target-link-regexp
5987 (org-make-target-link-regexp (org-all-targets 'radio)))
5988 (org-restart-font-lock)))
5990 (defun org-hide-wide-columns (limit)
5991 (let (s e)
5992 (setq s (text-property-any (point) (or limit (point-max))
5993 'org-cwidth t))
5994 (when s
5995 (setq e (next-single-property-change s 'org-cwidth))
5996 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5997 (goto-char e)
5998 t)))
6000 (defvar org-latex-and-related-regexp nil
6001 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6002 (defvar org-match-substring-regexp)
6003 (defvar org-match-substring-with-braces-regexp)
6005 (defun org-compute-latex-and-related-regexp ()
6006 "Compute regular expression for LaTeX, entities and sub/superscript.
6007 Result depends on variable `org-highlight-latex-and-related'."
6008 (org-set-local
6009 'org-latex-and-related-regexp
6010 (let* ((re-sub
6011 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6012 ((eq org-use-sub-superscripts '{})
6013 (list org-match-substring-with-braces-regexp))
6014 (org-use-sub-superscripts (list org-match-substring-regexp))))
6015 (re-latex
6016 (when (memq 'latex org-highlight-latex-and-related)
6017 (let ((matchers (plist-get org-format-latex-options :matchers)))
6018 (delq nil
6019 (mapcar (lambda (x)
6020 (and (member (car x) matchers) (nth 1 x)))
6021 org-latex-regexps)))))
6022 (re-entities
6023 (when (memq 'entities org-highlight-latex-and-related)
6024 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6025 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6027 (defun org-do-latex-and-related (limit)
6028 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6029 LIMIT bounds the search for syntax to highlight. Stop at first
6030 highlighted object, if any. Return t if some highlighting was
6031 done, nil otherwise."
6032 (when (org-string-nw-p org-latex-and-related-regexp)
6033 (catch 'found
6034 (while (re-search-forward org-latex-and-related-regexp limit t)
6035 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6036 'face))
6037 '(org-code org-verbatim underline))
6038 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6039 '(?_ ?^))
6041 0)))
6042 (font-lock-prepend-text-property
6043 (+ offset (match-beginning 0)) (match-end 0)
6044 'face 'org-latex-and-related)
6045 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6046 '(font-lock-multiline t)))
6047 (throw 'found t)))
6048 nil)))
6050 (defun org-restart-font-lock ()
6051 "Restart `font-lock-mode', to force refontification."
6052 (when (and (boundp 'font-lock-mode) font-lock-mode)
6053 (font-lock-mode -1)
6054 (font-lock-mode 1)))
6056 (defun org-all-targets (&optional radio)
6057 "Return a list of all targets in this file.
6058 When optional argument RADIO is non-nil, only find radio
6059 targets."
6060 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6061 (save-excursion
6062 (goto-char (point-min))
6063 (while (re-search-forward re nil t)
6064 ;; Make sure point is really within the object.
6065 (backward-char)
6066 (let ((obj (org-element-context)))
6067 (when (memq (org-element-type obj) '(radio-target target))
6068 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6069 rtn)))
6071 (defun org-make-target-link-regexp (targets)
6072 "Make regular expression matching all strings in TARGETS.
6073 The regular expression finds the targets also if there is a line break
6074 between words."
6075 (and targets
6076 (concat
6077 "\\<\\("
6078 (mapconcat
6079 (lambda (x)
6080 (setq x (regexp-quote x))
6081 (while (string-match " +" x)
6082 (setq x (replace-match "\\s-+" t t x)))
6084 targets
6085 "\\|")
6086 "\\)\\>")))
6088 (defun org-activate-tags (limit)
6089 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6090 (progn
6091 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6092 (add-text-properties (match-beginning 1) (match-end 1)
6093 (list 'mouse-face 'highlight
6094 'keymap org-mouse-map))
6095 (org-rear-nonsticky-at (match-end 1))
6096 t)))
6098 (defun org-outline-level ()
6099 "Compute the outline level of the heading at point.
6100 If this is called at a normal headline, the level is the number of stars.
6101 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6102 (save-excursion
6103 (if (not (condition-case nil
6104 (org-back-to-heading t)
6105 (error nil)))
6107 (looking-at org-outline-regexp)
6108 (1- (- (match-end 0) (match-beginning 0))))))
6110 (defvar org-font-lock-keywords nil)
6112 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6113 "Regular expression matching a property line.")
6115 (defvar org-font-lock-hook nil
6116 "Functions to be called for special font lock stuff.")
6118 (defvar org-font-lock-set-keywords-hook nil
6119 "Functions that can manipulate `org-font-lock-extra-keywords'.
6120 This is called after `org-font-lock-extra-keywords' is defined, but before
6121 it is installed to be used by font lock. This can be useful if something
6122 needs to be inserted at a specific position in the font-lock sequence.")
6124 (defun org-font-lock-hook (limit)
6125 "Run `org-font-lock-hook' within LIMIT."
6126 (run-hook-with-args 'org-font-lock-hook limit))
6128 (defun org-set-font-lock-defaults ()
6129 "Set font lock defaults for the current buffer."
6130 (let* ((em org-fontify-emphasized-text)
6131 (lk org-activate-links)
6132 (org-font-lock-extra-keywords
6133 (list
6134 ;; Call the hook
6135 '(org-font-lock-hook)
6136 ;; Headlines
6137 `(,(if org-fontify-whole-heading-line
6138 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6139 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6140 (1 (org-get-level-face 1))
6141 (2 (org-get-level-face 2))
6142 (3 (org-get-level-face 3)))
6143 ;; Table lines
6144 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6145 (1 'org-table t))
6146 ;; Table internals
6147 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6148 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6149 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6150 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6151 ;; Drawers
6152 (list org-drawer-regexp '(0 'org-special-keyword t))
6153 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6154 ;; Properties
6155 (list org-property-re
6156 '(1 'org-special-keyword t)
6157 '(3 'org-property-value t))
6158 ;; Links
6159 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6160 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6161 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6162 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6163 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6164 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6165 (if (memq 'footnote lk) '(org-activate-footnote-links))
6166 ;; Targets.
6167 (list org-any-target-regexp '(0 'org-target t))
6168 ;; Diary sexps.
6169 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6170 ;; Macro
6171 '("{{{.+}}}" (0 'org-macro t))
6172 '(org-hide-wide-columns (0 nil append))
6173 ;; TODO keyword
6174 (list (format org-heading-keyword-regexp-format
6175 org-todo-regexp)
6176 '(2 (org-get-todo-face 2) t))
6177 ;; DONE
6178 (if org-fontify-done-headline
6179 (list (format org-heading-keyword-regexp-format
6180 (concat
6181 "\\(?:"
6182 (mapconcat 'regexp-quote org-done-keywords "\\|")
6183 "\\)"))
6184 '(2 'org-headline-done t))
6185 nil)
6186 ;; Priorities
6187 '(org-font-lock-add-priority-faces)
6188 ;; Tags
6189 '(org-font-lock-add-tag-faces)
6190 ;; Tags groups
6191 (if (and org-group-tags org-tag-groups-alist)
6192 (list (concat org-outline-regexp-bol ".+\\(:"
6193 (regexp-opt (mapcar 'car org-tag-groups-alist))
6194 ":\\).*$")
6195 '(1 'org-tag-group prepend)))
6196 ;; Special keywords
6197 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6198 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6199 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6200 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6201 ;; Emphasis
6202 (if em
6203 (if (featurep 'xemacs)
6204 '(org-do-emphasis-faces (0 nil append))
6205 '(org-do-emphasis-faces)))
6206 ;; Checkboxes
6207 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6208 1 'org-checkbox prepend)
6209 (if (cdr (assq 'checkbox org-list-automatic-rules))
6210 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6211 (0 (org-get-checkbox-statistics-face) t)))
6212 ;; Description list items
6213 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6214 1 'org-list-dt prepend)
6215 ;; ARCHIVEd headings
6216 (list (concat
6217 org-outline-regexp-bol
6218 "\\(.*:" org-archive-tag ":.*\\)")
6219 '(1 'org-archived prepend))
6220 ;; Specials
6221 '(org-do-latex-and-related)
6222 '(org-fontify-entities)
6223 '(org-raise-scripts)
6224 ;; Code
6225 '(org-activate-code (1 'org-code t))
6226 ;; COMMENT
6227 (list (format org-heading-keyword-regexp-format
6228 (concat "\\("
6229 org-comment-string "\\|" org-quote-string
6230 "\\)"))
6231 '(2 'org-special-keyword t))
6232 ;; Blocks and meta lines
6233 '(org-fontify-meta-lines-and-blocks))))
6234 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6235 (run-hooks 'org-font-lock-set-keywords-hook)
6236 ;; Now set the full font-lock-keywords
6237 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6238 (org-set-local 'font-lock-defaults
6239 '(org-font-lock-keywords t nil nil backward-paragraph))
6240 (kill-local-variable 'font-lock-keywords) nil))
6242 (defun org-toggle-pretty-entities ()
6243 "Toggle the composition display of entities as UTF8 characters."
6244 (interactive)
6245 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6246 (org-restart-font-lock)
6247 (if org-pretty-entities
6248 (message "Entities are now displayed as UTF8 characters")
6249 (save-restriction
6250 (widen)
6251 (org-decompose-region (point-min) (point-max))
6252 (message "Entities are now displayed as plain text"))))
6254 (defvar org-custom-properties-overlays nil
6255 "List of overlays used for custom properties.")
6256 (make-variable-buffer-local 'org-custom-properties-overlays)
6258 (defun org-toggle-custom-properties-visibility ()
6259 "Display or hide properties in `org-custom-properties'."
6260 (interactive)
6261 (if org-custom-properties-overlays
6262 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6263 (setq org-custom-properties-overlays nil))
6264 (unless (not org-custom-properties)
6265 (save-excursion
6266 (save-restriction
6267 (widen)
6268 (goto-char (point-min))
6269 (while (re-search-forward org-property-re nil t)
6270 (mapc (lambda(p)
6271 (when (equal p (substring (match-string 1) 1 -1))
6272 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6273 (overlay-put o 'invisible t)
6274 (overlay-put o 'org-custom-property t)
6275 (push o org-custom-properties-overlays))))
6276 org-custom-properties)))))))
6278 (defun org-fontify-entities (limit)
6279 "Find an entity to fontify."
6280 (let (ee)
6281 (when org-pretty-entities
6282 (catch 'match
6283 (while (re-search-forward
6284 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6285 limit t)
6286 (if (and (not (org-in-indented-comment-line))
6287 (setq ee (org-entity-get (match-string 1)))
6288 (= (length (nth 6 ee)) 1))
6289 (let*
6290 ((end (if (equal (match-string 2) "{}")
6291 (match-end 2)
6292 (match-end 1))))
6293 (add-text-properties
6294 (match-beginning 0) end
6295 (list 'font-lock-fontified t))
6296 (compose-region (match-beginning 0) end
6297 (nth 6 ee) nil)
6298 (backward-char 1)
6299 (throw 'match t))))
6300 nil))))
6302 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6303 "Fontify string S like in Org-mode."
6304 (with-temp-buffer
6305 (insert s)
6306 (let ((org-odd-levels-only odd-levels))
6307 (org-mode)
6308 (font-lock-fontify-buffer)
6309 (buffer-string))))
6311 (defvar org-m nil)
6312 (defvar org-l nil)
6313 (defvar org-f nil)
6314 (defun org-get-level-face (n)
6315 "Get the right face for match N in font-lock matching of headlines."
6316 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6317 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6318 (if org-cycle-level-faces
6319 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6320 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6321 (cond
6322 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6323 ((eq n 2) org-f)
6324 (t (if org-level-color-stars-only nil org-f))))
6327 (defun org-get-todo-face (kwd)
6328 "Get the right face for a TODO keyword KWD.
6329 If KWD is a number, get the corresponding match group."
6330 (if (numberp kwd) (setq kwd (match-string kwd)))
6331 (or (org-face-from-face-or-color
6332 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6333 (and (member kwd org-done-keywords) 'org-done)
6334 'org-todo))
6336 (defun org-face-from-face-or-color (context inherit face-or-color)
6337 "Create a face list that inherits INHERIT, but sets the foreground color.
6338 When FACE-OR-COLOR is not a string, just return it."
6339 (if (stringp face-or-color)
6340 (list :inherit inherit
6341 (cdr (assoc context org-faces-easy-properties))
6342 face-or-color)
6343 face-or-color))
6345 (defun org-font-lock-add-tag-faces (limit)
6346 "Add the special tag faces."
6347 (when (and org-tag-faces org-tags-special-faces-re)
6348 (while (re-search-forward org-tags-special-faces-re limit t)
6349 (add-text-properties (match-beginning 1) (match-end 1)
6350 (list 'face (org-get-tag-face 1)
6351 'font-lock-fontified t))
6352 (backward-char 1))))
6354 (defun org-font-lock-add-priority-faces (limit)
6355 "Add the special priority faces."
6356 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6357 (when (save-match-data (org-at-heading-p))
6358 (add-text-properties
6359 (match-beginning 0) (match-end 0)
6360 (list 'face (or (org-face-from-face-or-color
6361 'priority 'org-priority
6362 (cdr (assoc (char-after (match-beginning 1))
6363 org-priority-faces)))
6364 'org-priority)
6365 'font-lock-fontified t)))))
6367 (defun org-get-tag-face (kwd)
6368 "Get the right face for a TODO keyword KWD.
6369 If KWD is a number, get the corresponding match group."
6370 (if (numberp kwd) (setq kwd (match-string kwd)))
6371 (or (org-face-from-face-or-color
6372 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6373 'org-tag))
6375 (defun org-unfontify-region (beg end &optional maybe_loudly)
6376 "Remove fontification and activation overlays from links."
6377 (font-lock-default-unfontify-region beg end)
6378 (let* ((buffer-undo-list t)
6379 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6380 (inhibit-modification-hooks t)
6381 deactivate-mark buffer-file-name buffer-file-truename)
6382 (org-decompose-region beg end)
6383 (remove-text-properties beg end
6384 '(mouse-face t keymap t org-linked-text t
6385 invisible t intangible t
6386 org-no-flyspell t org-emphasis t))
6387 (org-remove-font-lock-display-properties beg end)))
6389 (defconst org-script-display '(((raise -0.3) (height 0.7))
6390 ((raise 0.3) (height 0.7))
6391 ((raise -0.5))
6392 ((raise 0.5)))
6393 "Display properties for showing superscripts and subscripts.")
6395 (defun org-remove-font-lock-display-properties (beg end)
6396 "Remove specific display properties that have been added by font lock.
6397 The will remove the raise properties that are used to show superscripts
6398 and subscripts."
6399 (let (next prop)
6400 (while (< beg end)
6401 (setq next (next-single-property-change beg 'display nil end)
6402 prop (get-text-property beg 'display))
6403 (if (member prop org-script-display)
6404 (put-text-property beg next 'display nil))
6405 (setq beg next))))
6407 (defun org-raise-scripts (limit)
6408 "Add raise properties to sub/superscripts."
6409 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6410 (if (re-search-forward
6411 (if (eq org-use-sub-superscripts t)
6412 org-match-substring-regexp
6413 org-match-substring-with-braces-regexp)
6414 limit t)
6415 (let* ((pos (point)) table-p comment-p
6416 (mpos (match-beginning 3))
6417 (emph-p (get-text-property mpos 'org-emphasis))
6418 (link-p (get-text-property mpos 'mouse-face))
6419 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6420 (goto-char (point-at-bol))
6421 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6422 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6423 (goto-char pos)
6424 ;; Handle a_b^c
6425 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6426 (if (or comment-p emph-p link-p keyw-p)
6428 (put-text-property (match-beginning 3) (match-end 0)
6429 'display
6430 (if (equal (char-after (match-beginning 2)) ?^)
6431 (nth (if table-p 3 1) org-script-display)
6432 (nth (if table-p 2 0) org-script-display)))
6433 (add-text-properties (match-beginning 2) (match-end 2)
6434 (list 'invisible t
6435 'org-dwidth t 'org-dwidth-n 1))
6436 (if (and (eq (char-after (match-beginning 3)) ?{)
6437 (eq (char-before (match-end 3)) ?}))
6438 (progn
6439 (add-text-properties
6440 (match-beginning 3) (1+ (match-beginning 3))
6441 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6442 (add-text-properties
6443 (1- (match-end 3)) (match-end 3)
6444 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6445 t)))))
6447 ;;;; Visibility cycling, including org-goto and indirect buffer
6449 ;;; Cycling
6451 (defvar org-cycle-global-status nil)
6452 (make-variable-buffer-local 'org-cycle-global-status)
6453 (put 'org-cycle-global-status 'org-state t)
6454 (defvar org-cycle-subtree-status nil)
6455 (make-variable-buffer-local 'org-cycle-subtree-status)
6456 (put 'org-cycle-subtree-status 'org-state t)
6458 (defvar org-inlinetask-min-level)
6460 ;;;###autoload
6461 (defun org-cycle (&optional arg)
6462 "TAB-action and visibility cycling for Org-mode.
6464 This is the command invoked in Org-mode by the TAB key. Its main purpose
6465 is outline visibility cycling, but it also invokes other actions
6466 in special contexts.
6468 - When this function is called with a prefix argument, rotate the entire
6469 buffer through 3 states (global cycling)
6470 1. OVERVIEW: Show only top-level headlines.
6471 2. CONTENTS: Show all headlines of all levels, but no body text.
6472 3. SHOW ALL: Show everything.
6473 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6474 determined by the variable `org-startup-folded', and by any VISIBILITY
6475 properties in the buffer.
6476 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6477 including any drawers.
6479 - When inside a table, re-align the table and move to the next field.
6481 - When point is at the beginning of a headline, rotate the subtree started
6482 by this line through 3 different states (local cycling)
6483 1. FOLDED: Only the main headline is shown.
6484 2. CHILDREN: The main headline and the direct children are shown.
6485 From this state, you can move to one of the children
6486 and zoom in further.
6487 3. SUBTREE: Show the entire subtree, including body text.
6488 If there is no subtree, switch directly from CHILDREN to FOLDED.
6490 - When point is at the beginning of an empty headline and the variable
6491 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6492 of the headline by demoting and promoting it to likely levels. This
6493 speeds up creation document structure by pressing TAB once or several
6494 times right after creating a new headline.
6496 - When there is a numeric prefix, go up to a heading with level ARG, do
6497 a `show-subtree' and return to the previous cursor position. If ARG
6498 is negative, go up that many levels.
6500 - When point is not at the beginning of a headline, execute the global
6501 binding for TAB, which is re-indenting the line. See the option
6502 `org-cycle-emulate-tab' for details.
6504 - Special case: if point is at the beginning of the buffer and there is
6505 no headline in line 1, this function will act as if called with prefix arg
6506 (C-u TAB, same as S-TAB) also when called without prefix arg.
6507 But only if also the variable `org-cycle-global-at-bob' is t."
6508 (interactive "P")
6509 (org-load-modules-maybe)
6510 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6511 (and org-cycle-level-after-item/entry-creation
6512 (or (org-cycle-level)
6513 (org-cycle-item-indentation))))
6514 (let* (message-log-max ; Don't populate the *Messages* buffer
6515 (limit-level
6516 (or org-cycle-max-level
6517 (and (boundp 'org-inlinetask-min-level)
6518 org-inlinetask-min-level
6519 (1- org-inlinetask-min-level))))
6520 (nstars (and limit-level
6521 (if org-odd-levels-only
6522 (and limit-level (1- (* limit-level 2)))
6523 limit-level)))
6524 (org-outline-regexp
6525 (if (not (derived-mode-p 'org-mode))
6526 outline-regexp
6527 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6528 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6529 (not (looking-at org-outline-regexp))))
6530 (org-cycle-hook
6531 (if bob-special
6532 (delq 'org-optimize-window-after-visibility-change
6533 (copy-sequence org-cycle-hook))
6534 org-cycle-hook))
6535 (pos (point)))
6537 (if (or bob-special (equal arg '(4)))
6538 ;; special case: use global cycling
6539 (setq arg t))
6541 (cond
6543 ((equal arg '(16))
6544 (setq last-command 'dummy)
6545 (org-set-startup-visibility)
6546 (message "Startup visibility, plus VISIBILITY properties"))
6548 ((equal arg '(64))
6549 (show-all)
6550 (message "Entire buffer visible, including drawers"))
6552 ;; Table: enter it or move to the next field.
6553 ((org-at-table-p 'any)
6554 (if (org-at-table.el-p)
6555 (message "Use C-c ' to edit table.el tables")
6556 (if arg (org-table-edit-field t)
6557 (org-table-justify-field-maybe)
6558 (call-interactively 'org-table-next-field))))
6560 ((run-hook-with-args-until-success
6561 'org-tab-after-check-for-table-hook))
6563 ;; Global cycling: delegate to `org-cycle-internal-global'.
6564 ((eq arg t) (org-cycle-internal-global))
6566 ;; Drawers: delegate to `org-flag-drawer'.
6567 ((and org-drawers org-drawer-regexp
6568 (save-excursion
6569 (beginning-of-line 1)
6570 (looking-at org-drawer-regexp)))
6571 (org-flag-drawer ; toggle block visibility
6572 (not (get-char-property (match-end 0) 'invisible))))
6574 ;; Show-subtree, ARG levels up from here.
6575 ((integerp arg)
6576 (save-excursion
6577 (org-back-to-heading)
6578 (outline-up-heading (if (< arg 0) (- arg)
6579 (- (funcall outline-level) arg)))
6580 (org-show-subtree)))
6582 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6583 ((and (featurep 'org-inlinetask)
6584 (org-inlinetask-at-task-p)
6585 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6586 (org-inlinetask-toggle-visibility))
6588 ((org-try-cdlatex-tab))
6590 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6591 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6592 (save-excursion (beginning-of-line 1)
6593 (looking-at org-outline-regexp)))
6594 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6595 (org-cycle-internal-local))
6597 ;; From there: TAB emulation and template completion.
6598 (buffer-read-only (org-back-to-heading))
6600 ((run-hook-with-args-until-success
6601 'org-tab-after-check-for-cycling-hook))
6603 ((org-try-structure-completion))
6605 ((run-hook-with-args-until-success
6606 'org-tab-before-tab-emulation-hook))
6608 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6609 (or (not (bolp))
6610 (not (looking-at org-outline-regexp))))
6611 (call-interactively (global-key-binding "\t")))
6613 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6614 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6615 (or (and (eq org-cycle-emulate-tab 'white)
6616 (= (match-end 0) (point-at-eol)))
6617 (and (eq org-cycle-emulate-tab 'whitestart)
6618 (>= (match-end 0) pos))))
6620 (eq org-cycle-emulate-tab t))
6621 (call-interactively (global-key-binding "\t")))
6623 (t (save-excursion
6624 (org-back-to-heading)
6625 (org-cycle)))))))
6627 (defun org-cycle-internal-global ()
6628 "Do the global cycling action."
6629 ;; Hack to avoid display of messages for .org attachments in Gnus
6630 (let (message-log-max ; Don't populate the *Messages* buffer
6631 (ga (string-match "\\*fontification" (buffer-name))))
6632 (cond
6633 ((and (eq last-command this-command)
6634 (eq org-cycle-global-status 'overview))
6635 ;; We just created the overview - now do table of contents
6636 ;; This can be slow in very large buffers, so indicate action
6637 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6638 (unless ga (message "CONTENTS..."))
6639 (org-content)
6640 (unless ga (message "CONTENTS...done"))
6641 (setq org-cycle-global-status 'contents)
6642 (run-hook-with-args 'org-cycle-hook 'contents))
6644 ((and (eq last-command this-command)
6645 (eq org-cycle-global-status 'contents))
6646 ;; We just showed the table of contents - now show everything
6647 (run-hook-with-args 'org-pre-cycle-hook 'all)
6648 (show-all)
6649 (unless ga (message "SHOW ALL"))
6650 (setq org-cycle-global-status 'all)
6651 (run-hook-with-args 'org-cycle-hook 'all))
6654 ;; Default action: go to overview
6655 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6656 (org-overview)
6657 (unless ga (message "OVERVIEW"))
6658 (setq org-cycle-global-status 'overview)
6659 (run-hook-with-args 'org-cycle-hook 'overview)))))
6661 (defun org-cycle-internal-local ()
6662 "Do the local cycling action."
6663 (let (message-log-max ; Don't populate the *Messages* buffer
6664 (goal-column 0) eoh eol eos has-children children-skipped struct)
6665 ;; First, determine end of headline (EOH), end of subtree or item
6666 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6667 (save-excursion
6668 (if (org-at-item-p)
6669 (progn
6670 (beginning-of-line)
6671 (setq struct (org-list-struct))
6672 (setq eoh (point-at-eol))
6673 (setq eos (org-list-get-item-end-before-blank (point) struct))
6674 (setq has-children (org-list-has-child-p (point) struct)))
6675 (org-back-to-heading)
6676 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6677 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6678 (setq has-children
6679 (or (save-excursion
6680 (let ((level (funcall outline-level)))
6681 (outline-next-heading)
6682 (and (org-at-heading-p t)
6683 (> (funcall outline-level) level))))
6684 (save-excursion
6685 (org-list-search-forward (org-item-beginning-re) eos t)))))
6686 ;; Determine end invisible part of buffer (EOL)
6687 (beginning-of-line 2)
6688 ;; XEmacs doesn't have `next-single-char-property-change'
6689 (if (featurep 'xemacs)
6690 (while (and (not (eobp)) ;; this is like `next-line'
6691 (get-char-property (1- (point)) 'invisible))
6692 (beginning-of-line 2))
6693 (while (and (not (eobp)) ;; this is like `next-line'
6694 (get-char-property (1- (point)) 'invisible))
6695 (goto-char (next-single-char-property-change (point) 'invisible))
6696 (and (eolp) (beginning-of-line 2))))
6697 (setq eol (point)))
6698 ;; Find out what to do next and set `this-command'
6699 (cond
6700 ((= eos eoh)
6701 ;; Nothing is hidden behind this heading
6702 (unless (org-before-first-heading-p)
6703 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6704 (message "EMPTY ENTRY")
6705 (setq org-cycle-subtree-status nil)
6706 (save-excursion
6707 (goto-char eos)
6708 (outline-next-heading)
6709 (if (outline-invisible-p) (org-flag-heading nil))))
6710 ((and (or (>= eol eos)
6711 (not (string-match "\\S-" (buffer-substring eol eos))))
6712 (or has-children
6713 (not (setq children-skipped
6714 org-cycle-skip-children-state-if-no-children))))
6715 ;; Entire subtree is hidden in one line: children view
6716 (unless (org-before-first-heading-p)
6717 (run-hook-with-args 'org-pre-cycle-hook 'children))
6718 (if (org-at-item-p)
6719 (org-list-set-item-visibility (point-at-bol) struct 'children)
6720 (org-show-entry)
6721 (org-with-limited-levels (show-children))
6722 ;; FIXME: This slows down the func way too much.
6723 ;; How keep drawers hidden in subtree anyway?
6724 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6725 ;; (org-cycle-hide-drawers 'subtree))
6727 ;; Fold every list in subtree to top-level items.
6728 (when (eq org-cycle-include-plain-lists 'integrate)
6729 (save-excursion
6730 (org-back-to-heading)
6731 (while (org-list-search-forward (org-item-beginning-re) eos t)
6732 (beginning-of-line 1)
6733 (let* ((struct (org-list-struct))
6734 (prevs (org-list-prevs-alist struct))
6735 (end (org-list-get-bottom-point struct)))
6736 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6737 (org-list-get-all-items (point) struct prevs))
6738 (goto-char (if (< end eos) end eos)))))))
6739 (message "CHILDREN")
6740 (save-excursion
6741 (goto-char eos)
6742 (outline-next-heading)
6743 (if (outline-invisible-p) (org-flag-heading nil)))
6744 (setq org-cycle-subtree-status 'children)
6745 (unless (org-before-first-heading-p)
6746 (run-hook-with-args 'org-cycle-hook 'children)))
6747 ((or children-skipped
6748 (and (eq last-command this-command)
6749 (eq org-cycle-subtree-status 'children)))
6750 ;; We just showed the children, or no children are there,
6751 ;; now show everything.
6752 (unless (org-before-first-heading-p)
6753 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6754 (outline-flag-region eoh eos nil)
6755 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6756 (setq org-cycle-subtree-status 'subtree)
6757 (unless (org-before-first-heading-p)
6758 (run-hook-with-args 'org-cycle-hook 'subtree)))
6760 ;; Default action: hide the subtree.
6761 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6762 (outline-flag-region eoh eos t)
6763 (message "FOLDED")
6764 (setq org-cycle-subtree-status 'folded)
6765 (unless (org-before-first-heading-p)
6766 (run-hook-with-args 'org-cycle-hook 'folded))))))
6768 ;;;###autoload
6769 (defun org-global-cycle (&optional arg)
6770 "Cycle the global visibility. For details see `org-cycle'.
6771 With \\[universal-argument] prefix arg, switch to startup visibility.
6772 With a numeric prefix, show all headlines up to that level."
6773 (interactive "P")
6774 (let ((org-cycle-include-plain-lists
6775 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6776 (cond
6777 ((integerp arg)
6778 (show-all)
6779 (hide-sublevels arg)
6780 (setq org-cycle-global-status 'contents))
6781 ((equal arg '(4))
6782 (org-set-startup-visibility)
6783 (message "Startup visibility, plus VISIBILITY properties."))
6785 (org-cycle '(4))))))
6787 (defun org-set-startup-visibility ()
6788 "Set the visibility required by startup options and properties."
6789 (cond
6790 ((eq org-startup-folded t)
6791 (org-cycle '(4)))
6792 ((eq org-startup-folded 'content)
6793 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6794 (org-cycle '(4)) (org-cycle '(4)))))
6795 (unless (eq org-startup-folded 'showeverything)
6796 (if org-hide-block-startup (org-hide-block-all))
6797 (org-set-visibility-according-to-property 'no-cleanup)
6798 (org-cycle-hide-archived-subtrees 'all)
6799 (org-cycle-hide-drawers 'all)
6800 (org-cycle-show-empty-lines t)))
6802 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6803 "Switch subtree visibilities according to :VISIBILITY: property."
6804 (interactive)
6805 (let (org-show-entry-below state)
6806 (save-excursion
6807 (goto-char (point-min))
6808 (while (re-search-forward
6809 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6810 nil t)
6811 (setq state (match-string 1))
6812 (save-excursion
6813 (org-back-to-heading t)
6814 (hide-subtree)
6815 (org-reveal)
6816 (cond
6817 ((equal state '("fold" "folded"))
6818 (hide-subtree))
6819 ((equal state "children")
6820 (org-show-hidden-entry)
6821 (show-children))
6822 ((equal state "content")
6823 (save-excursion
6824 (save-restriction
6825 (org-narrow-to-subtree)
6826 (org-content))))
6827 ((member state '("all" "showall"))
6828 (show-subtree)))))
6829 (unless no-cleanup
6830 (org-cycle-hide-archived-subtrees 'all)
6831 (org-cycle-hide-drawers 'all)
6832 (org-cycle-show-empty-lines 'all)))))
6834 ;; This function uses outline-regexp instead of the more fundamental
6835 ;; org-outline-regexp so that org-cycle-global works outside of Org
6836 ;; buffers, where outline-regexp is needed.
6837 (defun org-overview ()
6838 "Switch to overview mode, showing only top-level headlines.
6839 Really, this shows all headlines with level equal or greater than the level
6840 of the first headline in the buffer. This is important, because if the
6841 first headline is not level one, then (hide-sublevels 1) gives confusing
6842 results."
6843 (interactive)
6844 (let ((l (org-current-line))
6845 (level (save-excursion
6846 (goto-char (point-min))
6847 (if (re-search-forward (concat "^" outline-regexp) nil t)
6848 (progn
6849 (goto-char (match-beginning 0))
6850 (funcall outline-level))))))
6851 (and level (hide-sublevels level))
6852 (recenter '(4))
6853 (org-goto-line l)))
6855 (defun org-content (&optional arg)
6856 "Show all headlines in the buffer, like a table of contents.
6857 With numerical argument N, show content up to level N."
6858 (interactive "P")
6859 (save-excursion
6860 ;; Visit all headings and show their offspring
6861 (and (integerp arg) (org-overview))
6862 (goto-char (point-max))
6863 (catch 'exit
6864 (while (and (progn (condition-case nil
6865 (outline-previous-visible-heading 1)
6866 (error (goto-char (point-min))))
6868 (looking-at org-outline-regexp))
6869 (if (integerp arg)
6870 (show-children (1- arg))
6871 (show-branches))
6872 (if (bobp) (throw 'exit nil))))))
6875 (defun org-optimize-window-after-visibility-change (state)
6876 "Adjust the window after a change in outline visibility.
6877 This function is the default value of the hook `org-cycle-hook'."
6878 (when (get-buffer-window (current-buffer))
6879 (cond
6880 ((eq state 'content) nil)
6881 ((eq state 'all) nil)
6882 ((eq state 'folded) nil)
6883 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6884 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6886 (defun org-remove-empty-overlays-at (pos)
6887 "Remove outline overlays that do not contain non-white stuff."
6888 (mapc
6889 (lambda (o)
6890 (and (eq 'outline (overlay-get o 'invisible))
6891 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6892 (overlay-end o))))
6893 (delete-overlay o)))
6894 (overlays-at pos)))
6896 (defun org-clean-visibility-after-subtree-move ()
6897 "Fix visibility issues after moving a subtree."
6898 ;; First, find a reasonable region to look at:
6899 ;; Start two siblings above, end three below
6900 (let* ((beg (save-excursion
6901 (and (org-get-last-sibling)
6902 (org-get-last-sibling))
6903 (point)))
6904 (end (save-excursion
6905 (and (org-get-next-sibling)
6906 (org-get-next-sibling)
6907 (org-get-next-sibling))
6908 (if (org-at-heading-p)
6909 (point-at-eol)
6910 (point))))
6911 (level (looking-at "\\*+"))
6912 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6913 (save-excursion
6914 (save-restriction
6915 (narrow-to-region beg end)
6916 (when re
6917 ;; Properly fold already folded siblings
6918 (goto-char (point-min))
6919 (while (re-search-forward re nil t)
6920 (if (and (not (outline-invisible-p))
6921 (save-excursion
6922 (goto-char (point-at-eol)) (outline-invisible-p)))
6923 (hide-entry))))
6924 (org-cycle-show-empty-lines 'overview)
6925 (org-cycle-hide-drawers 'overview)))))
6927 (defun org-cycle-show-empty-lines (state)
6928 "Show empty lines above all visible headlines.
6929 The region to be covered depends on STATE when called through
6930 `org-cycle-hook'. Lisp program can use t for STATE to get the
6931 entire buffer covered. Note that an empty line is only shown if there
6932 are at least `org-cycle-separator-lines' empty lines before the headline."
6933 (when (not (= org-cycle-separator-lines 0))
6934 (save-excursion
6935 (let* ((n (abs org-cycle-separator-lines))
6936 (re (cond
6937 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6938 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6939 (t (let ((ns (number-to-string (- n 2))))
6940 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6941 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6942 beg end b e)
6943 (cond
6944 ((memq state '(overview contents t))
6945 (setq beg (point-min) end (point-max)))
6946 ((memq state '(children folded))
6947 (setq beg (point) end (progn (org-end-of-subtree t t)
6948 (beginning-of-line 2)
6949 (point)))))
6950 (when beg
6951 (goto-char beg)
6952 (while (re-search-forward re end t)
6953 (unless (get-char-property (match-end 1) 'invisible)
6954 (setq e (match-end 1))
6955 (if (< org-cycle-separator-lines 0)
6956 (setq b (save-excursion
6957 (goto-char (match-beginning 0))
6958 (org-back-over-empty-lines)
6959 (if (save-excursion
6960 (goto-char (max (point-min) (1- (point))))
6961 (org-at-heading-p))
6962 (1- (point))
6963 (point))))
6964 (setq b (match-beginning 1)))
6965 (outline-flag-region b e nil)))))))
6966 ;; Never hide empty lines at the end of the file.
6967 (save-excursion
6968 (goto-char (point-max))
6969 (outline-previous-heading)
6970 (outline-end-of-heading)
6971 (if (and (looking-at "[ \t\n]+")
6972 (= (match-end 0) (point-max)))
6973 (outline-flag-region (point) (match-end 0) nil))))
6975 (defun org-show-empty-lines-in-parent ()
6976 "Move to the parent and re-show empty lines before visible headlines."
6977 (save-excursion
6978 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6979 (org-cycle-show-empty-lines context))))
6981 (defun org-files-list ()
6982 "Return `org-agenda-files' list, plus all open org-mode files.
6983 This is useful for operations that need to scan all of a user's
6984 open and agenda-wise Org files."
6985 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6986 (dolist (buf (buffer-list))
6987 (with-current-buffer buf
6988 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6989 (let ((file (expand-file-name (buffer-file-name))))
6990 (unless (member file files)
6991 (push file files))))))
6992 files))
6994 (defsubst org-entry-beginning-position ()
6995 "Return the beginning position of the current entry."
6996 (save-excursion (outline-back-to-heading t) (point)))
6998 (defsubst org-entry-end-position ()
6999 "Return the end position of the current entry."
7000 (save-excursion (outline-next-heading) (point)))
7002 (defun org-cycle-hide-drawers (state)
7003 "Re-hide all drawers after a visibility state change."
7004 (when (and (derived-mode-p 'org-mode)
7005 (not (memq state '(overview folded contents))))
7006 (save-excursion
7007 (let* ((globalp (memq state '(contents all)))
7008 (beg (if globalp (point-min) (point)))
7009 (end (if globalp (point-max)
7010 (if (eq state 'children)
7011 (save-excursion (outline-next-heading) (point))
7012 (org-end-of-subtree t)))))
7013 (goto-char beg)
7014 (while (re-search-forward org-drawer-regexp end t)
7015 (org-flag-drawer t))))))
7017 (defun org-cycle-hide-inline-tasks (state)
7018 "Re-hide inline task when switching to 'contents visibility state."
7019 (when (and (eq state 'contents)
7020 (boundp 'org-inlinetask-min-level)
7021 org-inlinetask-min-level)
7022 (hide-sublevels (1- org-inlinetask-min-level))))
7024 (defun org-flag-drawer (flag)
7025 "When FLAG is non-nil, hide the drawer we are within.
7026 Otherwise make it visible."
7027 (save-excursion
7028 (beginning-of-line 1)
7029 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7030 (let ((b (match-end 0)))
7031 (if (re-search-forward
7032 "^[ \t]*:END:"
7033 (save-excursion (outline-next-heading) (point)) t)
7034 (outline-flag-region b (point-at-eol) flag)
7035 (user-error ":END: line missing at position %s" b))))))
7037 (defun org-subtree-end-visible-p ()
7038 "Is the end of the current subtree visible?"
7039 (pos-visible-in-window-p
7040 (save-excursion (org-end-of-subtree t) (point))))
7042 (defun org-first-headline-recenter (&optional N)
7043 "Move cursor to the first headline and recenter the headline.
7044 Optional argument N means put the headline into the Nth line of the window."
7045 (goto-char (point-min))
7046 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7047 (beginning-of-line)
7048 (recenter (prefix-numeric-value N))))
7050 ;;; Saving and restoring visibility
7052 (defun org-outline-overlay-data (&optional use-markers)
7053 "Return a list of the locations of all outline overlays.
7054 These are overlays with the `invisible' property value `outline'.
7055 The return value is a list of cons cells, with start and stop
7056 positions for each overlay.
7057 If USE-MARKERS is set, return the positions as markers."
7058 (let (beg end)
7059 (save-excursion
7060 (save-restriction
7061 (widen)
7062 (delq nil
7063 (mapcar (lambda (o)
7064 (when (eq (overlay-get o 'invisible) 'outline)
7065 (setq beg (overlay-start o)
7066 end (overlay-end o))
7067 (and beg end (> end beg)
7068 (if use-markers
7069 (cons (move-marker (make-marker) beg)
7070 (move-marker (make-marker) end))
7071 (cons beg end)))))
7072 (overlays-in (point-min) (point-max))))))))
7074 (defun org-set-outline-overlay-data (data)
7075 "Create visibility overlays for all positions in DATA.
7076 DATA should have been made by `org-outline-overlay-data'."
7077 (let (o)
7078 (save-excursion
7079 (save-restriction
7080 (widen)
7081 (show-all)
7082 (mapc (lambda (c)
7083 (outline-flag-region (car c) (cdr c) t))
7084 data)))))
7086 ;;; Folding of blocks
7088 (defvar org-hide-block-overlays nil
7089 "Overlays hiding blocks.")
7090 (make-variable-buffer-local 'org-hide-block-overlays)
7092 (defun org-block-map (function &optional start end)
7093 "Call FUNCTION at the head of all source blocks in the current buffer.
7094 Optional arguments START and END can be used to limit the range."
7095 (let ((start (or start (point-min)))
7096 (end (or end (point-max))))
7097 (save-excursion
7098 (goto-char start)
7099 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7100 (save-excursion
7101 (save-match-data
7102 (goto-char (match-beginning 0))
7103 (funcall function)))))))
7105 (defun org-hide-block-toggle-all ()
7106 "Toggle the visibility of all blocks in the current buffer."
7107 (org-block-map #'org-hide-block-toggle))
7109 (defun org-hide-block-all ()
7110 "Fold all blocks in the current buffer."
7111 (interactive)
7112 (org-show-block-all)
7113 (org-block-map #'org-hide-block-toggle-maybe))
7115 (defun org-show-block-all ()
7116 "Unfold all blocks in the current buffer."
7117 (interactive)
7118 (mapc 'delete-overlay org-hide-block-overlays)
7119 (setq org-hide-block-overlays nil))
7121 (defun org-hide-block-toggle-maybe ()
7122 "Toggle visibility of block at point."
7123 (interactive)
7124 (let ((case-fold-search t))
7125 (if (save-excursion
7126 (beginning-of-line 1)
7127 (looking-at org-block-regexp))
7128 (progn (org-hide-block-toggle)
7129 t) ;; to signal that we took action
7130 nil))) ;; to signal that we did not
7132 (defun org-hide-block-toggle (&optional force)
7133 "Toggle the visibility of the current block."
7134 (interactive)
7135 (save-excursion
7136 (beginning-of-line)
7137 (if (re-search-forward org-block-regexp nil t)
7138 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7139 (end (match-end 0)) ;; end of entire body
7141 (if (memq t (mapcar (lambda (overlay)
7142 (eq (overlay-get overlay 'invisible)
7143 'org-hide-block))
7144 (overlays-at start)))
7145 (if (or (not force) (eq force 'off))
7146 (mapc (lambda (ov)
7147 (when (member ov org-hide-block-overlays)
7148 (setq org-hide-block-overlays
7149 (delq ov org-hide-block-overlays)))
7150 (when (eq (overlay-get ov 'invisible)
7151 'org-hide-block)
7152 (delete-overlay ov)))
7153 (overlays-at start)))
7154 (setq ov (make-overlay start end))
7155 (overlay-put ov 'invisible 'org-hide-block)
7156 ;; make the block accessible to isearch
7157 (overlay-put
7158 ov 'isearch-open-invisible
7159 (lambda (ov)
7160 (when (member ov org-hide-block-overlays)
7161 (setq org-hide-block-overlays
7162 (delq ov org-hide-block-overlays)))
7163 (when (eq (overlay-get ov 'invisible)
7164 'org-hide-block)
7165 (delete-overlay ov))))
7166 (push ov org-hide-block-overlays)))
7167 (user-error "Not looking at a source block"))))
7169 ;; org-tab-after-check-for-cycling-hook
7170 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7171 ;; Remove overlays when changing major mode
7172 (add-hook 'org-mode-hook
7173 (lambda () (org-add-hook 'change-major-mode-hook
7174 'org-show-block-all 'append 'local)))
7176 ;;; Org-goto
7178 (defvar org-goto-window-configuration nil)
7179 (defvar org-goto-marker nil)
7180 (defvar org-goto-map)
7181 (defun org-goto-map ()
7182 "Set the keymap `org-goto'."
7183 (setq org-goto-map
7184 (let ((map (make-sparse-keymap)))
7185 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7186 mouse-drag-region universal-argument org-occur))
7187 cmd)
7188 (while (setq cmd (pop cmds))
7189 (substitute-key-definition cmd cmd map global-map)))
7190 (suppress-keymap map)
7191 (org-defkey map "\C-m" 'org-goto-ret)
7192 (org-defkey map [(return)] 'org-goto-ret)
7193 (org-defkey map [(left)] 'org-goto-left)
7194 (org-defkey map [(right)] 'org-goto-right)
7195 (org-defkey map [(control ?g)] 'org-goto-quit)
7196 (org-defkey map "\C-i" 'org-cycle)
7197 (org-defkey map [(tab)] 'org-cycle)
7198 (org-defkey map [(down)] 'outline-next-visible-heading)
7199 (org-defkey map [(up)] 'outline-previous-visible-heading)
7200 (if org-goto-auto-isearch
7201 (if (fboundp 'define-key-after)
7202 (define-key-after map [t] 'org-goto-local-auto-isearch)
7203 nil)
7204 (org-defkey map "q" 'org-goto-quit)
7205 (org-defkey map "n" 'outline-next-visible-heading)
7206 (org-defkey map "p" 'outline-previous-visible-heading)
7207 (org-defkey map "f" 'outline-forward-same-level)
7208 (org-defkey map "b" 'outline-backward-same-level)
7209 (org-defkey map "u" 'outline-up-heading))
7210 (org-defkey map "/" 'org-occur)
7211 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7212 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7213 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7214 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7215 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7216 map)))
7218 (defconst org-goto-help
7219 "Browse buffer copy, to find location or copy text.%s
7220 RET=jump to location C-g=quit and return to previous location
7221 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7223 (defvar org-goto-start-pos) ; dynamically scoped parameter
7225 (defun org-goto (&optional alternative-interface)
7226 "Look up a different location in the current file, keeping current visibility.
7228 When you want look-up or go to a different location in a
7229 document, the fastest way is often to fold the entire buffer and
7230 then dive into the tree. This method has the disadvantage, that
7231 the previous location will be folded, which may not be what you
7232 want.
7234 This command works around this by showing a copy of the current
7235 buffer in an indirect buffer, in overview mode. You can dive
7236 into the tree in that copy, use org-occur and incremental search
7237 to find a location. When pressing RET or `Q', the command
7238 returns to the original buffer in which the visibility is still
7239 unchanged. After RET it will also jump to the location selected
7240 in the indirect buffer and expose the headline hierarchy above.
7242 With a prefix argument, use the alternative interface: e.g. if
7243 `org-goto-interface' is 'outline use 'outline-path-completion."
7244 (interactive "P")
7245 (org-goto-map)
7246 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7247 (org-refile-use-outline-path t)
7248 (org-refile-target-verify-function nil)
7249 (interface
7250 (if (not alternative-interface)
7251 org-goto-interface
7252 (if (eq org-goto-interface 'outline)
7253 'outline-path-completion
7254 'outline)))
7255 (org-goto-start-pos (point))
7256 (selected-point
7257 (if (eq interface 'outline)
7258 (car (org-get-location (current-buffer) org-goto-help))
7259 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7260 (org-refile-check-position pa)
7261 (nth 3 pa)))))
7262 (if selected-point
7263 (progn
7264 (org-mark-ring-push org-goto-start-pos)
7265 (goto-char selected-point)
7266 (if (or (outline-invisible-p) (org-invisible-p2))
7267 (org-show-context 'org-goto)))
7268 (message "Quit"))))
7270 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7271 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7272 (defvar org-goto-local-auto-isearch-map) ; defined below
7274 (defun org-get-location (buf help)
7275 "Let the user select a location in the Org-mode buffer BUF.
7276 This function uses a recursive edit. It returns the selected position
7277 or nil."
7278 (org-no-popups
7279 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7280 (isearch-hide-immediately nil)
7281 (isearch-search-fun-function
7282 (lambda () 'org-goto-local-search-headings))
7283 (org-goto-selected-point org-goto-exit-command))
7284 (save-excursion
7285 (save-window-excursion
7286 (delete-other-windows)
7287 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7288 (org-pop-to-buffer-same-window
7289 (condition-case nil
7290 (make-indirect-buffer (current-buffer) "*org-goto*")
7291 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7292 (with-output-to-temp-buffer "*Org Help*"
7293 (princ (format help (if org-goto-auto-isearch
7294 " Just type for auto-isearch."
7295 " n/p/f/b/u to navigate, q to quit."))))
7296 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7297 (setq buffer-read-only nil)
7298 (let ((org-startup-truncated t)
7299 (org-startup-folded nil)
7300 (org-startup-align-all-tables nil))
7301 (org-mode)
7302 (org-overview))
7303 (setq buffer-read-only t)
7304 (if (and (boundp 'org-goto-start-pos)
7305 (integer-or-marker-p org-goto-start-pos))
7306 (let ((org-show-hierarchy-above t)
7307 (org-show-siblings t)
7308 (org-show-following-heading t))
7309 (goto-char org-goto-start-pos)
7310 (and (outline-invisible-p) (org-show-context)))
7311 (goto-char (point-min)))
7312 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7313 (message "Select location and press RET")
7314 (use-local-map org-goto-map)
7315 (recursive-edit)))
7316 (kill-buffer "*org-goto*")
7317 (cons org-goto-selected-point org-goto-exit-command))))
7319 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7320 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7321 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7322 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7324 (defun org-goto-local-search-headings (string bound noerror)
7325 "Search and make sure that any matches are in headlines."
7326 (catch 'return
7327 (while (if isearch-forward
7328 (search-forward string bound noerror)
7329 (search-backward string bound noerror))
7330 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7331 (and (member :headline context)
7332 (not (member :tags context))))
7333 (throw 'return (point))))))
7335 (defun org-goto-local-auto-isearch ()
7336 "Start isearch."
7337 (interactive)
7338 (goto-char (point-min))
7339 (let ((keys (this-command-keys)))
7340 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7341 (isearch-mode t)
7342 (isearch-process-search-char (string-to-char keys)))))
7344 (defun org-goto-ret (&optional arg)
7345 "Finish `org-goto' by going to the new location."
7346 (interactive "P")
7347 (setq org-goto-selected-point (point)
7348 org-goto-exit-command 'return)
7349 (throw 'exit nil))
7351 (defun org-goto-left ()
7352 "Finish `org-goto' by going to the new location."
7353 (interactive)
7354 (if (org-at-heading-p)
7355 (progn
7356 (beginning-of-line 1)
7357 (setq org-goto-selected-point (point)
7358 org-goto-exit-command 'left)
7359 (throw 'exit nil))
7360 (user-error "Not on a heading")))
7362 (defun org-goto-right ()
7363 "Finish `org-goto' by going to the new location."
7364 (interactive)
7365 (if (org-at-heading-p)
7366 (progn
7367 (setq org-goto-selected-point (point)
7368 org-goto-exit-command 'right)
7369 (throw 'exit nil))
7370 (user-error "Not on a heading")))
7372 (defun org-goto-quit ()
7373 "Finish `org-goto' without cursor motion."
7374 (interactive)
7375 (setq org-goto-selected-point nil)
7376 (setq org-goto-exit-command 'quit)
7377 (throw 'exit nil))
7379 ;;; Indirect buffer display of subtrees
7381 (defvar org-indirect-dedicated-frame nil
7382 "This is the frame being used for indirect tree display.")
7383 (defvar org-last-indirect-buffer nil)
7385 (defun org-tree-to-indirect-buffer (&optional arg)
7386 "Create indirect buffer and narrow it to current subtree.
7387 With a numerical prefix ARG, go up to this level and then take that tree.
7388 If ARG is negative, go up that many levels.
7390 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7391 indirect buffer previously made with this command, to avoid proliferation of
7392 indirect buffers. However, when you call the command with a \
7393 \\[universal-argument] prefix, or
7394 when `org-indirect-buffer-display' is `new-frame', the last buffer
7395 is kept so that you can work with several indirect buffers at the same time.
7396 If `org-indirect-buffer-display' is `dedicated-frame', the \
7397 \\[universal-argument] prefix also
7398 requests that a new frame be made for the new buffer, so that the dedicated
7399 frame is not changed."
7400 (interactive "P")
7401 (let ((cbuf (current-buffer))
7402 (cwin (selected-window))
7403 (pos (point))
7404 beg end level heading ibuf)
7405 (save-excursion
7406 (org-back-to-heading t)
7407 (when (numberp arg)
7408 (setq level (org-outline-level))
7409 (if (< arg 0) (setq arg (+ level arg)))
7410 (while (> (setq level (org-outline-level)) arg)
7411 (org-up-heading-safe)))
7412 (setq beg (point)
7413 heading (org-get-heading))
7414 (org-end-of-subtree t t)
7415 (if (org-at-heading-p) (backward-char 1))
7416 (setq end (point)))
7417 (if (and (buffer-live-p org-last-indirect-buffer)
7418 (not (eq org-indirect-buffer-display 'new-frame))
7419 (not arg))
7420 (kill-buffer org-last-indirect-buffer))
7421 (setq ibuf (org-get-indirect-buffer cbuf)
7422 org-last-indirect-buffer ibuf)
7423 (cond
7424 ((or (eq org-indirect-buffer-display 'new-frame)
7425 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7426 (select-frame (make-frame))
7427 (delete-other-windows)
7428 (org-pop-to-buffer-same-window ibuf)
7429 (org-set-frame-title heading))
7430 ((eq org-indirect-buffer-display 'dedicated-frame)
7431 (raise-frame
7432 (select-frame (or (and org-indirect-dedicated-frame
7433 (frame-live-p org-indirect-dedicated-frame)
7434 org-indirect-dedicated-frame)
7435 (setq org-indirect-dedicated-frame (make-frame)))))
7436 (delete-other-windows)
7437 (org-pop-to-buffer-same-window ibuf)
7438 (org-set-frame-title (concat "Indirect: " heading)))
7439 ((eq org-indirect-buffer-display 'current-window)
7440 (org-pop-to-buffer-same-window ibuf))
7441 ((eq org-indirect-buffer-display 'other-window)
7442 (pop-to-buffer ibuf))
7443 (t (error "Invalid value")))
7444 (if (featurep 'xemacs)
7445 (save-excursion (org-mode) (turn-on-font-lock)))
7446 (narrow-to-region beg end)
7447 (show-all)
7448 (goto-char pos)
7449 (run-hook-with-args 'org-cycle-hook 'all)
7450 (and (window-live-p cwin) (select-window cwin))))
7452 (defun org-get-indirect-buffer (&optional buffer)
7453 (setq buffer (or buffer (current-buffer)))
7454 (let ((n 1) (base (buffer-name buffer)) bname)
7455 (while (buffer-live-p
7456 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7457 (setq n (1+ n)))
7458 (condition-case nil
7459 (make-indirect-buffer buffer bname 'clone)
7460 (error (make-indirect-buffer buffer bname)))))
7462 (defun org-set-frame-title (title)
7463 "Set the title of the current frame to the string TITLE."
7464 ;; FIXME: how to name a single frame in XEmacs???
7465 (unless (featurep 'xemacs)
7466 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7468 ;;;; Structure editing
7470 ;;; Inserting headlines
7472 (defun org-previous-line-empty-p (&optional next)
7473 "Is the previous line a blank line?
7474 When NEXT is non-nil, check the next line instead."
7475 (save-excursion
7476 (and (not (bobp))
7477 (or (beginning-of-line (if next 2 0)) t)
7478 (save-match-data
7479 (looking-at "[ \t]*$")))))
7481 (defun org-insert-heading (&optional arg invisible-ok)
7482 "Insert a new heading or item with same depth at point.
7483 If point is in a plain list and ARG is nil, create a new list item.
7484 With one universal prefix argument, insert a heading even in lists.
7485 With two universal prefix arguments, insert the heading at the end
7486 of the parent subtree.
7488 If point is at the beginning of a headline, insert a sibling before
7489 the current headline. If point is not at the beginning, split the line
7490 and create a new headline with the text in the current line after point
7491 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7493 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7494 This is important for non-interactive uses of the command."
7495 (interactive "P")
7496 (cond
7497 ((or (= (buffer-size) 0)
7498 (and (not (save-excursion
7499 (and (ignore-errors (org-back-to-heading invisible-ok))
7500 (org-at-heading-p))))
7501 (or arg (not (org-in-item-p)))))
7502 (insert
7503 (if (org-previous-line-empty-p) "" "\n")
7504 (if (org-in-src-block-p) ",* " "* "))
7505 (run-hooks 'org-insert-heading-hook))
7506 ((or arg
7507 org-insert-heading-respect-content
7508 (not (org-insert-item
7509 (save-excursion
7510 (beginning-of-line)
7511 (looking-at org-list-full-item-re)
7512 (match-string 3)))))
7513 (let (begn endn)
7514 (when (org-buffer-narrowed-p)
7515 (setq begn (point-min) endn (point-max))
7516 (widen))
7517 (let* ((empty-line-p nil)
7518 (eops (equal arg '(16))) ; insert at end of parent subtree
7519 (org-insert-heading-respect-content
7520 (or (not (null arg)) org-insert-heading-respect-content))
7521 (level nil)
7522 (on-heading (org-at-heading-p))
7523 (on-empty-line
7524 (save-excursion (beginning-of-line 1) (looking-at "^\\s-*$")))
7525 (head (save-excursion
7526 (condition-case nil
7527 (progn
7528 (org-back-to-heading invisible-ok)
7529 (when (and (not on-heading)
7530 (featurep 'org-inlinetask)
7531 (integerp org-inlinetask-min-level)
7532 (>= (length (match-string 0))
7533 org-inlinetask-min-level))
7534 ;; Find a heading level before the inline task
7535 (while (and (setq level (org-up-heading-safe))
7536 (>= level org-inlinetask-min-level)))
7537 (if (org-at-heading-p)
7538 (org-back-to-heading invisible-ok)
7539 (error "This should not happen")))
7540 (unless (and (save-excursion
7541 (save-match-data
7542 (org-backward-heading-same-level 1 invisible-ok))
7543 (= (point) (match-beginning 0)))
7544 (not (org-previous-line-empty-p t)))
7545 (setq empty-line-p (org-previous-line-empty-p)))
7546 (match-string 0))
7547 (error "* "))))
7548 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7549 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7550 pos hide-previous previous-pos)
7551 (if ;; At the beginning of a heading, open a new line for insertiong
7552 (and (bolp) (org-at-heading-p)
7553 (not eops)
7554 (or (bobp)
7555 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7556 (open-line (if blank 2 1))
7557 (save-excursion
7558 (setq previous-pos (point-at-bol))
7559 (end-of-line)
7560 (setq hide-previous (outline-invisible-p)))
7561 (and org-insert-heading-respect-content
7562 (save-excursion
7563 (while (outline-invisible-p)
7564 (org-show-subtree)
7565 (org-up-heading-safe))))
7566 (let ((split
7567 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7568 (save-excursion
7569 (let ((p (point)))
7570 (goto-char (point-at-bol))
7571 (and (looking-at org-complex-heading-regexp)
7572 (match-beginning 4)
7573 (> p (match-beginning 4)))))))
7574 tags pos)
7575 (cond
7576 ;; Insert a new line, possibly at end of parent subtree
7577 ((and (not arg) (not on-heading) (not on-empty-line)
7578 (not (save-excursion
7579 (beginning-of-line 1)
7580 (looking-at org-list-full-item-re))))
7581 (beginning-of-line 1))
7582 (org-insert-heading-respect-content
7583 (if (not eops)
7584 (progn
7585 (org-end-of-subtree nil t)
7586 (and (looking-at "^\\*") (backward-char 1))
7587 (while (and (not (bobp))
7588 ;; Don't delete spaces in empty headlines
7589 (not (looking-back org-outline-regexp))
7590 (member (char-before) '(?\ ?\t ?\n)))
7591 (backward-delete-char 1)))
7592 (let ((p (point)))
7593 (org-up-heading-safe)
7594 (if (= p (point))
7595 (goto-char (point-max))
7596 (org-end-of-subtree nil t))))
7597 (when (featurep 'org-inlinetask)
7598 (while (and (not (eobp))
7599 (looking-at "\\(\\*+\\)[ \t]+")
7600 (>= (length (match-string 1))
7601 org-inlinetask-min-level))
7602 (org-end-of-subtree nil t)))
7603 (or (bolp) (newline))
7604 (or (org-previous-line-empty-p)
7605 (and blank (newline)))
7606 (if (or empty-line-p eops) (open-line 1)))
7607 ;; Insert a headling containing text after point
7608 ((org-at-heading-p)
7609 (when hide-previous
7610 (show-children)
7611 (org-show-entry))
7612 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7613 (setq tags (and (match-end 2) (match-string 2)))
7614 (and (match-end 1)
7615 (delete-region (match-beginning 1) (match-end 1)))
7616 (setq pos (point-at-bol))
7617 (or split (end-of-line 1))
7618 (delete-horizontal-space)
7619 (if (string-match "\\`\\*+\\'"
7620 (buffer-substring (point-at-bol) (point)))
7621 (insert " "))
7622 (newline (if blank 2 1))
7623 (when tags
7624 (save-excursion
7625 (goto-char pos)
7626 (end-of-line 1)
7627 (insert " " tags)
7628 (org-set-tags nil 'align))))
7630 (or split (end-of-line 1))
7631 (newline (cond ((and blank (not on-empty-line)) 2)
7632 (blank 1)
7633 (on-empty-line 0) (t 1)))))))
7634 (insert head) (just-one-space)
7635 (setq pos (point))
7636 (end-of-line 1)
7637 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7638 (when (and org-insert-heading-respect-content hide-previous)
7639 (save-excursion
7640 (goto-char previous-pos)
7641 (hide-subtree)))
7642 (when (and begn endn)
7643 (narrow-to-region (min (point) begn) (max (point) endn)))
7644 (run-hooks 'org-insert-heading-hook))))))
7646 (defun org-get-heading (&optional no-tags no-todo)
7647 "Return the heading of the current entry, without the stars.
7648 When NO-TAGS is non-nil, don't include tags.
7649 When NO-TODO is non-nil, don't include TODO keywords."
7650 (save-excursion
7651 (org-back-to-heading t)
7652 (cond
7653 ((and no-tags no-todo)
7654 (looking-at org-complex-heading-regexp)
7655 (match-string 4))
7656 (no-tags
7657 (looking-at (concat org-outline-regexp
7658 "\\(.*?\\)"
7659 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7660 (match-string 1))
7661 (no-todo
7662 (looking-at org-todo-line-regexp)
7663 (match-string 3))
7664 (t (looking-at org-heading-regexp)
7665 (match-string 2)))))
7667 (defvar orgstruct-mode) ; defined below
7669 (defun org-heading-components ()
7670 "Return the components of the current heading.
7671 This is a list with the following elements:
7672 - the level as an integer
7673 - the reduced level, different if `org-odd-levels-only' is set.
7674 - the TODO keyword, or nil
7675 - the priority character, like ?A, or nil if no priority is given
7676 - the headline text itself, or the tags string if no headline text
7677 - the tags string, or nil."
7678 (save-excursion
7679 (org-back-to-heading t)
7680 (if (let (case-fold-search)
7681 (looking-at
7682 (if orgstruct-mode
7683 org-heading-regexp
7684 org-complex-heading-regexp)))
7685 (if orgstruct-mode
7686 (list (length (match-string 1))
7687 (org-reduced-level (length (match-string 1)))
7690 (match-string 2)
7691 nil)
7692 (list (length (match-string 1))
7693 (org-reduced-level (length (match-string 1)))
7694 (org-match-string-no-properties 2)
7695 (and (match-end 3) (aref (match-string 3) 2))
7696 (org-match-string-no-properties 4)
7697 (org-match-string-no-properties 5))))))
7699 (defun org-get-entry ()
7700 "Get the entry text, after heading, entire subtree."
7701 (save-excursion
7702 (org-back-to-heading t)
7703 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7705 (defun org-insert-heading-after-current ()
7706 "Insert a new heading with same level as current, after current subtree."
7707 (interactive)
7708 (org-back-to-heading)
7709 (org-insert-heading)
7710 (org-move-subtree-down)
7711 (end-of-line 1))
7713 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7714 "Insert heading with `org-insert-heading-respect-content' set to t."
7715 (interactive "P")
7716 (let ((org-insert-heading-respect-content t))
7717 (org-insert-heading arg invisible-ok)))
7719 (defun org-insert-todo-heading-respect-content (&optional force-state)
7720 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7721 (interactive "P")
7722 (let ((org-insert-heading-respect-content t))
7723 (org-insert-todo-heading force-state t)))
7725 (defun org-insert-todo-heading (arg &optional force-heading)
7726 "Insert a new heading with the same level and TODO state as current heading.
7727 If the heading has no TODO state, or if the state is DONE, use the first
7728 state (TODO by default). Also one prefix arg, force first state. With two
7729 prefix args, force inserting at the end of the parent subtree."
7730 (interactive "P")
7731 (when (or force-heading (not (org-insert-item 'checkbox)))
7732 (org-insert-heading (or (and (equal arg '(16)) '(16))
7733 force-heading))
7734 (save-excursion
7735 (org-back-to-heading)
7736 (outline-previous-heading)
7737 (looking-at org-todo-line-regexp))
7738 (let*
7739 ((new-mark-x
7740 (if (or arg
7741 (not (match-beginning 2))
7742 (member (match-string 2) org-done-keywords))
7743 (car org-todo-keywords-1)
7744 (match-string 2)))
7745 (new-mark
7747 (run-hook-with-args-until-success
7748 'org-todo-get-default-hook new-mark-x nil)
7749 new-mark-x)))
7750 (beginning-of-line 1)
7751 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7752 (if org-treat-insert-todo-heading-as-state-change
7753 (org-todo new-mark)
7754 (insert new-mark " "))))
7755 (when org-provide-todo-statistics
7756 (org-update-parent-todo-statistics))))
7758 (defun org-insert-subheading (arg)
7759 "Insert a new subheading and demote it.
7760 Works for outline headings and for plain lists alike."
7761 (interactive "P")
7762 (org-insert-heading arg)
7763 (cond
7764 ((org-at-heading-p) (org-do-demote))
7765 ((org-at-item-p) (org-indent-item))))
7767 (defun org-insert-todo-subheading (arg)
7768 "Insert a new subheading with TODO keyword or checkbox and demote it.
7769 Works for outline headings and for plain lists alike."
7770 (interactive "P")
7771 (org-insert-todo-heading arg)
7772 (cond
7773 ((org-at-heading-p) (org-do-demote))
7774 ((org-at-item-p) (org-indent-item))))
7776 ;;; Promotion and Demotion
7778 (defvar org-after-demote-entry-hook nil
7779 "Hook run after an entry has been demoted.
7780 The cursor will be at the beginning of the entry.
7781 When a subtree is being demoted, the hook will be called for each node.")
7783 (defvar org-after-promote-entry-hook nil
7784 "Hook run after an entry has been promoted.
7785 The cursor will be at the beginning of the entry.
7786 When a subtree is being promoted, the hook will be called for each node.")
7788 (defun org-promote-subtree ()
7789 "Promote the entire subtree.
7790 See also `org-promote'."
7791 (interactive)
7792 (save-excursion
7793 (org-with-limited-levels (org-map-tree 'org-promote)))
7794 (org-fix-position-after-promote))
7796 (defun org-demote-subtree ()
7797 "Demote the entire subtree. See `org-demote'.
7798 See also `org-promote'."
7799 (interactive)
7800 (save-excursion
7801 (org-with-limited-levels (org-map-tree 'org-demote)))
7802 (org-fix-position-after-promote))
7805 (defun org-do-promote ()
7806 "Promote the current heading higher up the tree.
7807 If the region is active in `transient-mark-mode', promote all headings
7808 in the region."
7809 (interactive)
7810 (save-excursion
7811 (if (org-region-active-p)
7812 (org-map-region 'org-promote (region-beginning) (region-end))
7813 (org-promote)))
7814 (org-fix-position-after-promote))
7816 (defun org-do-demote ()
7817 "Demote the current heading lower down the tree.
7818 If the region is active in `transient-mark-mode', demote all headings
7819 in the region."
7820 (interactive)
7821 (save-excursion
7822 (if (org-region-active-p)
7823 (org-map-region 'org-demote (region-beginning) (region-end))
7824 (org-demote)))
7825 (org-fix-position-after-promote))
7827 (defun org-fix-position-after-promote ()
7828 "Make sure that after pro/demotion cursor position is right."
7829 (let ((pos (point)))
7830 (when (save-excursion
7831 (beginning-of-line 1)
7832 (looking-at org-todo-line-regexp)
7833 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7834 (cond ((eobp) (insert " "))
7835 ((eolp) (insert " "))
7836 ((equal (char-after) ?\ ) (forward-char 1))))))
7838 (defun org-current-level ()
7839 "Return the level of the current entry, or nil if before the first headline.
7840 The level is the number of stars at the beginning of the headline."
7841 (save-excursion
7842 (org-with-limited-levels
7843 (if (ignore-errors (org-back-to-heading t))
7844 (funcall outline-level)))))
7846 (defun org-get-previous-line-level ()
7847 "Return the outline depth of the last headline before the current line.
7848 Returns 0 for the first headline in the buffer, and nil if before the
7849 first headline."
7850 (let ((current-level (org-current-level))
7851 (prev-level (when (> (line-number-at-pos) 1)
7852 (save-excursion
7853 (beginning-of-line 0)
7854 (org-current-level)))))
7855 (cond ((null current-level) nil) ; Before first headline
7856 ((null prev-level) 0) ; At first headline
7857 (prev-level))))
7859 (defun org-reduced-level (l)
7860 "Compute the effective level of a heading.
7861 This takes into account the setting of `org-odd-levels-only'."
7862 (cond
7863 ((zerop l) 0)
7864 (org-odd-levels-only (1+ (floor (/ l 2))))
7865 (t l)))
7867 (defun org-level-increment ()
7868 "Return the number of stars that will be added or removed at a
7869 time to headlines when structure editing, based on the value of
7870 `org-odd-levels-only'."
7871 (if org-odd-levels-only 2 1))
7873 (defun org-get-valid-level (level &optional change)
7874 "Rectify a level change under the influence of `org-odd-levels-only'
7875 LEVEL is a current level, CHANGE is by how much the level should be
7876 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7877 even level numbers will become the next higher odd number."
7878 (if org-odd-levels-only
7879 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7880 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7881 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7882 (max 1 (+ level (or change 0)))))
7884 (if (boundp 'define-obsolete-function-alias)
7885 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7886 (define-obsolete-function-alias 'org-get-legal-level
7887 'org-get-valid-level)
7888 (define-obsolete-function-alias 'org-get-legal-level
7889 'org-get-valid-level "23.1")))
7891 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7892 ;; ̀org-with-limited-levels'
7893 (defun org-promote ()
7894 "Promote the current heading higher up the tree.
7895 If the region is active in `transient-mark-mode', promote all headings
7896 in the region."
7897 (org-back-to-heading t)
7898 (let* ((level (save-match-data (funcall outline-level)))
7899 (after-change-functions (remove 'flyspell-after-change-function
7900 after-change-functions))
7901 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7902 (diff (abs (- level (length up-head) -1))))
7903 (cond ((and (= level 1) org-called-with-limited-levels
7904 org-allow-promoting-top-level-subtree)
7905 (replace-match "# " nil t))
7906 ((= level 1)
7907 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7908 (t (replace-match up-head nil t)))
7909 ;; Fixup tag positioning
7910 (unless (= level 1)
7911 (and org-auto-align-tags (org-set-tags nil t))
7912 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7913 (run-hooks 'org-after-promote-entry-hook)))
7915 (defun org-demote ()
7916 "Demote the current heading lower down the tree.
7917 If the region is active in `transient-mark-mode', demote all headings
7918 in the region."
7919 (org-back-to-heading t)
7920 (let* ((level (save-match-data (funcall outline-level)))
7921 (after-change-functions (remove 'flyspell-after-change-function
7922 after-change-functions))
7923 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7924 (diff (abs (- level (length down-head) -1))))
7925 (replace-match down-head nil t)
7926 ;; Fixup tag positioning
7927 (and org-auto-align-tags (org-set-tags nil t))
7928 (if org-adapt-indentation (org-fixup-indentation diff))
7929 (run-hooks 'org-after-demote-entry-hook)))
7931 (defun org-cycle-level ()
7932 "Cycle the level of an empty headline through possible states.
7933 This goes first to child, then to parent, level, then up the hierarchy.
7934 After top level, it switches back to sibling level."
7935 (interactive)
7936 (let ((org-adapt-indentation nil))
7937 (when (org-point-at-end-of-empty-headline)
7938 (setq this-command 'org-cycle-level) ; Only needed for caching
7939 (let ((cur-level (org-current-level))
7940 (prev-level (org-get-previous-line-level)))
7941 (cond
7942 ;; If first headline in file, promote to top-level.
7943 ((= prev-level 0)
7944 (loop repeat (/ (- cur-level 1) (org-level-increment))
7945 do (org-do-promote)))
7946 ;; If same level as prev, demote one.
7947 ((= prev-level cur-level)
7948 (org-do-demote))
7949 ;; If parent is top-level, promote to top level if not already.
7950 ((= prev-level 1)
7951 (loop repeat (/ (- cur-level 1) (org-level-increment))
7952 do (org-do-promote)))
7953 ;; If top-level, return to prev-level.
7954 ((= cur-level 1)
7955 (loop repeat (/ (- prev-level 1) (org-level-increment))
7956 do (org-do-demote)))
7957 ;; If less than prev-level, promote one.
7958 ((< cur-level prev-level)
7959 (org-do-promote))
7960 ;; If deeper than prev-level, promote until higher than
7961 ;; prev-level.
7962 ((> cur-level prev-level)
7963 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7964 do (org-do-promote))))
7965 t))))
7967 (defun org-map-tree (fun)
7968 "Call FUN for every heading underneath the current one."
7969 (org-back-to-heading)
7970 (let ((level (funcall outline-level)))
7971 (save-excursion
7972 (funcall fun)
7973 (while (and (progn
7974 (outline-next-heading)
7975 (> (funcall outline-level) level))
7976 (not (eobp)))
7977 (funcall fun)))))
7979 (defun org-map-region (fun beg end)
7980 "Call FUN for every heading between BEG and END."
7981 (let ((org-ignore-region t))
7982 (save-excursion
7983 (setq end (copy-marker end))
7984 (goto-char beg)
7985 (if (and (re-search-forward org-outline-regexp-bol nil t)
7986 (< (point) end))
7987 (funcall fun))
7988 (while (and (progn
7989 (outline-next-heading)
7990 (< (point) end))
7991 (not (eobp)))
7992 (funcall fun)))))
7994 (defvar org-property-end-re) ; silence byte-compiler
7995 (defun org-fixup-indentation (diff)
7996 "Change the indentation in the current entry by DIFF.
7997 However, if any line in the current entry has no indentation, or if it
7998 would end up with no indentation after the change, nothing at all is done."
7999 (save-excursion
8000 (let ((end (save-excursion (outline-next-heading)
8001 (point-marker)))
8002 (prohibit (if (> diff 0)
8003 "^\\S-"
8004 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8005 col)
8006 (unless (save-excursion (end-of-line 1)
8007 (re-search-forward prohibit end t))
8008 (while (and (< (point) end)
8009 (re-search-forward "^[ \t]+" end t))
8010 (goto-char (match-end 0))
8011 (setq col (current-column))
8012 (if (< diff 0) (replace-match ""))
8013 (org-indent-to-column (+ diff col))))
8014 (move-marker end nil))))
8016 (defun org-convert-to-odd-levels ()
8017 "Convert an org-mode file with all levels allowed to one with odd levels.
8018 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8019 level 5 etc."
8020 (interactive)
8021 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8022 (let ((outline-level 'org-outline-level)
8023 (org-odd-levels-only nil) n)
8024 (save-excursion
8025 (goto-char (point-min))
8026 (while (re-search-forward "^\\*\\*+ " nil t)
8027 (setq n (- (length (match-string 0)) 2))
8028 (while (>= (setq n (1- n)) 0)
8029 (org-demote))
8030 (end-of-line 1))))))
8032 (defun org-convert-to-oddeven-levels ()
8033 "Convert an org-mode file with only odd levels to one with odd/even levels.
8034 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8035 file contains a section with an even level, conversion would
8036 destroy the structure of the file. An error is signaled in this
8037 case."
8038 (interactive)
8039 (goto-char (point-min))
8040 ;; First check if there are no even levels
8041 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8042 (org-show-context t)
8043 (error "Not all levels are odd in this file. Conversion not possible"))
8044 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8045 (let ((outline-regexp org-outline-regexp)
8046 (outline-level 'org-outline-level)
8047 (org-odd-levels-only nil) n)
8048 (save-excursion
8049 (goto-char (point-min))
8050 (while (re-search-forward "^\\*\\*+ " nil t)
8051 (setq n (/ (1- (length (match-string 0))) 2))
8052 (while (>= (setq n (1- n)) 0)
8053 (org-promote))
8054 (end-of-line 1))))))
8056 (defun org-tr-level (n)
8057 "Make N odd if required."
8058 (if org-odd-levels-only (1+ (/ n 2)) n))
8060 ;;; Vertical tree motion, cutting and pasting of subtrees
8062 (defun org-move-subtree-up (&optional arg)
8063 "Move the current subtree up past ARG headlines of the same level."
8064 (interactive "p")
8065 (org-move-subtree-down (- (prefix-numeric-value arg))))
8067 (defun org-move-subtree-down (&optional arg)
8068 "Move the current subtree down past ARG headlines of the same level."
8069 (interactive "p")
8070 (setq arg (prefix-numeric-value arg))
8071 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8072 'org-get-last-sibling))
8073 (ins-point (make-marker))
8074 (cnt (abs arg))
8075 (col (current-column))
8076 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8077 ;; Select the tree
8078 (org-back-to-heading)
8079 (setq beg0 (point))
8080 (save-excursion
8081 (setq ne-beg (org-back-over-empty-lines))
8082 (setq beg (point)))
8083 (save-match-data
8084 (save-excursion (outline-end-of-heading)
8085 (setq folded (outline-invisible-p)))
8086 (outline-end-of-subtree))
8087 (outline-next-heading)
8088 (setq ne-end (org-back-over-empty-lines))
8089 (setq end (point))
8090 (goto-char beg0)
8091 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8092 ;; include less whitespace
8093 (save-excursion
8094 (goto-char beg)
8095 (forward-line (- ne-beg ne-end))
8096 (setq beg (point))))
8097 ;; Find insertion point, with error handling
8098 (while (> cnt 0)
8099 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8100 (progn (goto-char beg0)
8101 (user-error "Cannot move past superior level or buffer limit")))
8102 (setq cnt (1- cnt)))
8103 (if (> arg 0)
8104 ;; Moving forward - still need to move over subtree
8105 (progn (org-end-of-subtree t t)
8106 (save-excursion
8107 (org-back-over-empty-lines)
8108 (or (bolp) (newline)))))
8109 (setq ne-ins (org-back-over-empty-lines))
8110 (move-marker ins-point (point))
8111 (setq txt (buffer-substring beg end))
8112 (org-save-markers-in-region beg end)
8113 (delete-region beg end)
8114 (org-remove-empty-overlays-at beg)
8115 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8116 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8117 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8118 (let ((bbb (point)))
8119 (insert-before-markers txt)
8120 (org-reinstall-markers-in-region bbb)
8121 (move-marker ins-point bbb))
8122 (or (bolp) (insert "\n"))
8123 (setq ins-end (point))
8124 (goto-char ins-point)
8125 (org-skip-whitespace)
8126 (when (and (< arg 0)
8127 (org-first-sibling-p)
8128 (> ne-ins ne-beg))
8129 ;; Move whitespace back to beginning
8130 (save-excursion
8131 (goto-char ins-end)
8132 (let ((kill-whole-line t))
8133 (kill-line (- ne-ins ne-beg)) (point)))
8134 (insert (make-string (- ne-ins ne-beg) ?\n)))
8135 (move-marker ins-point nil)
8136 (if folded
8137 (hide-subtree)
8138 (org-show-entry)
8139 (show-children)
8140 (org-cycle-hide-drawers 'children))
8141 (org-clean-visibility-after-subtree-move)
8142 ;; move back to the initial column we were at
8143 (move-to-column col)))
8145 (defvar org-subtree-clip ""
8146 "Clipboard for cut and paste of subtrees.
8147 This is actually only a copy of the kill, because we use the normal kill
8148 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8150 (defvar org-subtree-clip-folded nil
8151 "Was the last copied subtree folded?
8152 This is used to fold the tree back after pasting.")
8154 (defun org-cut-subtree (&optional n)
8155 "Cut the current subtree into the clipboard.
8156 With prefix arg N, cut this many sequential subtrees.
8157 This is a short-hand for marking the subtree and then cutting it."
8158 (interactive "p")
8159 (org-copy-subtree n 'cut))
8161 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8162 "Cut the current subtree into the clipboard.
8163 With prefix arg N, cut this many sequential subtrees.
8164 This is a short-hand for marking the subtree and then copying it.
8165 If CUT is non-nil, actually cut the subtree.
8166 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8167 of some markers in the region, even if CUT is non-nil. This is
8168 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8169 (interactive "p")
8170 (let (beg end folded (beg0 (point)))
8171 (if (org-called-interactively-p 'any)
8172 (org-back-to-heading nil) ; take what looks like a subtree
8173 (org-back-to-heading t)) ; take what is really there
8174 (setq beg (point))
8175 (skip-chars-forward " \t\r\n")
8176 (save-match-data
8177 (if nosubtrees
8178 (outline-next-heading)
8179 (save-excursion (outline-end-of-heading)
8180 (setq folded (outline-invisible-p)))
8181 (condition-case nil
8182 (org-forward-heading-same-level (1- n) t)
8183 (error nil))
8184 (org-end-of-subtree t t)))
8185 (setq end (point))
8186 (goto-char beg0)
8187 (when (> end beg)
8188 (setq org-subtree-clip-folded folded)
8189 (when (or cut force-store-markers)
8190 (org-save-markers-in-region beg end))
8191 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8192 (setq org-subtree-clip (current-kill 0))
8193 (message "%s: Subtree(s) with %d characters"
8194 (if cut "Cut" "Copied")
8195 (length org-subtree-clip)))))
8197 (defun org-paste-subtree (&optional level tree for-yank)
8198 "Paste the clipboard as a subtree, with modification of headline level.
8199 The entire subtree is promoted or demoted in order to match a new headline
8200 level.
8202 If the cursor is at the beginning of a headline, the same level as
8203 that headline is used to paste the tree.
8205 If not, the new level is derived from the *visible* headings
8206 before and after the insertion point, and taken to be the inferior headline
8207 level of the two. So if the previous visible heading is level 3 and the
8208 next is level 4 (or vice versa), level 4 will be used for insertion.
8209 This makes sure that the subtree remains an independent subtree and does
8210 not swallow low level entries.
8212 You can also force a different level, either by using a numeric prefix
8213 argument, or by inserting the heading marker by hand. For example, if the
8214 cursor is after \"*****\", then the tree will be shifted to level 5.
8216 If optional TREE is given, use this text instead of the kill ring.
8218 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8219 move back over whitespace before inserting, and move point to the end of
8220 the inserted text when done."
8221 (interactive "P")
8222 (setq tree (or tree (and kill-ring (current-kill 0))))
8223 (unless (org-kill-is-subtree-p tree)
8224 (user-error "%s"
8225 (substitute-command-keys
8226 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8227 (org-with-limited-levels
8228 (let* ((visp (not (outline-invisible-p)))
8229 (txt tree)
8230 (^re_ "\\(\\*+\\)[ \t]*")
8231 (old-level (if (string-match org-outline-regexp-bol txt)
8232 (- (match-end 0) (match-beginning 0) 1)
8233 -1))
8234 (force-level (cond (level (prefix-numeric-value level))
8235 ((and (looking-at "[ \t]*$")
8236 (string-match
8237 "^\\*+$" (buffer-substring
8238 (point-at-bol) (point))))
8239 (- (match-end 1) (match-beginning 1)))
8240 ((and (bolp)
8241 (looking-at org-outline-regexp))
8242 (- (match-end 0) (point) 1))))
8243 (previous-level (save-excursion
8244 (condition-case nil
8245 (progn
8246 (outline-previous-visible-heading 1)
8247 (if (looking-at ^re_)
8248 (- (match-end 0) (match-beginning 0) 1)
8250 (error 1))))
8251 (next-level (save-excursion
8252 (condition-case nil
8253 (progn
8254 (or (looking-at org-outline-regexp)
8255 (outline-next-visible-heading 1))
8256 (if (looking-at ^re_)
8257 (- (match-end 0) (match-beginning 0) 1)
8259 (error 1))))
8260 (new-level (or force-level (max previous-level next-level)))
8261 (shift (if (or (= old-level -1)
8262 (= new-level -1)
8263 (= old-level new-level))
8265 (- new-level old-level)))
8266 (delta (if (> shift 0) -1 1))
8267 (func (if (> shift 0) 'org-demote 'org-promote))
8268 (org-odd-levels-only nil)
8269 beg end newend)
8270 ;; Remove the forced level indicator
8271 (if force-level
8272 (delete-region (point-at-bol) (point)))
8273 ;; Paste
8274 (beginning-of-line (if (bolp) 1 2))
8275 (setq beg (point))
8276 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8277 (insert-before-markers txt)
8278 (unless (string-match "\n\\'" txt) (insert "\n"))
8279 (setq newend (point))
8280 (org-reinstall-markers-in-region beg)
8281 (setq end (point))
8282 (goto-char beg)
8283 (skip-chars-forward " \t\n\r")
8284 (setq beg (point))
8285 (if (and (outline-invisible-p) visp)
8286 (save-excursion (outline-show-heading)))
8287 ;; Shift if necessary
8288 (unless (= shift 0)
8289 (save-restriction
8290 (narrow-to-region beg end)
8291 (while (not (= shift 0))
8292 (org-map-region func (point-min) (point-max))
8293 (setq shift (+ delta shift)))
8294 (goto-char (point-min))
8295 (setq newend (point-max))))
8296 (when (or (org-called-interactively-p 'interactive) for-yank)
8297 (message "Clipboard pasted as level %d subtree" new-level))
8298 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8299 kill-ring
8300 (eq org-subtree-clip (current-kill 0))
8301 org-subtree-clip-folded)
8302 ;; The tree was folded before it was killed/copied
8303 (hide-subtree))
8304 (and for-yank (goto-char newend)))))
8306 (defun org-kill-is-subtree-p (&optional txt)
8307 "Check if the current kill is an outline subtree, or a set of trees.
8308 Returns nil if kill does not start with a headline, or if the first
8309 headline level is not the largest headline level in the tree.
8310 So this will actually accept several entries of equal levels as well,
8311 which is OK for `org-paste-subtree'.
8312 If optional TXT is given, check this string instead of the current kill."
8313 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8314 (re (org-get-limited-outline-regexp))
8315 (^re (concat "^" re))
8316 (start-level (and kill
8317 (string-match
8318 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8319 kill)
8320 (- (match-end 2) (match-beginning 2) 1)))
8321 (start (1+ (or (match-beginning 2) -1))))
8322 (if (not start-level)
8323 (progn
8324 nil) ;; does not even start with a heading
8325 (catch 'exit
8326 (while (setq start (string-match ^re kill (1+ start)))
8327 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8328 (throw 'exit nil)))
8329 t))))
8331 (defvar org-markers-to-move nil
8332 "Markers that should be moved with a cut-and-paste operation.
8333 Those markers are stored together with their positions relative to
8334 the start of the region.")
8336 (defun org-save-markers-in-region (beg end)
8337 "Check markers in region.
8338 If these markers are between BEG and END, record their position relative
8339 to BEG, so that after moving the block of text, we can put the markers back
8340 into place.
8341 This function gets called just before an entry or tree gets cut from the
8342 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8343 called immediately, to move the markers with the entries."
8344 (setq org-markers-to-move nil)
8345 (when (featurep 'org-clock)
8346 (org-clock-save-markers-for-cut-and-paste beg end))
8347 (when (featurep 'org-agenda)
8348 (org-agenda-save-markers-for-cut-and-paste beg end)))
8350 (defun org-check-and-save-marker (marker beg end)
8351 "Check if MARKER is between BEG and END.
8352 If yes, remember the marker and the distance to BEG."
8353 (when (and (marker-buffer marker)
8354 (equal (marker-buffer marker) (current-buffer)))
8355 (if (and (>= marker beg) (< marker end))
8356 (push (cons marker (- marker beg)) org-markers-to-move))))
8358 (defun org-reinstall-markers-in-region (beg)
8359 "Move all remembered markers to their position relative to BEG."
8360 (mapc (lambda (x)
8361 (move-marker (car x) (+ beg (cdr x))))
8362 org-markers-to-move)
8363 (setq org-markers-to-move nil))
8365 (defun org-narrow-to-subtree ()
8366 "Narrow buffer to the current subtree."
8367 (interactive)
8368 (save-excursion
8369 (save-match-data
8370 (org-with-limited-levels
8371 (narrow-to-region
8372 (progn (org-back-to-heading t) (point))
8373 (progn (org-end-of-subtree t t)
8374 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8375 (point)))))))
8377 (defun org-narrow-to-block ()
8378 "Narrow buffer to the current block."
8379 (interactive)
8380 (let* ((case-fold-search t)
8381 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8382 "^[ \t]*#\\+end_.*")))
8383 (if blockp
8384 (narrow-to-region (car blockp) (cdr blockp))
8385 (user-error "Not in a block"))))
8387 (eval-when-compile
8388 (defvar org-property-drawer-re))
8390 (defvar org-property-start-re) ;; defined below
8391 (defun org-clone-subtree-with-time-shift (n &optional shift)
8392 "Clone the task (subtree) at point N times.
8393 The clones will be inserted as siblings.
8395 In interactive use, the user will be prompted for the number of
8396 clones to be produced. When called with a universal prefix argument
8397 and if the entry has a timestamp, the user will also be prompted for
8398 a time shift, which may be a repeater as used in time stamps, for
8399 example `+3d'.
8401 When a valid repeater is given and the entry contains any time
8402 stamps, the clones will become a sequence in time, with time
8403 stamps in the subtree shifted for each clone produced. If SHIFT
8404 is nil or the empty string, time stamps will be left alone. The
8405 ID property of the original subtree is removed.
8407 If the original subtree did contain time stamps with a repeater,
8408 the following will happen:
8409 - the repeater will be removed in each clone
8410 - an additional clone will be produced, with the current, unshifted
8411 date(s) in the entry.
8412 - the original entry will be placed *after* all the clones, with
8413 repeater intact.
8414 - the start days in the repeater in the original entry will be shifted
8415 to past the last clone.
8416 In this way you can spell out a number of instances of a repeating task,
8417 and still retain the repeater to cover future instances of the task."
8418 (interactive "nNumber of clones to produce: ")
8419 (let ((shift
8420 (or shift
8421 (if (and (equal current-prefix-arg '(4))
8422 (save-excursion
8423 (re-search-forward org-ts-regexp-both
8424 (save-excursion
8425 (org-end-of-subtree t)
8426 (point)) t)))
8427 (read-from-minibuffer
8428 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8429 ""))) ;; No time shift
8430 (n-no-remove -1)
8431 (drawer-re org-drawer-regexp)
8432 beg end template task idprop
8433 shift-n shift-what doshift nmin nmax)
8434 (if (not (and (integerp n) (> n 0)))
8435 (error "Invalid number of replications %s" n))
8436 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8437 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8438 shift)))
8439 (error "Invalid shift specification %s" shift))
8440 (when doshift
8441 (setq shift-n (string-to-number (match-string 1 shift))
8442 shift-what (cdr (assoc (match-string 2 shift)
8443 '(("d" . day) ("w" . week)
8444 ("m" . month) ("y" . year))))))
8445 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8446 (setq nmin 1 nmax n)
8447 (org-back-to-heading t)
8448 (setq beg (point))
8449 (setq idprop (org-entry-get nil "ID"))
8450 (org-end-of-subtree t t)
8451 (or (bolp) (insert "\n"))
8452 (setq end (point))
8453 (setq template (buffer-substring beg end))
8454 (when (and doshift
8455 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8456 (delete-region beg end)
8457 (setq end beg)
8458 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8459 (goto-char end)
8460 (loop for n from nmin to nmax do
8461 ;; prepare clone
8462 (with-temp-buffer
8463 (insert template)
8464 (org-mode)
8465 (goto-char (point-min))
8466 (org-show-subtree)
8467 (and idprop (if org-clone-delete-id
8468 (org-entry-delete nil "ID")
8469 (org-id-get-create t)))
8470 (unless (= n 0)
8471 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8472 (kill-whole-line))
8473 (goto-char (point-min))
8474 (while (re-search-forward drawer-re nil t)
8475 (mapc (lambda (d)
8476 (org-remove-empty-drawer-at d (point))) org-drawers)))
8477 (goto-char (point-min))
8478 (when doshift
8479 (while (re-search-forward org-ts-regexp-both nil t)
8480 (org-timestamp-change (* n shift-n) shift-what))
8481 (unless (= n n-no-remove)
8482 (goto-char (point-min))
8483 (while (re-search-forward org-ts-regexp nil t)
8484 (save-excursion
8485 (goto-char (match-beginning 0))
8486 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8487 (delete-region (match-beginning 1) (match-end 1)))))))
8488 (setq task (buffer-string)))
8489 (insert task))
8490 (goto-char beg)))
8492 ;;; Outline Sorting
8494 (defun org-sort (with-case)
8495 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8496 Optional argument WITH-CASE means sort case-sensitively."
8497 (interactive "P")
8498 (cond
8499 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8500 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8502 (org-call-with-arg 'org-sort-entries with-case))))
8504 (defun org-sort-remove-invisible (s)
8505 "Remove invisible links from string S."
8506 (remove-text-properties 0 (length s) org-rm-props s)
8507 (while (string-match org-bracket-link-regexp s)
8508 (setq s (replace-match (if (match-end 2)
8509 (match-string 3 s)
8510 (match-string 1 s)) t t s)))
8511 (let ((st (format " %s " s)))
8512 (while (string-match org-emph-re st)
8513 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8514 (setq s (substring st 1 -1)))
8517 (defvar org-priority-regexp) ; defined later in the file
8519 (defvar org-after-sorting-entries-or-items-hook nil
8520 "Hook that is run after a bunch of entries or items have been sorted.
8521 When children are sorted, the cursor is in the parent line when this
8522 hook gets called. When a region or a plain list is sorted, the cursor
8523 will be in the first entry of the sorted region/list.")
8525 (defun org-sort-entries
8526 (&optional with-case sorting-type getkey-func compare-func property)
8527 "Sort entries on a certain level of an outline tree.
8528 If there is an active region, the entries in the region are sorted.
8529 Else, if the cursor is before the first entry, sort the top-level items.
8530 Else, the children of the entry at point are sorted.
8532 Sorting can be alphabetically, numerically, by date/time as given by
8533 a time stamp, by a property, by priority order, or by a custom function.
8535 The command prompts for the sorting type unless it has been given to the
8536 function through the SORTING-TYPE argument, which needs to be a character,
8537 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8538 precise meaning of each character:
8540 n Numerically, by converting the beginning of the entry/item to a number.
8541 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8542 o By order of TODO keywords.
8543 t By date/time, either the first active time stamp in the entry, or, if
8544 none exist, by the first inactive one.
8545 s By the scheduled date/time.
8546 d By deadline date/time.
8547 c By creation time, which is assumed to be the first inactive time stamp
8548 at the beginning of a line.
8549 p By priority according to the cookie.
8550 r By the value of a property.
8552 Capital letters will reverse the sort order.
8554 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8555 called with point at the beginning of the record. It must return either
8556 a string or a number that should serve as the sorting key for that record.
8558 Comparing entries ignores case by default. However, with an optional argument
8559 WITH-CASE, the sorting considers case as well.
8561 Sorting is done against the visible part of the headlines, it ignores hidden
8562 links."
8563 (interactive "P")
8564 (let ((case-func (if with-case 'identity 'downcase))
8565 (cmstr
8566 ;; The clock marker is lost when using `sort-subr', let's
8567 ;; store the clocking string.
8568 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8569 (save-excursion
8570 (goto-char org-clock-marker)
8571 (looking-back "^.*") (match-string-no-properties 0))))
8572 start beg end stars re re2
8573 txt what tmp)
8574 ;; Find beginning and end of region to sort
8575 (cond
8576 ((org-region-active-p)
8577 ;; we will sort the region
8578 (setq end (region-end)
8579 what "region")
8580 (goto-char (region-beginning))
8581 (if (not (org-at-heading-p)) (outline-next-heading))
8582 (setq start (point)))
8583 ((or (org-at-heading-p)
8584 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8585 ;; we will sort the children of the current headline
8586 (org-back-to-heading)
8587 (setq start (point)
8588 end (progn (org-end-of-subtree t t)
8589 (or (bolp) (insert "\n"))
8590 (org-back-over-empty-lines)
8591 (point))
8592 what "children")
8593 (goto-char start)
8594 (show-subtree)
8595 (outline-next-heading))
8597 ;; we will sort the top-level entries in this file
8598 (goto-char (point-min))
8599 (or (org-at-heading-p) (outline-next-heading))
8600 (setq start (point))
8601 (goto-char (point-max))
8602 (beginning-of-line 1)
8603 (when (looking-at ".*?\\S-")
8604 ;; File ends in a non-white line
8605 (end-of-line 1)
8606 (insert "\n"))
8607 (setq end (point-max))
8608 (setq what "top-level")
8609 (goto-char start)
8610 (show-all)))
8612 (setq beg (point))
8613 (if (>= beg end) (user-error "Nothing to sort"))
8615 (looking-at "\\(\\*+\\)")
8616 (setq stars (match-string 1)
8617 re (concat "^" (regexp-quote stars) " +")
8618 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8619 txt (buffer-substring beg end))
8620 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8621 (if (and (not (equal stars "*")) (string-match re2 txt))
8622 (user-error "Region to sort contains a level above the first entry"))
8624 (unless sorting-type
8625 (message
8626 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8627 [t]ime [s]cheduled [d]eadline [c]reated
8628 A/N/P/R/O/F/T/S/D/C means reversed:"
8629 what)
8630 (setq sorting-type (read-char-exclusive))
8632 (unless getkey-func
8633 (and (= (downcase sorting-type) ?f)
8634 (setq getkey-func
8635 (org-icompleting-read "Sort using function: "
8636 obarray 'fboundp t nil nil))
8637 (setq getkey-func (intern getkey-func))))
8639 (and (= (downcase sorting-type) ?r)
8640 (not property)
8641 (setq property
8642 (org-icompleting-read "Property: "
8643 (mapcar 'list (org-buffer-property-keys t))
8644 nil t))))
8646 (message "Sorting entries...")
8648 (save-restriction
8649 (narrow-to-region start end)
8650 (let ((dcst (downcase sorting-type))
8651 (case-fold-search nil)
8652 (now (current-time)))
8653 (sort-subr
8654 (/= dcst sorting-type)
8655 ;; This function moves to the beginning character of the "record" to
8656 ;; be sorted.
8657 (lambda nil
8658 (if (re-search-forward re nil t)
8659 (goto-char (match-beginning 0))
8660 (goto-char (point-max))))
8661 ;; This function moves to the last character of the "record" being
8662 ;; sorted.
8663 (lambda nil
8664 (save-match-data
8665 (condition-case nil
8666 (outline-forward-same-level 1)
8667 (error
8668 (goto-char (point-max))))))
8669 ;; This function returns the value that gets sorted against.
8670 (lambda nil
8671 (cond
8672 ((= dcst ?n)
8673 (if (looking-at org-complex-heading-regexp)
8674 (string-to-number (org-sort-remove-invisible (match-string 4)))
8675 nil))
8676 ((= dcst ?a)
8677 (if (looking-at org-complex-heading-regexp)
8678 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8679 nil))
8680 ((= dcst ?t)
8681 (let ((end (save-excursion (outline-next-heading) (point))))
8682 (if (or (re-search-forward org-ts-regexp end t)
8683 (re-search-forward org-ts-regexp-both end t))
8684 (org-time-string-to-seconds (match-string 0))
8685 (org-float-time now))))
8686 ((= dcst ?c)
8687 (let ((end (save-excursion (outline-next-heading) (point))))
8688 (if (re-search-forward
8689 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8690 end t)
8691 (org-time-string-to-seconds (match-string 0))
8692 (org-float-time now))))
8693 ((= dcst ?s)
8694 (let ((end (save-excursion (outline-next-heading) (point))))
8695 (if (re-search-forward org-scheduled-time-regexp end t)
8696 (org-time-string-to-seconds (match-string 1))
8697 (org-float-time now))))
8698 ((= dcst ?d)
8699 (let ((end (save-excursion (outline-next-heading) (point))))
8700 (if (re-search-forward org-deadline-time-regexp end t)
8701 (org-time-string-to-seconds (match-string 1))
8702 (org-float-time now))))
8703 ((= dcst ?p)
8704 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8705 (string-to-char (match-string 2))
8706 org-default-priority))
8707 ((= dcst ?r)
8708 (or (org-entry-get nil property) ""))
8709 ((= dcst ?o)
8710 (if (looking-at org-complex-heading-regexp)
8711 (- 9999 (length (member (match-string 2)
8712 org-todo-keywords-1)))))
8713 ((= dcst ?f)
8714 (if getkey-func
8715 (progn
8716 (setq tmp (funcall getkey-func))
8717 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8718 tmp)
8719 (error "Invalid key function `%s'" getkey-func)))
8720 (t (error "Invalid sorting type `%c'" sorting-type))))
8722 (cond
8723 ((= dcst ?a) 'string<)
8724 ((= dcst ?f) compare-func)
8725 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8726 (run-hooks 'org-after-sorting-entries-or-items-hook)
8727 ;; Reset the clock marker if needed
8728 (when cmstr
8729 (save-excursion
8730 (goto-char start)
8731 (search-forward cmstr nil t)
8732 (move-marker org-clock-marker (point))))
8733 (message "Sorting entries...done")))
8735 (defun org-do-sort (table what &optional with-case sorting-type)
8736 "Sort TABLE of WHAT according to SORTING-TYPE.
8737 The user will be prompted for the SORTING-TYPE if the call to this
8738 function does not specify it. WHAT is only for the prompt, to indicate
8739 what is being sorted. The sorting key will be extracted from
8740 the car of the elements of the table.
8741 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8742 (unless sorting-type
8743 (message
8744 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8745 what)
8746 (setq sorting-type (read-char-exclusive)))
8747 (let ((dcst (downcase sorting-type))
8748 extractfun comparefun)
8749 ;; Define the appropriate functions
8750 (cond
8751 ((= dcst ?n)
8752 (setq extractfun 'string-to-number
8753 comparefun (if (= dcst sorting-type) '< '>)))
8754 ((= dcst ?a)
8755 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8756 (lambda(x) (downcase (org-sort-remove-invisible x))))
8757 comparefun (if (= dcst sorting-type)
8758 'string<
8759 (lambda (a b) (and (not (string< a b))
8760 (not (string= a b)))))))
8761 ((= dcst ?t)
8762 (setq extractfun
8763 (lambda (x)
8764 (if (or (string-match org-ts-regexp x)
8765 (string-match org-ts-regexp-both x))
8766 (org-float-time
8767 (org-time-string-to-time (match-string 0 x)))
8769 comparefun (if (= dcst sorting-type) '< '>)))
8770 (t (error "Invalid sorting type `%c'" sorting-type)))
8772 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8773 table)
8774 (lambda (a b) (funcall comparefun (car a) (car b))))))
8777 ;;; The orgstruct minor mode
8779 ;; Define a minor mode which can be used in other modes in order to
8780 ;; integrate the org-mode structure editing commands.
8782 ;; This is really a hack, because the org-mode structure commands use
8783 ;; keys which normally belong to the major mode. Here is how it
8784 ;; works: The minor mode defines all the keys necessary to operate the
8785 ;; structure commands, but wraps the commands into a function which
8786 ;; tests if the cursor is currently at a headline or a plain list
8787 ;; item. If that is the case, the structure command is used,
8788 ;; temporarily setting many Org-mode variables like regular
8789 ;; expressions for filling etc. However, when any of those keys is
8790 ;; used at a different location, function uses `key-binding' to look
8791 ;; up if the key has an associated command in another currently active
8792 ;; keymap (minor modes, major mode, global), and executes that
8793 ;; command. There might be problems if any of the keys is otherwise
8794 ;; used as a prefix key.
8796 (defcustom orgstruct-heading-prefix-regexp nil
8797 "Regexp that matches the custom prefix of Org headlines in
8798 orgstruct(++)-mode."
8799 :group 'org
8800 :version "24.4"
8801 :package-version '(Org . "8.0")
8802 :type 'string)
8803 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8805 (defcustom orgstruct-setup-hook nil
8806 "Hook run after orgstruct-mode-map is filled."
8807 :group 'org
8808 :version "24.4"
8809 :package-version '(Org . "8.0")
8810 :type 'hook)
8812 (defvar orgstruct-initialized nil)
8814 (defvar org-local-vars nil
8815 "List of local variables, for use by `orgstruct-mode'.")
8817 ;;;###autoload
8818 (define-minor-mode orgstruct-mode
8819 "Toggle the minor mode `orgstruct-mode'.
8820 This mode is for using Org-mode structure commands in other
8821 modes. The following keys behave as if Org-mode were active, if
8822 the cursor is on a headline, or on a plain list item (both as
8823 defined by Org-mode)."
8824 nil " OrgStruct" (make-sparse-keymap)
8825 (funcall (if orgstruct-mode
8826 'add-to-invisibility-spec
8827 'remove-from-invisibility-spec)
8828 '(outline . t))
8829 (when orgstruct-mode
8830 (org-load-modules-maybe)
8831 (unless orgstruct-initialized
8832 (orgstruct-setup)
8833 (setq orgstruct-initialized t))))
8835 ;;;###autoload
8836 (defun turn-on-orgstruct ()
8837 "Unconditionally turn on `orgstruct-mode'."
8838 (orgstruct-mode 1))
8840 (defvar org-fb-vars nil)
8841 (make-variable-buffer-local 'org-fb-vars)
8842 (defun orgstruct++-mode (&optional arg)
8843 "Toggle `orgstruct-mode', the enhanced version of it.
8844 In addition to setting orgstruct-mode, this also exports all
8845 indentation and autofilling variables from org-mode into the
8846 buffer. It will also recognize item context in multiline items."
8847 (interactive "P")
8848 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8849 (if (< arg 1)
8850 (progn (orgstruct-mode -1)
8851 (mapc (lambda(v)
8852 (org-set-local (car v)
8853 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8854 org-fb-vars))
8855 (orgstruct-mode 1)
8856 (setq org-fb-vars nil)
8857 (let (var val)
8858 (mapc
8859 (lambda (x)
8860 (when (string-match
8861 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8862 (symbol-name (car x)))
8863 (setq var (car x) val (nth 1 x))
8864 (push (list var `(quote ,(eval var))) org-fb-vars)
8865 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8866 org-local-vars)
8867 (org-set-local 'orgstruct-is-++ t))))
8869 (defvar orgstruct-is-++ nil
8870 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8871 (make-variable-buffer-local 'orgstruct-is-++)
8873 ;;;###autoload
8874 (defun turn-on-orgstruct++ ()
8875 "Unconditionally turn on `orgstruct++-mode'."
8876 (orgstruct++-mode 1))
8878 (defun orgstruct-error ()
8879 "Error when there is no default binding for a structure key."
8880 (interactive)
8881 (funcall (if (fboundp 'user-error)
8882 'user-error
8883 'error)
8884 "This key has no function outside structure elements"))
8886 (defun orgstruct-setup ()
8887 "Setup orgstruct keymap."
8888 (dolist (cell '((org-demote . t)
8889 (org-metaleft . t)
8890 (org-metaright . t)
8891 (org-promote . t)
8892 (org-shiftmetaleft . t)
8893 (org-shiftmetaright . t)
8894 org-backward-element
8895 org-backward-heading-same-level
8896 org-ctrl-c-ret
8897 org-ctrl-c-minus
8898 org-ctrl-c-star
8899 org-cycle
8900 org-forward-heading-same-level
8901 org-insert-heading
8902 org-insert-heading-respect-content
8903 org-kill-note-or-show-branches
8904 org-mark-subtree
8905 org-meta-return
8906 org-metadown
8907 org-metaup
8908 org-narrow-to-subtree
8909 org-promote-subtree
8910 org-reveal
8911 org-shiftdown
8912 org-shiftleft
8913 org-shiftmetadown
8914 org-shiftmetaup
8915 org-shiftright
8916 org-shifttab
8917 org-shifttab
8918 org-shiftup
8919 org-show-subtree
8920 org-sort
8921 org-up-element
8922 outline-demote
8923 outline-next-visible-heading
8924 outline-previous-visible-heading
8925 outline-promote
8926 outline-up-heading
8927 show-children))
8928 (let ((f (or (car-safe cell) cell))
8929 (disable-when-heading-prefix (cdr-safe cell)))
8930 (when (fboundp f)
8931 (dolist (binding (nconc (where-is-internal f org-mode-map)
8932 (where-is-internal f outline-mode-map)))
8933 ;; TODO use local-function-key-map
8934 (dolist (rep '(("<tab>" . "TAB")
8935 ("<return>" . "RET")
8936 ("<escape>" . "ESC")
8937 ("<delete>" . "DEL")))
8938 (setq binding (read-kbd-macro
8939 (let ((case-fold-search))
8940 (replace-regexp-in-string
8941 (regexp-quote (cdr rep))
8942 (car rep)
8943 (key-description binding))))))
8944 (let ((key (lookup-key orgstruct-mode-map binding)))
8945 (when (or (not key) (numberp key))
8946 (condition-case nil
8947 (org-defkey orgstruct-mode-map
8948 binding
8949 (orgstruct-make-binding f binding disable-when-heading-prefix))
8950 (error nil))))))))
8951 (run-hooks 'orgstruct-setup-hook))
8953 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8954 "Create a function for binding in the structure minor mode.
8955 FUN is the command to call inside a table. KEY is the key that
8956 should be checked in for a command to execute outside of tables.
8957 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8958 if `orgstruct-heading-prefix-regexp' is non-nil."
8959 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8960 (let ((nname name)
8961 (i 0))
8962 (while (fboundp (intern nname))
8963 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8964 (setq name (intern nname)))
8965 (eval
8966 (let ((bindings '((org-heading-regexp
8967 (concat "^"
8968 orgstruct-heading-prefix-regexp
8969 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8970 (org-outline-regexp
8971 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8972 (org-outline-regexp-bol
8973 (concat "^" org-outline-regexp))
8974 (outline-regexp org-outline-regexp)
8975 (outline-heading-end-regexp "\n")
8976 (outline-level 'org-outline-level)
8977 (outline-heading-alist))))
8978 `(defun ,name (arg)
8979 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8980 "Outside of structure, run the binding of `"
8981 (key-description key) "'."
8982 (when disable-when-heading-prefix
8983 (concat
8984 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8985 "back to the default binding due to limitations of Org's implementation of\n"
8986 "`" (symbol-name fun) "'.")))
8987 (interactive "p")
8988 (let* ((disable
8989 ,(when disable-when-heading-prefix
8990 '(and orgstruct-heading-prefix-regexp
8991 (not (string= orgstruct-heading-prefix-regexp "")))))
8992 (fallback
8993 (or disable
8994 (not
8995 (let* ,bindings
8996 (org-context-p 'headline 'item
8997 ,(when (memq fun '(org-insert-heading))
8998 '(when orgstruct-is-++
8999 'item-body))))))))
9000 (if fallback
9001 (let* ((orgstruct-mode)
9002 (binding
9003 (loop with key = ,key
9004 for rep in
9005 '(nil
9006 ("<\\([^>]*\\)tab>" . "\\1TAB")
9007 ("<\\([^>]*\\)return>" . "\\1RET")
9008 ("<\\([^>]*\\)escape>" . "\\1ESC")
9009 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9011 (when rep
9012 (setq key (read-kbd-macro
9013 (let ((case-fold-search))
9014 (replace-regexp-in-string
9015 (car rep)
9016 (cdr rep)
9017 (key-description key))))))
9018 thereis (key-binding key))))
9019 (if (keymapp binding)
9020 (set-temporary-overlay-map binding)
9021 (let ((func (or binding
9022 (unless disable
9023 'orgstruct-error))))
9024 (when func
9025 (call-interactively func)))))
9026 (org-run-like-in-org-mode
9027 (lambda ()
9028 (interactive)
9029 (let* ,bindings
9030 (call-interactively ',fun)))))))))
9031 name))
9033 (defun org-contextualize-keys (alist contexts)
9034 "Return valid elements in ALIST depending on CONTEXTS.
9036 `org-agenda-custom-commands' or `org-capture-templates' are the
9037 values used for ALIST, and `org-agenda-custom-commands-contexts'
9038 or `org-capture-templates-contexts' are the associated contexts
9039 definitions."
9040 (let ((contexts
9041 ;; normalize contexts
9042 (mapcar
9043 (lambda(c) (cond ((listp (cadr c))
9044 (list (car c) (car c) (cadr c)))
9045 ((string= "" (cadr c))
9046 (list (car c) (car c) (caddr c)))
9047 (t c))) contexts))
9048 (a alist) c r s)
9049 ;; loop over all commands or templates
9050 (while (setq c (pop a))
9051 (let (vrules repl)
9052 (cond
9053 ((not (assoc (car c) contexts))
9054 (push c r))
9055 ((and (assoc (car c) contexts)
9056 (setq vrules (org-contextualize-validate-key
9057 (car c) contexts)))
9058 (mapc (lambda (vr)
9059 (when (not (equal (car vr) (cadr vr)))
9060 (setq repl vr))) vrules)
9061 (if (not repl) (push c r)
9062 (push (cadr repl) s)
9063 (push
9064 (cons (car c)
9065 (cdr (or (assoc (cadr repl) alist)
9066 (error "Undefined key `%s' as contextual replacement for `%s'"
9067 (cadr repl) (car c)))))
9068 r))))))
9069 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9070 (delq
9072 (delete-dups
9073 (mapcar (lambda (x)
9074 (let ((tpl (car x)))
9075 (when (not (delq
9077 (mapcar (lambda(y)
9078 (equal y tpl)) s))) x)))
9079 (reverse r))))))
9081 (defun org-contextualize-validate-key (key contexts)
9082 "Check CONTEXTS for agenda or capture KEY."
9083 (let (r rr res)
9084 (while (setq r (pop contexts))
9085 (mapc
9086 (lambda (rr)
9087 (when
9088 (and (equal key (car r))
9089 (if (functionp rr) (funcall rr)
9090 (or (and (eq (car rr) 'in-file)
9091 (buffer-file-name)
9092 (string-match (cdr rr) (buffer-file-name)))
9093 (and (eq (car rr) 'in-mode)
9094 (string-match (cdr rr) (symbol-name major-mode)))
9095 (and (eq (car rr) 'in-buffer)
9096 (string-match (cdr rr) (buffer-name)))
9097 (when (and (eq (car rr) 'not-in-file)
9098 (buffer-file-name))
9099 (not (string-match (cdr rr) (buffer-file-name))))
9100 (when (eq (car rr) 'not-in-mode)
9101 (not (string-match (cdr rr) (symbol-name major-mode))))
9102 (when (eq (car rr) 'not-in-buffer)
9103 (not (string-match (cdr rr) (buffer-name)))))))
9104 (push r res)))
9105 (car (last r))))
9106 (delete-dups (delq nil res))))
9108 (defun org-context-p (&rest contexts)
9109 "Check if local context is any of CONTEXTS.
9110 Possible values in the list of contexts are `table', `headline', and `item'."
9111 (let ((pos (point)))
9112 (goto-char (point-at-bol))
9113 (prog1 (or (and (memq 'table contexts)
9114 (looking-at "[ \t]*|"))
9115 (and (memq 'headline contexts)
9116 (looking-at org-outline-regexp))
9117 (and (memq 'item contexts)
9118 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9119 (and (memq 'item-body contexts)
9120 (org-in-item-p)))
9121 (goto-char pos))))
9123 (defun org-get-local-variables ()
9124 "Return a list of all local variables in an Org mode buffer."
9125 (let (varlist)
9126 (with-current-buffer (get-buffer-create "*Org tmp*")
9127 (erase-buffer)
9128 (org-mode)
9129 (setq varlist (buffer-local-variables)))
9130 (kill-buffer "*Org tmp*")
9131 (delq nil
9132 (mapcar
9133 (lambda (x)
9134 (setq x
9135 (if (symbolp x)
9136 (list x)
9137 (list (car x) (cdr x))))
9138 (if (and (not (get (car x) 'org-state))
9139 (string-match
9140 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9141 (symbol-name (car x))))
9142 x nil))
9143 varlist))))
9145 (defun org-clone-local-variables (from-buffer &optional regexp)
9146 "Clone local variables from FROM-BUFFER.
9147 Optional argument REGEXP selects variables to clone."
9148 (mapc
9149 (lambda (pair)
9150 (and (symbolp (car pair))
9151 (or (null regexp)
9152 (string-match regexp (symbol-name (car pair))))
9153 (set (make-local-variable (car pair))
9154 (cdr pair))))
9155 (buffer-local-variables from-buffer)))
9157 ;;;###autoload
9158 (defun org-run-like-in-org-mode (cmd)
9159 "Run a command, pretending that the current buffer is in Org-mode.
9160 This will temporarily bind local variables that are typically bound in
9161 Org-mode to the values they have in Org-mode, and then interactively
9162 call CMD."
9163 (org-load-modules-maybe)
9164 (unless org-local-vars
9165 (setq org-local-vars (org-get-local-variables)))
9166 (let (binds)
9167 (dolist (var org-local-vars)
9168 (when (or (not (boundp (car var)))
9169 (eq (symbol-value (car var))
9170 (default-value (car var))))
9171 (push (list (car var) `(quote ,(cadr var))) binds)))
9172 (eval `(let ,binds
9173 (call-interactively (quote ,cmd))))))
9175 ;;;; Archiving
9177 (defun org-get-category (&optional pos force-refresh)
9178 "Get the category applying to position POS."
9179 (save-match-data
9180 (if force-refresh (org-refresh-category-properties))
9181 (let ((pos (or pos (point))))
9182 (or (get-text-property pos 'org-category)
9183 (progn (org-refresh-category-properties)
9184 (get-text-property pos 'org-category))))))
9186 (defun org-refresh-category-properties ()
9187 "Refresh category text properties in the buffer."
9188 (let ((case-fold-search t)
9189 (inhibit-read-only t)
9190 (def-cat (cond
9191 ((null org-category)
9192 (if buffer-file-name
9193 (file-name-sans-extension
9194 (file-name-nondirectory buffer-file-name))
9195 "???"))
9196 ((symbolp org-category) (symbol-name org-category))
9197 (t org-category)))
9198 beg end cat pos optionp)
9199 (org-with-silent-modifications
9200 (save-excursion
9201 (save-restriction
9202 (widen)
9203 (goto-char (point-min))
9204 (put-text-property (point) (point-max) 'org-category def-cat)
9205 (while (re-search-forward
9206 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9207 (setq pos (match-end 0)
9208 optionp (equal (char-after (match-beginning 0)) ?#)
9209 cat (org-trim (match-string 2)))
9210 (if optionp
9211 (setq beg (point-at-bol) end (point-max))
9212 (org-back-to-heading t)
9213 (setq beg (point) end (org-end-of-subtree t t)))
9214 (put-text-property beg end 'org-category cat)
9215 (put-text-property beg end 'org-category-position beg)
9216 (goto-char pos)))))))
9218 (defun org-refresh-properties (dprop tprop)
9219 "Refresh buffer text properties.
9220 DPROP is the drawer property and TPROP is the corresponding text
9221 property to set."
9222 (let ((case-fold-search t)
9223 (inhibit-read-only t) p)
9224 (org-with-silent-modifications
9225 (save-excursion
9226 (save-restriction
9227 (widen)
9228 (goto-char (point-min))
9229 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9230 (setq p (org-match-string-no-properties 1))
9231 (save-excursion
9232 (org-back-to-heading t)
9233 (put-text-property
9234 (point-at-bol) (point-at-eol) tprop p))))))))
9237 ;;;; Link Stuff
9239 ;;; Link abbreviations
9241 (defun org-link-expand-abbrev (link)
9242 "Apply replacements as defined in `org-link-abbrev-alist'."
9243 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9244 (let* ((key (match-string 1 link))
9245 (as (or (assoc key org-link-abbrev-alist-local)
9246 (assoc key org-link-abbrev-alist)))
9247 (tag (and (match-end 2) (match-string 3 link)))
9248 rpl)
9249 (if (not as)
9250 link
9251 (setq rpl (cdr as))
9252 (cond
9253 ((symbolp rpl) (funcall rpl tag))
9254 ((string-match "%(\\([^)]+\\))" rpl)
9255 (replace-match
9256 (save-match-data
9257 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9258 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9259 ((string-match "%h" rpl)
9260 (replace-match (url-hexify-string (or tag "")) t t rpl))
9261 (t (concat rpl tag)))))
9262 link))
9264 ;;; Storing and inserting links
9266 (defvar org-insert-link-history nil
9267 "Minibuffer history for links inserted with `org-insert-link'.")
9269 (defvar org-stored-links nil
9270 "Contains the links stored with `org-store-link'.")
9272 (defvar org-store-link-plist nil
9273 "Plist with info about the most recently link created with `org-store-link'.")
9275 (defvar org-link-protocols nil
9276 "Link protocols added to Org-mode using `org-add-link-type'.")
9278 (defvar org-store-link-functions nil
9279 "List of functions that are called to create and store a link.
9280 Each function will be called in turn until one returns a non-nil
9281 value. Each function should check if it is responsible for creating
9282 this link (for example by looking at the major mode).
9283 If not, it must exit and return nil.
9284 If yes, it should return a non-nil value after a calling
9285 `org-store-link-props' with a list of properties and values.
9286 Special properties are:
9288 :type The link prefix, like \"http\". This must be given.
9289 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9290 This is obligatory as well.
9291 :description Optional default description for the second pair
9292 of brackets in an Org-mode link. The user can still change
9293 this when inserting this link into an Org-mode buffer.
9295 In addition to these, any additional properties can be specified
9296 and then used in capture templates.")
9298 (defun org-add-link-type (type &optional follow export)
9299 "Add TYPE to the list of `org-link-types'.
9300 Re-compute all regular expressions depending on `org-link-types'
9302 FOLLOW and EXPORT are two functions.
9304 FOLLOW should take the link path as the single argument and do whatever
9305 is necessary to follow the link, for example find a file or display
9306 a mail message.
9308 EXPORT should format the link path for export to one of the export formats.
9309 It should be a function accepting three arguments:
9311 path the path of the link, the text after the prefix (like \"http:\")
9312 desc the description of the link, if any, or a description added by
9313 org-export-normalize-links if there is none
9314 format the export format, a symbol like `html' or `latex' or `ascii'..
9316 The function may use the FORMAT information to return different values
9317 depending on the format. The return value will be put literally into
9318 the exported file. If the return value is nil, this means Org should
9319 do what it normally does with links which do not have EXPORT defined.
9321 Org-mode has a built-in default for exporting links. If you are happy with
9322 this default, there is no need to define an export function for the link
9323 type. For a simple example of an export function, see `org-bbdb.el'."
9324 (add-to-list 'org-link-types type t)
9325 (org-make-link-regexps)
9326 (if (assoc type org-link-protocols)
9327 (setcdr (assoc type org-link-protocols) (list follow export))
9328 (push (list type follow export) org-link-protocols)))
9330 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9331 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9333 ;;;###autoload
9334 (defun org-store-link (arg)
9335 "\\<org-mode-map>Store an org-link to the current location.
9336 This link is added to `org-stored-links' and can later be inserted
9337 into an org-buffer with \\[org-insert-link].
9339 For some link types, a prefix arg is interpreted.
9340 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9341 For file links, arg negates `org-context-in-file-links'.
9343 A double prefix arg force skipping storing functions that are not
9344 part of Org's core.
9346 A triple prefix arg force storing a link for each line in the
9347 active region."
9348 (interactive "P")
9349 (org-load-modules-maybe)
9350 (if (and (equal arg '(64)) (org-region-active-p))
9351 (save-excursion
9352 (let ((end (region-end)))
9353 (goto-char (region-beginning))
9354 (set-mark (point))
9355 (while (< (point-at-eol) end)
9356 (move-end-of-line 1) (activate-mark)
9357 (let (current-prefix-arg)
9358 (call-interactively 'org-store-link))
9359 (move-beginning-of-line 2)
9360 (set-mark (point)))))
9361 (org-with-limited-levels
9362 (setq org-store-link-plist nil)
9363 (let (link cpltxt desc description search
9364 txt custom-id agenda-link sfuns sfunsn)
9365 (cond
9367 ;; Store a link using an external link type
9368 ((and (not (equal arg '(16)))
9369 (setq sfuns
9370 (delq
9371 nil (mapcar (lambda (f)
9372 (let (fs) (if (funcall f) (push f fs))))
9373 org-store-link-functions))
9374 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9375 (or (and (cdr sfuns)
9376 (funcall (intern
9377 (completing-read
9378 "Which function for creating the link? "
9379 sfunsn t (car sfunsn)))))
9380 (funcall (caar sfuns)))
9381 (setq link (plist-get org-store-link-plist :link)
9382 desc (or (plist-get org-store-link-plist
9383 :description) link))))
9385 ;; Store a link from a source code buffer
9386 ((org-src-edit-buffer-p)
9387 (let (label gc)
9388 (while (or (not label)
9389 (save-excursion
9390 (save-restriction
9391 (widen)
9392 (goto-char (point-min))
9393 (re-search-forward
9394 (regexp-quote (format org-coderef-label-format label))
9395 nil t))))
9396 (when label (message "Label exists already") (sit-for 2))
9397 (setq label (read-string "Code line label: " label)))
9398 (end-of-line 1)
9399 (setq link (format org-coderef-label-format label))
9400 (setq gc (- 79 (length link)))
9401 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9402 (insert link)
9403 (setq link (concat "(" label ")") desc nil)))
9405 ;; We are in the agenda, link to referenced location
9406 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9407 (let ((m (or (get-text-property (point) 'org-hd-marker)
9408 (get-text-property (point) 'org-marker))))
9409 (when m
9410 (org-with-point-at m
9411 (setq agenda-link
9412 (if (org-called-interactively-p 'any)
9413 (call-interactively 'org-store-link)
9414 (org-store-link nil)))))))
9416 ((eq major-mode 'calendar-mode)
9417 (let ((cd (calendar-cursor-to-date)))
9418 (setq link
9419 (format-time-string
9420 (car org-time-stamp-formats)
9421 (apply 'encode-time
9422 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9423 nil nil nil))))
9424 (org-store-link-props :type "calendar" :date cd)))
9426 ((eq major-mode 'help-mode)
9427 (setq link (concat "help:" (save-excursion
9428 (goto-char (point-min))
9429 (looking-at "^[^ ]+")
9430 (match-string 0))))
9431 (org-store-link-props :type "help"))
9433 ((eq major-mode 'w3-mode)
9434 (setq cpltxt (if (and (buffer-name)
9435 (not (string-match "Untitled" (buffer-name))))
9436 (buffer-name)
9437 (url-view-url t))
9438 link (url-view-url t))
9439 (org-store-link-props :type "w3" :url (url-view-url t)))
9441 ((eq major-mode 'image-mode)
9442 (setq cpltxt (concat "file:"
9443 (abbreviate-file-name buffer-file-name))
9444 link cpltxt)
9445 (org-store-link-props :type "image" :file buffer-file-name))
9447 ;; In dired, store a link to the file of the current line
9448 ((eq major-mode 'dired-mode)
9449 (let ((file (dired-get-filename nil t)))
9450 (setq file (if file
9451 (abbreviate-file-name
9452 (expand-file-name (dired-get-filename nil t)))
9453 ;; otherwise, no file so use current directory.
9454 default-directory))
9455 (setq cpltxt (concat "file:" file)
9456 link cpltxt)))
9458 ((setq search (run-hook-with-args-until-success
9459 'org-create-file-search-functions))
9460 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9461 "::" search))
9462 (setq cpltxt (or description link)))
9464 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9465 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9466 (cond
9467 ;; Store a link using the radio target at point
9468 ((org-in-regexp "<<\\(.*?\\)>>")
9469 (setq cpltxt
9470 (concat "file:"
9471 (abbreviate-file-name
9472 (buffer-file-name (buffer-base-buffer)))
9473 "::" (match-string 1))
9474 link cpltxt))
9475 ((and (featurep 'org-id)
9476 (or (eq org-id-link-to-org-use-id t)
9477 (and (org-called-interactively-p 'any)
9478 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9479 (and (eq org-id-link-to-org-use-id
9480 'create-if-interactive-and-no-custom-id)
9481 (not custom-id))))
9482 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9483 ;; Store a link using the ID at point
9484 (setq link (condition-case nil
9485 (prog1 (org-id-store-link)
9486 (setq desc (plist-get org-store-link-plist
9487 :description)))
9488 (error
9489 ;; Probably before first headline, link only to file
9490 (concat "file:"
9491 (abbreviate-file-name
9492 (buffer-file-name (buffer-base-buffer))))))))
9494 ;; Just link to current headline
9495 (setq cpltxt (concat "file:"
9496 (abbreviate-file-name
9497 (buffer-file-name (buffer-base-buffer)))))
9498 ;; Add a context search string
9499 (when (org-xor org-context-in-file-links arg)
9500 (let* ((ee (org-element-at-point))
9501 (et (org-element-type ee))
9502 (ev (plist-get (cadr ee) :value))
9503 (ek (plist-get (cadr ee) :key))
9504 (eok (and (stringp ek) (string-match "name" ek))))
9505 (setq txt (cond
9506 ((org-at-heading-p) nil)
9507 ((and (eq et 'keyword) eok) ev)
9508 ((org-region-active-p)
9509 (buffer-substring (region-beginning) (region-end)))))
9510 (when (or (null txt) (string-match "\\S-" txt))
9511 (setq cpltxt
9512 (concat cpltxt "::"
9513 (condition-case nil
9514 (org-make-org-heading-search-string txt)
9515 (error "")))
9516 desc (or (and (eq et 'keyword) eok ev)
9517 (nth 4 (ignore-errors (org-heading-components)))
9518 "NONE")))))
9519 (if (string-match "::\\'" cpltxt)
9520 (setq cpltxt (substring cpltxt 0 -2)))
9521 (setq link cpltxt))))
9523 ((buffer-file-name (buffer-base-buffer))
9524 ;; Just link to this file here.
9525 (setq cpltxt (concat "file:"
9526 (abbreviate-file-name
9527 (buffer-file-name (buffer-base-buffer)))))
9528 ;; Add a context string.
9529 (when (org-xor org-context-in-file-links arg)
9530 (setq txt (if (org-region-active-p)
9531 (buffer-substring (region-beginning) (region-end))
9532 (buffer-substring (point-at-bol) (point-at-eol))))
9533 ;; Only use search option if there is some text.
9534 (when (string-match "\\S-" txt)
9535 (setq cpltxt
9536 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9537 desc "NONE")))
9538 (setq link cpltxt))
9540 ((org-called-interactively-p 'interactive)
9541 (user-error "No method for storing a link from this buffer"))
9543 (t (setq link nil)))
9545 ;; We're done setting link and desc, clean up
9546 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9547 (setq link (or link cpltxt)
9548 desc (or desc cpltxt))
9549 (cond ((equal desc "NONE") (setq desc nil))
9550 ((string-match org-bracket-link-analytic-regexp desc)
9551 (let ((d0 (match-string 3 desc))
9552 (p0 (match-string 5 desc)))
9553 (setq desc
9554 (replace-regexp-in-string
9555 org-bracket-link-regexp
9556 (concat (or p0 d0)
9557 (if (equal (length (match-string 0 desc))
9558 (length desc)) "*" "")) desc)))))
9560 ;; Return the link
9561 (if (not (and (or (org-called-interactively-p 'any)
9562 executing-kbd-macro) link))
9563 (or agenda-link (and link (org-make-link-string link desc)))
9564 (push (list link desc) org-stored-links)
9565 (message "Stored: %s" (or desc link))
9566 (when custom-id
9567 (setq link (concat "file:" (abbreviate-file-name
9568 (buffer-file-name)) "::#" custom-id))
9569 (push (list link desc) org-stored-links)))))))
9571 (defun org-store-link-props (&rest plist)
9572 "Store link properties, extract names and addresses."
9573 (let (x adr)
9574 (when (setq x (plist-get plist :from))
9575 (setq adr (mail-extract-address-components x))
9576 (setq plist (plist-put plist :fromname (car adr)))
9577 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9578 (when (setq x (plist-get plist :to))
9579 (setq adr (mail-extract-address-components x))
9580 (setq plist (plist-put plist :toname (car adr)))
9581 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9582 (let ((from (plist-get plist :from))
9583 (to (plist-get plist :to)))
9584 (when (and from to org-from-is-user-regexp)
9585 (setq plist
9586 (plist-put plist :fromto
9587 (if (string-match org-from-is-user-regexp from)
9588 (concat "to %t")
9589 (concat "from %f"))))))
9590 (setq org-store-link-plist plist))
9592 (defun org-add-link-props (&rest plist)
9593 "Add these properties to the link property list."
9594 (let (key value)
9595 (while plist
9596 (setq key (pop plist) value (pop plist))
9597 (setq org-store-link-plist
9598 (plist-put org-store-link-plist key value)))))
9600 (defun org-email-link-description (&optional fmt)
9601 "Return the description part of an email link.
9602 This takes information from `org-store-link-plist' and formats it
9603 according to FMT (default from `org-email-link-description-format')."
9604 (setq fmt (or fmt org-email-link-description-format))
9605 (let* ((p org-store-link-plist)
9606 (to (plist-get p :toaddress))
9607 (from (plist-get p :fromaddress))
9608 (table
9609 (list
9610 (cons "%c" (plist-get p :fromto))
9611 (cons "%F" (plist-get p :from))
9612 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9613 (cons "%T" (plist-get p :to))
9614 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9615 (cons "%s" (plist-get p :subject))
9616 (cons "%d" (plist-get p :date))
9617 (cons "%m" (plist-get p :message-id)))))
9618 (when (string-match "%c" fmt)
9619 ;; Check if the user wrote this message
9620 (if (and org-from-is-user-regexp from to
9621 (save-match-data (string-match org-from-is-user-regexp from)))
9622 (setq fmt (replace-match "to %t" t t fmt))
9623 (setq fmt (replace-match "from %f" t t fmt))))
9624 (org-replace-escapes fmt table)))
9626 (defun org-make-org-heading-search-string (&optional string)
9627 "Make search string for the current headline or STRING."
9628 (let ((s (or string
9629 (and (derived-mode-p 'org-mode)
9630 (save-excursion
9631 (org-back-to-heading t)
9632 (org-element-property :raw-value (org-element-at-point))))))
9633 (lines org-context-in-file-links))
9634 (or string (setq s (concat "*" s))) ; Add * for headlines
9635 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9636 (when (and string (integerp lines) (> lines 0))
9637 (let ((slines (org-split-string s "\n")))
9638 (when (< lines (length slines))
9639 (setq s (mapconcat
9640 'identity
9641 (reverse (nthcdr (- (length slines) lines)
9642 (reverse slines))) "\n")))))
9643 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9645 (defun org-make-link-string (link &optional description)
9646 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9647 (unless (string-match "\\S-" link)
9648 (error "Empty link"))
9649 (when (and description
9650 (stringp description)
9651 (not (string-match "\\S-" description)))
9652 (setq description nil))
9653 (when (stringp description)
9654 ;; Remove brackets from the description, they are fatal.
9655 (while (string-match "\\[" description)
9656 (setq description (replace-match "{" t t description)))
9657 (while (string-match "\\]" description)
9658 (setq description (replace-match "}" t t description))))
9659 (when (equal link description)
9660 ;; No description needed, it is identical
9661 (setq description nil))
9662 (when (and (not description)
9663 (not (string-match (org-image-file-name-regexp) link))
9664 (not (equal link (org-link-escape link))))
9665 (setq description (org-extract-attributes link)))
9666 (setq link
9667 (cond ((string-match (org-image-file-name-regexp) link) link)
9668 ((string-match org-link-types-re link)
9669 (concat (match-string 1 link)
9670 (org-link-escape (substring link (match-end 1)))))
9671 (t (org-link-escape link))))
9672 (concat "[[" link "]"
9673 (if description (concat "[" description "]") "")
9674 "]"))
9676 (defconst org-link-escape-chars
9677 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9678 "List of characters that should be escaped in link.
9679 This is the list that is used for internal purposes.")
9681 (defconst org-link-escape-chars-browser
9682 '(?\ )
9683 "List of escapes for characters that are problematic in links.
9684 This is the list that is used before handing over to the browser.")
9686 (defun org-link-escape (text &optional table merge)
9687 "Return percent escaped representation of TEXT.
9688 TEXT is a string with the text to escape.
9689 Optional argument TABLE is a list with characters that should be
9690 escaped. When nil, `org-link-escape-chars' is used.
9691 If optional argument MERGE is set, merge TABLE into
9692 `org-link-escape-chars'."
9693 (cond
9694 ((and table merge)
9695 (mapc (lambda (defchr)
9696 (unless (member defchr table)
9697 (setq table (cons defchr table)))) org-link-escape-chars))
9698 ((null table)
9699 (setq table org-link-escape-chars)))
9700 (mapconcat
9701 (lambda (char)
9702 (if (or (member char table)
9703 (and (or (< char 32) (= char 37) (> char 126))
9704 org-url-hexify-p))
9705 (mapconcat (lambda (sequence-element)
9706 (format "%%%.2X" sequence-element))
9707 (or (encode-coding-char char 'utf-8)
9708 (error "Unable to percent escape character: %s"
9709 (char-to-string char))) "")
9710 (char-to-string char))) text ""))
9712 (defun org-link-unescape (str)
9713 "Unhex hexified Unicode strings as returned from the JavaScript function
9714 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9715 (unless (and (null str) (string= "" str))
9716 (let ((pos 0) (case-fold-search t) unhexed)
9717 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9718 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9719 (setq str (replace-match unhexed t t str))
9720 (setq pos (+ pos (length unhexed))))))
9721 str)
9723 (defun org-link-unescape-compound (hex)
9724 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9725 Note: this function also decodes single byte encodings like
9726 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9727 (save-match-data
9728 (let* ((bytes (cdr (split-string hex "%")))
9729 (ret "")
9730 (eat 0)
9731 (sum 0))
9732 (while bytes
9733 (let* ((val (string-to-number (pop bytes) 16))
9734 (shift-xor
9735 (if (= 0 eat)
9736 (cond
9737 ((>= val 252) (cons 6 252))
9738 ((>= val 248) (cons 5 248))
9739 ((>= val 240) (cons 4 240))
9740 ((>= val 224) (cons 3 224))
9741 ((>= val 192) (cons 2 192))
9742 (t (cons 0 0)))
9743 (cons 6 128))))
9744 (if (>= val 192) (setq eat (car shift-xor)))
9745 (setq val (logxor val (cdr shift-xor)))
9746 (setq sum (+ (lsh sum (car shift-xor)) val))
9747 (if (> eat 0) (setq eat (- eat 1)))
9748 (cond
9749 ((= 0 eat) ;multi byte
9750 (setq ret (concat ret (org-char-to-string sum)))
9751 (setq sum 0))
9752 ((not bytes) ; single byte(s)
9753 (setq ret (org-link-unescape-single-byte-sequence hex))))
9754 )) ;; end (while bytes
9755 ret )))
9757 (defun org-link-unescape-single-byte-sequence (hex)
9758 "Unhexify hex-encoded single byte character sequences."
9759 (mapconcat (lambda (byte)
9760 (char-to-string (string-to-number byte 16)))
9761 (cdr (split-string hex "%")) ""))
9763 (defun org-xor (a b)
9764 "Exclusive or."
9765 (if a (not b) b))
9767 (defun org-fixup-message-id-for-http (s)
9768 "Replace special characters in a message id, so it can be used in an http query."
9769 (when (string-match "%" s)
9770 (setq s (mapconcat (lambda (c)
9771 (if (eq c ?%)
9772 "%25"
9773 (char-to-string c)))
9774 s "")))
9775 (while (string-match "<" s)
9776 (setq s (replace-match "%3C" t t s)))
9777 (while (string-match ">" s)
9778 (setq s (replace-match "%3E" t t s)))
9779 (while (string-match "@" s)
9780 (setq s (replace-match "%40" t t s)))
9783 (defun org-link-prettify (link)
9784 "Return a human-readable representation of LINK.
9785 The car of LINK must be a raw link the cdr of LINK must be either
9786 a link description or nil."
9787 (let ((desc (or (cadr link) "<no description>")))
9788 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9789 "<" (car link) ">")))
9791 ;;;###autoload
9792 (defun org-insert-link-global ()
9793 "Insert a link like Org-mode does.
9794 This command can be called in any mode to insert a link in Org-mode syntax."
9795 (interactive)
9796 (org-load-modules-maybe)
9797 (org-run-like-in-org-mode 'org-insert-link))
9799 (defun org-insert-all-links (&optional keep)
9800 "Insert all links in `org-stored-links'."
9801 (interactive "P")
9802 (let ((links (copy-sequence org-stored-links)) l)
9803 (while (setq l (if keep (pop links) (pop org-stored-links)))
9804 (insert "- ")
9805 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9806 (insert "\n"))))
9808 (defun org-link-fontify-links-to-this-file ()
9809 "Fontify links to the current file in `org-stored-links'."
9810 (let ((f (buffer-file-name)) a b)
9811 (setq a (mapcar (lambda(l)
9812 (let ((ll (car l)))
9813 (when (and (string-match "^file:\\(.+\\)::" ll)
9814 (equal f (expand-file-name (match-string 1 ll))))
9815 ll)))
9816 org-stored-links))
9817 (when (featurep 'org-id)
9818 (setq b (mapcar (lambda(l)
9819 (let ((ll (car l)))
9820 (when (and (string-match "^id:\\(.+\\)$" ll)
9821 (equal f (expand-file-name
9822 (or (org-id-find-id-file
9823 (match-string 1 ll)) ""))))
9824 ll)))
9825 org-stored-links)))
9826 (mapcar (lambda(l)
9827 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9828 (delq nil (append a b)))))
9830 (defvar org-link-links-in-this-file nil)
9831 (defun org-insert-link (&optional complete-file link-location default-description)
9832 "Insert a link. At the prompt, enter the link.
9834 Completion can be used to insert any of the link protocol prefixes like
9835 http or ftp in use.
9837 The history can be used to select a link previously stored with
9838 `org-store-link'. When the empty string is entered (i.e. if you just
9839 press RET at the prompt), the link defaults to the most recently
9840 stored link. As SPC triggers completion in the minibuffer, you need to
9841 use M-SPC or C-q SPC to force the insertion of a space character.
9843 You will also be prompted for a description, and if one is given, it will
9844 be displayed in the buffer instead of the link.
9846 If there is already a link at point, this command will allow you to edit link
9847 and description parts.
9849 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9850 be selected using completion. The path to the file will be relative to the
9851 current directory if the file is in the current directory or a subdirectory.
9852 Otherwise, the link will be the absolute path as completed in the minibuffer
9853 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9854 option `org-link-file-path-type'.
9856 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9857 the current directory or below.
9859 With three \\[universal-argument] prefixes, negate the meaning of
9860 `org-keep-stored-link-after-insertion'.
9862 If `org-make-link-description-function' is non-nil, this function will be
9863 called with the link target, and the result will be the default
9864 link description.
9866 If the LINK-LOCATION parameter is non-nil, this value will be
9867 used as the link location instead of reading one interactively.
9869 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9870 be used as the default description."
9871 (interactive "P")
9872 (let* ((wcf (current-window-configuration))
9873 (origbuf (current-buffer))
9874 (region (if (org-region-active-p)
9875 (buffer-substring (region-beginning) (region-end))))
9876 (remove (and region (list (region-beginning) (region-end))))
9877 (desc region)
9878 tmphist ; byte-compile incorrectly complains about this
9879 (link link-location)
9880 (abbrevs org-link-abbrev-alist-local)
9881 entry file all-prefixes auto-desc)
9882 (cond
9883 (link-location) ; specified by arg, just use it.
9884 ((org-in-regexp org-bracket-link-regexp 1)
9885 ;; We do have a link at point, and we are going to edit it.
9886 (setq remove (list (match-beginning 0) (match-end 0)))
9887 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9888 (setq link (read-string "Link: "
9889 (org-link-unescape
9890 (org-match-string-no-properties 1)))))
9891 ((or (org-in-regexp org-angle-link-re)
9892 (org-in-regexp org-plain-link-re))
9893 ;; Convert to bracket link
9894 (setq remove (list (match-beginning 0) (match-end 0))
9895 link (read-string "Link: "
9896 (org-remove-angle-brackets (match-string 0)))))
9897 ((member complete-file '((4) (16)))
9898 ;; Completing read for file names.
9899 (setq link (org-file-complete-link complete-file)))
9901 ;; Read link, with completion for stored links.
9902 (org-link-fontify-links-to-this-file)
9903 (org-switch-to-buffer-other-window "*Org Links*")
9904 (with-current-buffer "*Org Links*"
9905 (erase-buffer)
9906 (insert "Insert a link.
9907 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9908 (when org-stored-links
9909 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9910 (insert (mapconcat 'org-link-prettify
9911 (reverse org-stored-links) "\n")))
9912 (goto-char (point-min)))
9913 (let ((cw (selected-window)))
9914 (select-window (get-buffer-window "*Org Links*" 'visible))
9915 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9916 (unless (pos-visible-in-window-p (point-max))
9917 (org-fit-window-to-buffer))
9918 (and (window-live-p cw) (select-window cw)))
9919 ;; Fake a link history, containing the stored links.
9920 (setq tmphist (append (mapcar 'car org-stored-links)
9921 org-insert-link-history))
9922 (setq all-prefixes (append (mapcar 'car abbrevs)
9923 (mapcar 'car org-link-abbrev-alist)
9924 org-link-types))
9925 (unwind-protect
9926 (progn
9927 (setq link
9928 (org-completing-read
9929 "Link: "
9930 (append
9931 (mapcar (lambda (x) (concat x ":"))
9932 all-prefixes)
9933 (mapcar 'car org-stored-links))
9934 nil nil nil
9935 'tmphist
9936 (caar org-stored-links)))
9937 (if (not (string-match "\\S-" link))
9938 (user-error "No link selected"))
9939 (mapc (lambda(l)
9940 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9941 org-stored-links)
9942 (if (or (member link all-prefixes)
9943 (and (equal ":" (substring link -1))
9944 (member (substring link 0 -1) all-prefixes)
9945 (setq link (substring link 0 -1))))
9946 (setq link (with-current-buffer origbuf
9947 (org-link-try-special-completion link)))))
9948 (set-window-configuration wcf)
9949 (kill-buffer "*Org Links*"))
9950 (setq entry (assoc link org-stored-links))
9951 (or entry (push link org-insert-link-history))
9952 (setq desc (or desc (nth 1 entry)))))
9954 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9955 (not org-keep-stored-link-after-insertion))
9956 (setq org-stored-links (delq (assoc link org-stored-links)
9957 org-stored-links)))
9959 (if (string-match org-plain-link-re link)
9960 ;; URL-like link, normalize the use of angular brackets.
9961 (setq link (org-remove-angle-brackets link)))
9963 ;; Check if we are linking to the current file with a search
9964 ;; option If yes, simplify the link by using only the search
9965 ;; option.
9966 (when (and buffer-file-name
9967 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9968 (let* ((path (match-string 1 link))
9969 (case-fold-search nil)
9970 (search (match-string 2 link)))
9971 (save-match-data
9972 (if (equal (file-truename buffer-file-name) (file-truename path))
9973 ;; We are linking to this same file, with a search option
9974 (setq link search)))))
9976 ;; Check if we can/should use a relative path. If yes, simplify the link
9977 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9978 (let* ((type (match-string 1 link))
9979 (path (match-string 2 link))
9980 (origpath path)
9981 (case-fold-search nil))
9982 (cond
9983 ((or (eq org-link-file-path-type 'absolute)
9984 (equal complete-file '(16)))
9985 (setq path (abbreviate-file-name (expand-file-name path))))
9986 ((eq org-link-file-path-type 'noabbrev)
9987 (setq path (expand-file-name path)))
9988 ((eq org-link-file-path-type 'relative)
9989 (setq path (file-relative-name path)))
9991 (save-match-data
9992 (if (string-match (concat "^" (regexp-quote
9993 (expand-file-name
9994 (file-name-as-directory
9995 default-directory))))
9996 (expand-file-name path))
9997 ;; We are linking a file with relative path name.
9998 (setq path (substring (expand-file-name path)
9999 (match-end 0)))
10000 (setq path (abbreviate-file-name (expand-file-name path)))))))
10001 (setq link (concat type path))
10002 (if (equal desc origpath)
10003 (setq desc path))))
10005 (if org-make-link-description-function
10006 (setq desc
10007 (or (condition-case nil
10008 (funcall org-make-link-description-function link desc)
10009 (error (progn (message "Can't get link description from `%s'"
10010 (symbol-name org-make-link-description-function))
10011 (sit-for 2) nil)))
10012 (read-string "Description: " default-description)))
10013 (if default-description (setq desc default-description)
10014 (setq desc (or (and auto-desc desc)
10015 (read-string "Description: " desc)))))
10017 (unless (string-match "\\S-" desc) (setq desc nil))
10018 (if remove (apply 'delete-region remove))
10019 (insert (org-make-link-string link desc))))
10021 (defun org-link-try-special-completion (type)
10022 "If there is completion support for link type TYPE, offer it."
10023 (let ((fun (intern (concat "org-" type "-complete-link"))))
10024 (if (functionp fun)
10025 (funcall fun)
10026 (read-string "Link (no completion support): " (concat type ":")))))
10028 (defun org-file-complete-link (&optional arg)
10029 "Create a file link using completion."
10030 (let (file link)
10031 (setq file (org-iread-file-name "File: "))
10032 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10033 (pwd1 (file-name-as-directory (abbreviate-file-name
10034 (expand-file-name ".")))))
10035 (cond
10036 ((equal arg '(16))
10037 (setq link (concat
10038 "file:"
10039 (abbreviate-file-name (expand-file-name file)))))
10040 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10041 (setq link (concat "file:" (match-string 1 file))))
10042 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10043 (expand-file-name file))
10044 (setq link (concat
10045 "file:" (match-string 1 (expand-file-name file)))))
10046 (t (setq link (concat "file:" file)))))
10047 link))
10049 (defun org-iread-file-name (&rest args)
10050 "Read-file-name using `ido-mode' speedup if available.
10051 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10052 See `read-file-name' for a description of parameters."
10053 (org-without-partial-completion
10054 (if (and org-completion-use-ido
10055 (fboundp 'ido-read-file-name)
10056 (boundp 'ido-mode) ido-mode
10057 (listp (second args)))
10058 (let ((ido-enter-matching-directory nil))
10059 (apply 'ido-read-file-name args))
10060 (apply 'read-file-name args))))
10062 (defun org-completing-read (&rest args)
10063 "Completing-read with SPACE being a normal character."
10064 (let ((enable-recursive-minibuffers t)
10065 (minibuffer-local-completion-map
10066 (copy-keymap minibuffer-local-completion-map)))
10067 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10068 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10069 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10070 (apply 'org-icompleting-read args)))
10072 (defun org-completing-read-no-i (&rest args)
10073 (let (org-completion-use-ido org-completion-use-iswitchb)
10074 (apply 'org-completing-read args)))
10076 (defun org-iswitchb-completing-read (prompt choices &rest args)
10077 "Use iswitch as a completing-read replacement to choose from choices.
10078 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10079 from."
10080 (let* ((iswitchb-use-virtual-buffers nil)
10081 (iswitchb-make-buflist-hook
10082 (lambda ()
10083 (setq iswitchb-temp-buflist choices))))
10084 (iswitchb-read-buffer prompt)))
10086 (defun org-icompleting-read (&rest args)
10087 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10088 (org-without-partial-completion
10089 (if (and org-completion-use-ido
10090 (fboundp 'ido-completing-read)
10091 (boundp 'ido-mode) ido-mode
10092 (listp (second args)))
10093 (let ((ido-enter-matching-directory nil))
10094 (apply 'ido-completing-read (concat (car args))
10095 (if (consp (car (nth 1 args)))
10096 (mapcar 'car (nth 1 args))
10097 (nth 1 args))
10098 (cddr args)))
10099 (if (and org-completion-use-iswitchb
10100 (boundp 'iswitchb-mode) iswitchb-mode
10101 (listp (second args)))
10102 (apply 'org-iswitchb-completing-read (concat (car args))
10103 (if (consp (car (nth 1 args)))
10104 (mapcar 'car (nth 1 args))
10105 (nth 1 args))
10106 (cddr args))
10107 (apply 'completing-read args)))))
10109 (defun org-extract-attributes (s)
10110 "Extract the attributes cookie from a string and set as text property."
10111 (let (a attr (start 0) key value)
10112 (save-match-data
10113 (when (string-match "{{\\([^}]+\\)}}$" s)
10114 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10115 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10116 (setq key (match-string 1 a) value (match-string 2 a)
10117 start (match-end 0)
10118 attr (plist-put attr (intern key) value))))
10119 (org-add-props s nil 'org-attr attr))
10122 ;;; Opening/following a link
10124 (defvar org-link-search-failed nil)
10126 (defvar org-open-link-functions nil
10127 "Hook for functions finding a plain text link.
10128 These functions must take a single argument, the link content.
10129 They will be called for links that look like [[link text][description]]
10130 when LINK TEXT does not have a protocol like \"http:\" and does not look
10131 like a filename (e.g. \"./blue.png\").
10133 These functions will be called *before* Org attempts to resolve the
10134 link by doing text searches in the current buffer - so if you want a
10135 link \"[[target]]\" to still find \"<<target>>\", your function should
10136 handle this as a special case.
10138 When the function does handle the link, it must return a non-nil value.
10139 If it decides that it is not responsible for this link, it must return
10140 nil to indicate that that Org-mode can continue with other options
10141 like exact and fuzzy text search.")
10143 (defun org-next-link (&optional search-backward)
10144 "Move forward to the next link.
10145 If the link is in hidden text, expose it."
10146 (interactive "P")
10147 (when (and org-link-search-failed (eq this-command last-command))
10148 (goto-char (point-min))
10149 (message "Link search wrapped back to beginning of buffer"))
10150 (setq org-link-search-failed nil)
10151 (let* ((pos (point))
10152 (ct (org-context))
10153 (a (assoc :link ct))
10154 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10155 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10156 ((looking-at org-any-link-re)
10157 ;; Don't stay stuck at link without an org-link face
10158 (forward-char (if search-backward -1 1))))
10159 (if (funcall srch-fun org-any-link-re nil t)
10160 (progn
10161 (goto-char (match-beginning 0))
10162 (if (outline-invisible-p) (org-show-context)))
10163 (goto-char pos)
10164 (setq org-link-search-failed t)
10165 (message "No further link found"))))
10167 (defun org-previous-link ()
10168 "Move backward to the previous link.
10169 If the link is in hidden text, expose it."
10170 (interactive)
10171 (funcall 'org-next-link t))
10173 (defun org-translate-link (s)
10174 "Translate a link string if a translation function has been defined."
10175 (if (and org-link-translation-function
10176 (fboundp org-link-translation-function)
10177 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10178 (progn
10179 (setq s (funcall org-link-translation-function
10180 (match-string 1 s) (match-string 2 s)))
10181 (concat (car s) ":" (cdr s)))
10184 (defun org-translate-link-from-planner (type path)
10185 "Translate a link from Emacs Planner syntax so that Org can follow it.
10186 This is still an experimental function, your mileage may vary."
10187 (cond
10188 ((member type '("http" "https" "news" "ftp"))
10189 ;; standard Internet links are the same.
10190 nil)
10191 ((and (equal type "irc") (string-match "^//" path))
10192 ;; Planner has two / at the beginning of an irc link, we have 1.
10193 ;; We should have zero, actually....
10194 (setq path (substring path 1)))
10195 ((and (equal type "lisp") (string-match "^/" path))
10196 ;; Planner has a slash, we do not.
10197 (setq type "elisp" path (substring path 1)))
10198 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10199 ;; A typical message link. Planner has the id after the final slash,
10200 ;; we separate it with a hash mark
10201 (setq path (concat (match-string 1 path) "#"
10202 (org-remove-angle-brackets (match-string 2 path))))))
10203 (cons type path))
10205 (defun org-find-file-at-mouse (ev)
10206 "Open file link or URL at mouse."
10207 (interactive "e")
10208 (mouse-set-point ev)
10209 (org-open-at-point 'in-emacs))
10211 (defun org-open-at-mouse (ev)
10212 "Open file link or URL at mouse.
10213 See the docstring of `org-open-file' for details."
10214 (interactive "e")
10215 (mouse-set-point ev)
10216 (if (eq major-mode 'org-agenda-mode)
10217 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10218 (org-open-at-point))
10220 (defvar org-window-config-before-follow-link nil
10221 "The window configuration before following a link.
10222 This is saved in case the need arises to restore it.")
10224 (defvar org-open-link-marker (make-marker)
10225 "Marker pointing to the location where `org-open-at-point; was called.")
10227 ;;;###autoload
10228 (defun org-open-at-point-global ()
10229 "Follow a link like Org-mode does.
10230 This command can be called in any mode to follow a link that has
10231 Org-mode syntax."
10232 (interactive)
10233 (org-run-like-in-org-mode 'org-open-at-point))
10235 ;;;###autoload
10236 (defun org-open-link-from-string (s &optional arg reference-buffer)
10237 "Open a link in the string S, as if it was in Org-mode."
10238 (interactive "sLink: \nP")
10239 (let ((reference-buffer (or reference-buffer (current-buffer))))
10240 (with-temp-buffer
10241 (let ((org-inhibit-startup (not reference-buffer)))
10242 (org-mode)
10243 (insert s)
10244 (goto-char (point-min))
10245 (when reference-buffer
10246 (setq org-link-abbrev-alist-local
10247 (with-current-buffer reference-buffer
10248 org-link-abbrev-alist-local)))
10249 (org-open-at-point arg reference-buffer)))))
10251 (defvar org-open-at-point-functions nil
10252 "Hook that is run when following a link at point.
10254 Functions in this hook must return t if they identify and follow
10255 a link at point. If they don't find anything interesting at point,
10256 they must return nil.")
10258 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10259 (defun org-open-at-point (&optional arg reference-buffer)
10260 "Open link at or after point.
10261 If there is no link at point, this function will search forward up to
10262 the end of the current line.
10263 Normally, files will be opened by an appropriate application. If the
10264 optional prefix argument ARG is non-nil, Emacs will visit the file.
10265 With a double prefix argument, try to open outside of Emacs, in the
10266 application the system uses for this file type."
10267 (interactive "P")
10268 ;; if in a code block, then open the block's results
10269 (unless (call-interactively #'org-babel-open-src-block-result)
10270 (org-load-modules-maybe)
10271 (move-marker org-open-link-marker (point))
10272 (setq org-window-config-before-follow-link (current-window-configuration))
10273 (org-remove-occur-highlights nil nil t)
10274 (cond
10275 ((and (org-at-heading-p)
10276 (not (org-at-timestamp-p t))
10277 (not (org-in-regexp
10278 (concat org-plain-link-re "\\|"
10279 org-bracket-link-regexp "\\|"
10280 org-angle-link-re "\\|"
10281 "[ \t]:[^ \t\n]+:[ \t]*$")))
10282 (not (get-text-property (point) 'org-linked-text)))
10283 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10284 (lk0 (car lkall))
10285 (lk (if (stringp lk0) (list lk0) lk0))
10286 (lkend (cdr lkall)))
10287 (mapcar (lambda(l)
10288 (search-forward l nil lkend)
10289 (goto-char (match-beginning 0))
10290 (org-open-at-point))
10291 lk))
10292 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10293 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10294 ((and (org-at-timestamp-p t)
10295 (not (org-in-regexp org-bracket-link-regexp)))
10296 (org-follow-timestamp-link))
10297 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10298 (not (org-in-regexp org-any-link-re)))
10299 (org-footnote-action))
10301 (let (type path link line search (pos (point)))
10302 (catch 'match
10303 (save-excursion
10304 (skip-chars-forward "^]\n\r")
10305 (when (org-in-regexp org-bracket-link-regexp 1)
10306 (setq link (org-extract-attributes
10307 (org-link-unescape (org-match-string-no-properties 1))))
10308 (while (string-match " *\n *" link)
10309 (setq link (replace-match " " t t link)))
10310 (setq link (org-link-expand-abbrev link))
10311 (cond
10312 ((or (file-name-absolute-p link)
10313 (string-match "^\\.\\.?/" link))
10314 (setq type "file" path link))
10315 ((string-match org-link-re-with-space3 link)
10316 (setq type (match-string 1 link) path (match-string 2 link)))
10317 ((string-match "^help:+\\(.+\\)" link)
10318 (setq type "help" path (match-string 1 link)))
10319 (t (setq type "thisfile" path link)))
10320 (throw 'match t)))
10322 (when (get-text-property (point) 'org-linked-text)
10323 (setq type "thisfile"
10324 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10325 (1+ (point)) (point))
10326 path (buffer-substring
10327 (or (previous-single-property-change pos 'org-linked-text)
10328 (point-min))
10329 (or (next-single-property-change pos 'org-linked-text)
10330 (point-max))))
10331 (throw 'match t))
10333 (save-excursion
10334 (when (or (org-in-regexp org-angle-link-re)
10335 (let ((match (org-in-regexp org-plain-link-re)))
10336 ;; Check a plain link is not within a bracket link
10337 (and match
10338 (save-excursion
10339 (progn
10340 (goto-char (car match))
10341 (not (org-in-regexp org-bracket-link-regexp))))))
10342 (let ((line_ending (save-excursion (end-of-line) (point))))
10343 ;; We are in a line before a plain or bracket link
10344 (or (re-search-forward org-plain-link-re line_ending t)
10345 (re-search-forward org-bracket-link-regexp line_ending t))))
10346 (setq type (match-string 1)
10347 path (org-link-unescape (match-string 2)))
10348 (throw 'match t)))
10349 (save-excursion
10350 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10351 (setq type "tags"
10352 path (match-string 1))
10353 (while (string-match ":" path)
10354 (setq path (replace-match "+" t t path)))
10355 (throw 'match t)))
10356 (when (org-in-regexp "<\\([^><\n]+\\)>")
10357 (setq type "tree-match"
10358 path (match-string 1))
10359 (throw 'match t)))
10360 (unless path
10361 (user-error "No link found"))
10363 ;; switch back to reference buffer
10364 ;; needed when if called in a temporary buffer through
10365 ;; org-open-link-from-string
10366 (with-current-buffer (or reference-buffer (current-buffer))
10368 ;; Remove any trailing spaces in path
10369 (if (string-match " +\\'" path)
10370 (setq path (replace-match "" t t path)))
10371 (if (and org-link-translation-function
10372 (fboundp org-link-translation-function))
10373 ;; Check if we need to translate the link
10374 (let ((tmp (funcall org-link-translation-function type path)))
10375 (setq type (car tmp) path (cdr tmp))))
10377 (cond
10379 ((assoc type org-link-protocols)
10380 (funcall (nth 1 (assoc type org-link-protocols)) path))
10382 ((equal type "help")
10383 (let ((f-or-v (intern path)))
10384 (cond ((fboundp f-or-v)
10385 (describe-function f-or-v))
10386 ((boundp f-or-v)
10387 (describe-variable f-or-v))
10388 (t (error "Not a known function or variable")))))
10390 ((equal type "mailto")
10391 (let ((cmd (car org-link-mailto-program))
10392 (args (cdr org-link-mailto-program)) args1
10393 (address path) (subject "") a)
10394 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10395 (setq address (match-string 1 path)
10396 subject (org-link-escape (match-string 2 path))))
10397 (while args
10398 (cond
10399 ((not (stringp (car args))) (push (pop args) args1))
10400 (t (setq a (pop args))
10401 (if (string-match "%a" a)
10402 (setq a (replace-match address t t a)))
10403 (if (string-match "%s" a)
10404 (setq a (replace-match subject t t a)))
10405 (push a args1))))
10406 (apply cmd (nreverse args1))))
10408 ((member type '("http" "https" "ftp" "news"))
10409 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10410 (org-link-escape
10411 path org-link-escape-chars-browser)
10412 path))))
10414 ((string= type "doi")
10415 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10416 (org-link-escape
10417 path org-link-escape-chars-browser)
10418 path))))
10420 ((member type '("message"))
10421 (browse-url (concat type ":" path)))
10423 ((string= type "tags")
10424 (org-tags-view arg path))
10426 ((string= type "tree-match")
10427 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10429 ((string= type "file")
10430 (if (string-match "::\\([0-9]+\\)\\'" path)
10431 (setq line (string-to-number (match-string 1 path))
10432 path (substring path 0 (match-beginning 0)))
10433 (if (string-match "::\\(.+\\)\\'" path)
10434 (setq search (match-string 1 path)
10435 path (substring path 0 (match-beginning 0)))))
10436 (if (string-match "[*?{]" (file-name-nondirectory path))
10437 (dired path)
10438 (org-open-file path arg line search)))
10440 ((string= type "shell")
10441 (let ((buf (generate-new-buffer "*Org Shell Output"))
10442 (cmd path))
10443 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10444 (string-match org-confirm-shell-link-not-regexp cmd))
10445 (not org-confirm-shell-link-function)
10446 (funcall org-confirm-shell-link-function
10447 (format "Execute \"%s\" in shell? "
10448 (org-add-props cmd nil
10449 'face 'org-warning))))
10450 (progn
10451 (message "Executing %s" cmd)
10452 (shell-command cmd buf)
10453 (if (featurep 'midnight)
10454 (setq clean-buffer-list-kill-buffer-names
10455 (cons buf clean-buffer-list-kill-buffer-names))))
10456 (error "Abort"))))
10458 ((string= type "elisp")
10459 (let ((cmd path))
10460 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10461 (string-match org-confirm-elisp-link-not-regexp cmd))
10462 (not org-confirm-elisp-link-function)
10463 (funcall org-confirm-elisp-link-function
10464 (format "Execute \"%s\" as elisp? "
10465 (org-add-props cmd nil
10466 'face 'org-warning))))
10467 (message "%s => %s" cmd
10468 (if (equal (string-to-char cmd) ?\()
10469 (eval (read cmd))
10470 (call-interactively (read cmd))))
10471 (error "Abort"))))
10473 ((and (string= type "thisfile")
10474 (run-hook-with-args-until-success
10475 'org-open-link-functions path)))
10477 ((string= type "thisfile")
10478 (if arg
10479 (switch-to-buffer-other-window
10480 (org-get-buffer-for-internal-link (current-buffer)))
10481 (org-mark-ring-push))
10482 (let ((cmd `(org-link-search
10483 ,path
10484 ,(cond ((equal arg '(4)) ''occur)
10485 ((equal arg '(16)) ''org-occur))
10486 ,pos)))
10487 (condition-case nil (let ((org-link-search-inhibit-query t))
10488 (eval cmd))
10489 (error (progn (widen) (eval cmd))))))
10491 (t (browse-url-at-point)))))))
10492 (move-marker org-open-link-marker nil)
10493 (run-hook-with-args 'org-follow-link-hook)))
10495 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10496 "Offer links in the current entry and return the selected link.
10497 If there is only one link, return it.
10498 If NTH is an integer, return the NTH link found.
10499 If ZERO is a string, check also this string for a link, and if
10500 there is one, return it."
10501 (with-current-buffer buffer
10502 (save-excursion
10503 (save-restriction
10504 (widen)
10505 (goto-char marker)
10506 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10507 "\\(" org-angle-link-re "\\)\\|"
10508 "\\(" org-plain-link-re "\\)"))
10509 (cnt ?0)
10510 (in-emacs (if (integerp nth) nil nth))
10511 have-zero end links link c)
10512 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10513 (push (match-string 0 zero) links)
10514 (setq cnt (1- cnt) have-zero t))
10515 (save-excursion
10516 (org-back-to-heading t)
10517 (setq end (save-excursion (outline-next-heading) (point)))
10518 (while (re-search-forward re end t)
10519 (push (match-string 0) links))
10520 (setq links (org-uniquify (reverse links))))
10521 (cond
10522 ((null links)
10523 (message "No links"))
10524 ((equal (length links) 1)
10525 (setq link (car links)))
10526 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10527 (setq link (nth (if have-zero nth (1- nth)) links)))
10528 (t ; we have to select a link
10529 (save-excursion
10530 (save-window-excursion
10531 (delete-other-windows)
10532 (with-output-to-temp-buffer "*Select Link*"
10533 (mapc (lambda (l)
10534 (if (not (string-match org-bracket-link-regexp l))
10535 (princ (format "[%c] %s\n" (incf cnt)
10536 (org-remove-angle-brackets l)))
10537 (if (match-end 3)
10538 (princ (format "[%c] %s (%s)\n" (incf cnt)
10539 (match-string 3 l) (match-string 1 l)))
10540 (princ (format "[%c] %s\n" (incf cnt)
10541 (match-string 1 l))))))
10542 links))
10543 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10544 (message "Select link to open, RET to open all:")
10545 (setq c (read-char-exclusive))
10546 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10547 (when (equal c ?q) (error "Abort"))
10548 (if (equal c ?\C-m)
10549 (setq link links)
10550 (setq nth (- c ?0))
10551 (if have-zero (setq nth (1+ nth)))
10552 (unless (and (integerp nth) (>= (length links) nth))
10553 (user-error "Invalid link selection"))
10554 (setq link (nth (1- nth) links)))))
10555 (cons link end))))))
10557 ;; Add special file links that specify the way of opening
10559 (org-add-link-type "file+sys" 'org-open-file-with-system)
10560 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10561 (defun org-open-file-with-system (path)
10562 "Open file at PATH using the system way of opening it."
10563 (org-open-file path 'system))
10564 (defun org-open-file-with-emacs (path)
10565 "Open file at PATH in Emacs."
10566 (org-open-file path 'emacs))
10569 ;;; File search
10571 (defvar org-create-file-search-functions nil
10572 "List of functions to construct the right search string for a file link.
10573 These functions are called in turn with point at the location to
10574 which the link should point.
10576 A function in the hook should first test if it would like to
10577 handle this file type, for example by checking the `major-mode'
10578 or the file extension. If it decides not to handle this file, it
10579 should just return nil to give other functions a chance. If it
10580 does handle the file, it must return the search string to be used
10581 when following the link. The search string will be part of the
10582 file link, given after a double colon, and `org-open-at-point'
10583 will automatically search for it. If special measures must be
10584 taken to make the search successful, another function should be
10585 added to the companion hook `org-execute-file-search-functions',
10586 which see.
10588 A function in this hook may also use `setq' to set the variable
10589 `description' to provide a suggestion for the descriptive text to
10590 be used for this link when it gets inserted into an Org-mode
10591 buffer with \\[org-insert-link].")
10593 (defvar org-execute-file-search-functions nil
10594 "List of functions to execute a file search triggered by a link.
10596 Functions added to this hook must accept a single argument, the
10597 search string that was part of the file link, the part after the
10598 double colon. The function must first check if it would like to
10599 handle this search, for example by checking the `major-mode' or
10600 the file extension. If it decides not to handle this search, it
10601 should just return nil to give other functions a chance. If it
10602 does handle the search, it must return a non-nil value to keep
10603 other functions from trying.
10605 Each function can access the current prefix argument through the
10606 variable `current-prefix-arg'. Note that a single prefix is used
10607 to force opening a link in Emacs, so it may be good to only use a
10608 numeric or double prefix to guide the search function.
10610 In case this is needed, a function in this hook can also restore
10611 the window configuration before `org-open-at-point' was called using:
10613 (set-window-configuration org-window-config-before-follow-link)")
10615 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10616 (defun org-link-search (s &optional type avoid-pos stealth)
10617 "Search for a link search option.
10618 If S is surrounded by forward slashes, it is interpreted as a
10619 regular expression. In org-mode files, this will create an `org-occur'
10620 sparse tree. In ordinary files, `occur' will be used to list matches.
10621 If the current buffer is in `dired-mode', grep will be used to search
10622 in all files. If AVOID-POS is given, ignore matches near that position.
10624 When optional argument STEALTH is non-nil, do not modify
10625 visibility around point, thus ignoring
10626 `org-show-hierarchy-above', `org-show-following-heading' and
10627 `org-show-siblings' variables."
10628 (let ((case-fold-search t)
10629 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10630 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10631 (append '(("") (" ") ("\t") ("\n"))
10632 org-emphasis-alist)
10633 "\\|") "\\)"))
10634 (pos (point))
10635 (pre nil) (post nil)
10636 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10637 (cond
10638 ;; First check if there are any special search functions
10639 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10640 ;; Now try the builtin stuff
10641 ((and (equal (string-to-char s0) ?#)
10642 (> (length s0) 1)
10643 (save-excursion
10644 (goto-char (point-min))
10645 (and
10646 (re-search-forward
10647 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10648 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10649 (setq type 'dedicated
10650 pos (match-beginning 0))))
10651 ;; There is an exact target for this
10652 (goto-char pos)
10653 (org-back-to-heading t)))
10654 ((save-excursion
10655 (goto-char (point-min))
10656 (and
10657 (re-search-forward
10658 (concat "<<" (regexp-quote s0) ">>") nil t)
10659 (setq type 'dedicated
10660 pos (match-beginning 0))))
10661 ;; There is an exact target for this
10662 (goto-char pos))
10663 ((save-excursion
10664 (goto-char (point-min))
10665 (and
10666 (re-search-forward
10667 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10668 (setq type 'dedicated pos (match-beginning 0))))
10669 ;; Found an element with a matching #+name affiliated keyword.
10670 (goto-char pos))
10671 ((and (string-match "^(\\(.*\\))$" s0)
10672 (save-excursion
10673 (goto-char (point-min))
10674 (and
10675 (re-search-forward
10676 (concat "[^[]" (regexp-quote
10677 (format org-coderef-label-format
10678 (match-string 1 s0))))
10679 nil t)
10680 (setq type 'dedicated
10681 pos (1+ (match-beginning 0))))))
10682 ;; There is a coderef target for this
10683 (goto-char pos))
10684 ((string-match "^/\\(.*\\)/$" s)
10685 ;; A regular expression
10686 (cond
10687 ((derived-mode-p 'org-mode)
10688 (org-occur (match-string 1 s)))
10689 (t (org-do-occur (match-string 1 s)))))
10690 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10691 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10692 (goto-char (point-min))
10693 (cond
10694 ((let (case-fold-search)
10695 (re-search-forward (format org-complex-heading-regexp-format
10696 (regexp-quote s))
10697 nil t))
10698 ;; OK, found a match
10699 (setq type 'dedicated)
10700 (goto-char (match-beginning 0)))
10701 ((and (not org-link-search-inhibit-query)
10702 (eq org-link-search-must-match-exact-headline 'query-to-create)
10703 (y-or-n-p "No match - create this as a new heading? "))
10704 (goto-char (point-max))
10705 (or (bolp) (newline))
10706 (insert "* " s "\n")
10707 (beginning-of-line 0))
10709 (goto-char pos)
10710 (error "No match"))))
10712 ;; A normal search string
10713 (when (equal (string-to-char s) ?*)
10714 ;; Anchor on headlines, post may include tags.
10715 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10716 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10717 s (substring s 1)))
10718 (remove-text-properties
10719 0 (length s)
10720 '(face nil mouse-face nil keymap nil fontified nil) s)
10721 ;; Make a series of regular expressions to find a match
10722 (setq words (org-split-string s "[ \n\r\t]+")
10724 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10725 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10726 "\\)" markers)
10727 re2a_ (concat "\\(" (mapconcat 'downcase words
10728 "[ \t\r\n]+") "\\)[ \t\r\n]")
10729 re2a (concat "[ \t\r\n]" re2a_)
10730 re4_ (concat "\\(" (mapconcat 'downcase words
10731 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10732 re4 (concat "[^a-zA-Z_]" re4_)
10734 re1 (concat pre re2 post)
10735 re3 (concat pre (if pre re4_ re4) post)
10736 re5 (concat pre ".*" re4)
10737 re2 (concat pre re2)
10738 re2a (concat pre (if pre re2a_ re2a))
10739 re4 (concat pre (if pre re4_ re4))
10740 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10741 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10742 re5 "\\)"))
10743 (cond
10744 ((eq type 'org-occur) (org-occur reall))
10745 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10746 (t (goto-char (point-min))
10747 (setq type 'fuzzy)
10748 (if (or (and (org-search-not-self 1 re0 nil t)
10749 (setq type 'dedicated))
10750 (org-search-not-self 1 re1 nil t)
10751 (org-search-not-self 1 re2 nil t)
10752 (org-search-not-self 1 re2a nil t)
10753 (org-search-not-self 1 re3 nil t)
10754 (org-search-not-self 1 re4 nil t)
10755 (org-search-not-self 1 re5 nil t))
10756 (goto-char (match-beginning 1))
10757 (goto-char pos)
10758 (error "No match"))))))
10759 (and (derived-mode-p 'org-mode)
10760 (not stealth)
10761 (org-show-context 'link-search))
10762 type))
10764 (defun org-search-not-self (group &rest args)
10765 "Execute `re-search-forward', but only accept matches that do not
10766 enclose the position of `org-open-link-marker'."
10767 (let ((m org-open-link-marker))
10768 (catch 'exit
10769 (while (apply 're-search-forward args)
10770 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10771 (goto-char (match-end group))
10772 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10773 (> (match-beginning 0) (marker-position m))
10774 (< (match-end 0) (marker-position m)))
10775 (save-match-data
10776 (or (not (org-in-regexp
10777 org-bracket-link-analytic-regexp 1))
10778 (not (match-end 4)) ; no description
10779 (and (<= (match-beginning 4) (point))
10780 (>= (match-end 4) (point))))))
10781 (throw 'exit (point))))))))
10783 (defun org-get-buffer-for-internal-link (buffer)
10784 "Return a buffer to be used for displaying the link target of internal links."
10785 (cond
10786 ((not org-display-internal-link-with-indirect-buffer)
10787 buffer)
10788 ((string-match "(Clone)$" (buffer-name buffer))
10789 (message "Buffer is already a clone, not making another one")
10790 ;; we also do not modify visibility in this case
10791 buffer)
10792 (t ; make a new indirect buffer for displaying the link
10793 (let* ((bn (buffer-name buffer))
10794 (ibn (concat bn "(Clone)"))
10795 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10796 (with-current-buffer ib (org-overview))
10797 ib))))
10799 (defun org-do-occur (regexp &optional cleanup)
10800 "Call the Emacs command `occur'.
10801 If CLEANUP is non-nil, remove the printout of the regular expression
10802 in the *Occur* buffer. This is useful if the regex is long and not useful
10803 to read."
10804 (occur regexp)
10805 (when cleanup
10806 (let ((cwin (selected-window)) win beg end)
10807 (when (setq win (get-buffer-window "*Occur*"))
10808 (select-window win))
10809 (goto-char (point-min))
10810 (when (re-search-forward "match[a-z]+" nil t)
10811 (setq beg (match-end 0))
10812 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10813 (setq end (1- (match-beginning 0)))))
10814 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10815 (goto-char (point-min))
10816 (select-window cwin))))
10818 ;;; The mark ring for links jumps
10820 (defvar org-mark-ring nil
10821 "Mark ring for positions before jumps in Org-mode.")
10822 (defvar org-mark-ring-last-goto nil
10823 "Last position in the mark ring used to go back.")
10824 ;; Fill and close the ring
10825 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10826 (loop for i from 1 to org-mark-ring-length do
10827 (push (make-marker) org-mark-ring))
10828 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10829 org-mark-ring)
10831 (defun org-mark-ring-push (&optional pos buffer)
10832 "Put the current position or POS into the mark ring and rotate it."
10833 (interactive)
10834 (setq pos (or pos (point)))
10835 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10836 (move-marker (car org-mark-ring)
10837 (or pos (point))
10838 (or buffer (current-buffer)))
10839 (message "%s"
10840 (substitute-command-keys
10841 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10843 (defun org-mark-ring-goto (&optional n)
10844 "Jump to the previous position in the mark ring.
10845 With prefix arg N, jump back that many stored positions. When
10846 called several times in succession, walk through the entire ring.
10847 Org-mode commands jumping to a different position in the current file,
10848 or to another Org-mode file, automatically push the old position
10849 onto the ring."
10850 (interactive "p")
10851 (let (p m)
10852 (if (eq last-command this-command)
10853 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10854 (setq p org-mark-ring))
10855 (setq org-mark-ring-last-goto p)
10856 (setq m (car p))
10857 (org-pop-to-buffer-same-window (marker-buffer m))
10858 (goto-char m)
10859 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10861 (defun org-remove-angle-brackets (s)
10862 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10863 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10865 (defun org-add-angle-brackets (s)
10866 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10867 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10869 (defun org-remove-double-quotes (s)
10870 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10871 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10874 ;;; Following specific links
10876 (defun org-follow-timestamp-link ()
10877 "Open an agenda view for the time-stamp date/range at point."
10878 (cond
10879 ((org-at-date-range-p t)
10880 (let ((org-agenda-start-on-weekday)
10881 (t1 (match-string 1))
10882 (t2 (match-string 2)) tt1 tt2)
10883 (setq tt1 (time-to-days (org-time-string-to-time t1))
10884 tt2 (time-to-days (org-time-string-to-time t2)))
10885 (let ((org-agenda-buffer-tmp-name
10886 (format "*Org Agenda(a:%s)"
10887 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10888 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10889 ((org-at-timestamp-p t)
10890 (let ((org-agenda-buffer-tmp-name
10891 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10892 (org-agenda-list nil (time-to-days (org-time-string-to-time
10893 (substring (match-string 1) 0 10)))
10894 1)))
10895 (t (error "This should not happen"))))
10898 ;;; Following file links
10899 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10900 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10901 (declare-function mailcap-mime-info
10902 "mailcap" (string &optional request no-decode))
10903 (defvar org-wait nil)
10904 (defun org-open-file (path &optional in-emacs line search)
10905 "Open the file at PATH.
10906 First, this expands any special file name abbreviations. Then the
10907 configuration variable `org-file-apps' is checked if it contains an
10908 entry for this file type, and if yes, the corresponding command is launched.
10910 If no application is found, Emacs simply visits the file.
10912 With optional prefix argument IN-EMACS, Emacs will visit the file.
10913 With a double \\[universal-argument] \\[universal-argument] \
10914 prefix arg, Org tries to avoid opening in Emacs
10915 and to use an external application to visit the file.
10917 Optional LINE specifies a line to go to, optional SEARCH a string
10918 to search for. If LINE or SEARCH is given, the file will be
10919 opened in Emacs, unless an entry from org-file-apps that makes
10920 use of groups in a regexp matches.
10922 If you want to change the way frames are used when following a
10923 link, please customize `org-link-frame-setup'.
10925 If the file does not exist, an error is thrown."
10926 (let* ((file (if (equal path "")
10927 buffer-file-name
10928 (substitute-in-file-name (expand-file-name path))))
10929 (file-apps (append org-file-apps (org-default-apps)))
10930 (apps (org-remove-if
10931 'org-file-apps-entry-match-against-dlink-p file-apps))
10932 (apps-dlink (org-remove-if-not
10933 'org-file-apps-entry-match-against-dlink-p file-apps))
10934 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10935 (dirp (if remp nil (file-directory-p file)))
10936 (file (if (and dirp org-open-directory-means-index-dot-org)
10937 (concat (file-name-as-directory file) "index.org")
10938 file))
10939 (a-m-a-p (assq 'auto-mode apps))
10940 (dfile (downcase file))
10941 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10942 (link (cond ((and (eq line nil)
10943 (eq search nil))
10944 file)
10945 (line
10946 (concat file "::" (number-to-string line)))
10947 (search
10948 (concat file "::" search))))
10949 (dlink (downcase link))
10950 (old-buffer (current-buffer))
10951 (old-pos (point))
10952 (old-mode major-mode)
10953 ext cmd link-match-data)
10954 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10955 (setq ext (match-string 1 dfile))
10956 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10957 (setq ext (match-string 1 dfile))))
10958 (cond
10959 ((member in-emacs '((16) system))
10960 (setq cmd (cdr (assoc 'system apps))))
10961 (in-emacs (setq cmd 'emacs))
10963 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10964 (and dirp (cdr (assoc 'directory apps)))
10965 ; first, try matching against apps-dlink
10966 ; if we get a match here, store the match data for later
10967 (let ((match (assoc-default dlink apps-dlink
10968 'string-match)))
10969 (if match
10970 (progn (setq link-match-data (match-data))
10971 match)
10972 (progn (setq in-emacs (or in-emacs line search))
10973 nil))) ; if we have no match in apps-dlink,
10974 ; always open the file in emacs if line or search
10975 ; is given (for backwards compatibility)
10976 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10977 'string-match)
10978 (cdr (assoc ext apps))
10979 (cdr (assoc t apps))))))
10980 (when (eq cmd 'system)
10981 (setq cmd (cdr (assoc 'system apps))))
10982 (when (eq cmd 'default)
10983 (setq cmd (cdr (assoc t apps))))
10984 (when (eq cmd 'mailcap)
10985 (require 'mailcap)
10986 (mailcap-parse-mailcaps)
10987 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10988 (command (mailcap-mime-info mime-type)))
10989 (if (stringp command)
10990 (setq cmd command)
10991 (setq cmd 'emacs))))
10992 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10993 (not (file-exists-p file))
10994 (not org-open-non-existing-files))
10995 (user-error "No such file: %s" file))
10996 (cond
10997 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10998 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10999 (while (string-match "['\"]%s['\"]" cmd)
11000 (setq cmd (replace-match "%s" t t cmd)))
11001 (while (string-match "%s" cmd)
11002 (setq cmd (replace-match
11003 (save-match-data
11004 (shell-quote-argument
11005 (convert-standard-filename file)))
11006 t t cmd)))
11008 ;; Replace "%1", "%2" etc. in command with group matches from regex
11009 (save-match-data
11010 (let ((match-index 1)
11011 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11012 (set-match-data link-match-data)
11013 (while (<= match-index number-of-groups)
11014 (let ((regex (concat "%" (number-to-string match-index)))
11015 (replace-with (match-string match-index dlink)))
11016 (while (string-match regex cmd)
11017 (setq cmd (replace-match replace-with t t cmd))))
11018 (setq match-index (+ match-index 1)))))
11020 (save-window-excursion
11021 (message "Running %s...done" cmd)
11022 (start-process-shell-command cmd nil cmd)
11023 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11024 ((or (stringp cmd)
11025 (eq cmd 'emacs))
11026 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11027 (widen)
11028 (if line (org-goto-line line)
11029 (if search (org-link-search search))))
11030 ((consp cmd)
11031 (let ((file (convert-standard-filename file)))
11032 (save-match-data
11033 (set-match-data link-match-data)
11034 (eval cmd))))
11035 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11036 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11037 (or (not (equal old-buffer (current-buffer)))
11038 (not (equal old-pos (point))))
11039 (org-mark-ring-push old-pos old-buffer))))
11041 (defun org-file-apps-entry-match-against-dlink-p (entry)
11042 "This function returns non-nil if `entry' uses a regular
11043 expression which should be matched against the whole link by
11044 org-open-file.
11046 It assumes that is the case when the entry uses a regular
11047 expression which has at least one grouping construct and the
11048 action is either a lisp form or a command string containing
11049 '%1', i.e. using at least one subexpression match as a
11050 parameter."
11051 (let ((selector (car entry))
11052 (action (cdr entry)))
11053 (if (stringp selector)
11054 (and (> (regexp-opt-depth selector) 0)
11055 (or (and (stringp action)
11056 (string-match "%[0-9]" action))
11057 (consp action)))
11058 nil)))
11060 (defun org-default-apps ()
11061 "Return the default applications for this operating system."
11062 (cond
11063 ((eq system-type 'darwin)
11064 org-file-apps-defaults-macosx)
11065 ((eq system-type 'windows-nt)
11066 org-file-apps-defaults-windowsnt)
11067 (t org-file-apps-defaults-gnu)))
11069 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11070 "Convert extensions to regular expressions in the cars of LIST.
11071 Also, weed out any non-string entries, because the return value is used
11072 only for regexp matching.
11073 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11074 point to the symbol `emacs', indicating that the file should
11075 be opened in Emacs."
11076 (append
11077 (delq nil
11078 (mapcar (lambda (x)
11079 (if (not (stringp (car x)))
11081 (if (string-match "\\W" (car x))
11083 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11084 list))
11085 (if add-auto-mode
11086 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11088 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11089 (defun org-file-remote-p (file)
11090 "Test whether FILE specifies a location on a remote system.
11091 Return non-nil if the location is indeed remote.
11093 For example, the filename \"/user@host:/foo\" specifies a location
11094 on the system \"/user@host:\"."
11095 (cond ((fboundp 'file-remote-p)
11096 (file-remote-p file))
11097 ((fboundp 'tramp-handle-file-remote-p)
11098 (tramp-handle-file-remote-p file))
11099 ((and (boundp 'ange-ftp-name-format)
11100 (string-match (car ange-ftp-name-format) file))
11101 t)))
11104 ;;;; Refiling
11106 (defun org-get-org-file ()
11107 "Read a filename, with default directory `org-directory'."
11108 (let ((default (or org-default-notes-file remember-data-file)))
11109 (read-file-name (format "File name [%s]: " default)
11110 (file-name-as-directory org-directory)
11111 default)))
11113 (defun org-notes-order-reversed-p ()
11114 "Check if the current file should receive notes in reversed order."
11115 (cond
11116 ((not org-reverse-note-order) nil)
11117 ((eq t org-reverse-note-order) t)
11118 ((not (listp org-reverse-note-order)) nil)
11119 (t (catch 'exit
11120 (let ((all org-reverse-note-order)
11121 entry)
11122 (while (setq entry (pop all))
11123 (if (string-match (car entry) buffer-file-name)
11124 (throw 'exit (cdr entry))))
11125 nil)))))
11127 (defvar org-refile-target-table nil
11128 "The list of refile targets, created by `org-refile'.")
11130 (defvar org-agenda-new-buffers nil
11131 "Buffers created to visit agenda files.")
11133 (defvar org-refile-cache nil
11134 "Cache for refile targets.")
11136 (defvar org-refile-markers nil
11137 "All the markers used for caching refile locations.")
11139 (defun org-refile-marker (pos)
11140 "Get a new refile marker, but only if caching is in use."
11141 (if (not org-refile-use-cache)
11143 (let ((m (make-marker)))
11144 (move-marker m pos)
11145 (push m org-refile-markers)
11146 m)))
11148 (defun org-refile-cache-clear ()
11149 "Clear the refile cache and disable all the markers."
11150 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11151 (setq org-refile-markers nil)
11152 (setq org-refile-cache nil)
11153 (message "Refile cache has been cleared"))
11155 (defun org-refile-cache-check-set (set)
11156 "Check if all the markers in the cache still have live buffers."
11157 (let (marker)
11158 (catch 'exit
11159 (while (and set (setq marker (nth 3 (pop set))))
11160 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11161 (when (and marker (null (marker-buffer marker)))
11162 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11163 (sit-for 3)
11164 (throw 'exit nil)))
11165 t)))
11167 (defun org-refile-cache-put (set &rest identifiers)
11168 "Push the refile targets SET into the cache, under IDENTIFIERS."
11169 (let* ((key (sha1 (prin1-to-string identifiers)))
11170 (entry (assoc key org-refile-cache)))
11171 (if entry
11172 (setcdr entry set)
11173 (push (cons key set) org-refile-cache))))
11175 (defun org-refile-cache-get (&rest identifiers)
11176 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11177 (cond
11178 ((not org-refile-cache) nil)
11179 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11181 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11182 org-refile-cache))))
11183 (and set (org-refile-cache-check-set set) set)))))
11185 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11186 "Produce a table with refile targets."
11187 (let ((case-fold-search nil)
11188 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11189 (entries (or org-refile-targets '((nil . (:level . 1)))))
11190 targets tgs txt re files f desc descre fast-path-p level pos0)
11191 (message "Getting targets...")
11192 (with-current-buffer (or default-buffer (current-buffer))
11193 (while (setq entry (pop entries))
11194 (setq files (car entry) desc (cdr entry))
11195 (setq fast-path-p nil)
11196 (cond
11197 ((null files) (setq files (list (current-buffer))))
11198 ((eq files 'org-agenda-files)
11199 (setq files (org-agenda-files 'unrestricted)))
11200 ((and (symbolp files) (fboundp files))
11201 (setq files (funcall files)))
11202 ((and (symbolp files) (boundp files))
11203 (setq files (symbol-value files))))
11204 (if (stringp files) (setq files (list files)))
11205 (cond
11206 ((eq (car desc) :tag)
11207 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11208 ((eq (car desc) :todo)
11209 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11210 ((eq (car desc) :regexp)
11211 (setq descre (cdr desc)))
11212 ((eq (car desc) :level)
11213 (setq descre (concat "^\\*\\{" (number-to-string
11214 (if org-odd-levels-only
11215 (1- (* 2 (cdr desc)))
11216 (cdr desc)))
11217 "\\}[ \t]")))
11218 ((eq (car desc) :maxlevel)
11219 (setq fast-path-p t)
11220 (setq descre (concat "^\\*\\{1," (number-to-string
11221 (if org-odd-levels-only
11222 (1- (* 2 (cdr desc)))
11223 (cdr desc)))
11224 "\\}[ \t]")))
11225 (t (error "Bad refiling target description %s" desc)))
11226 (while (setq f (pop files))
11227 (with-current-buffer
11228 (if (bufferp f) f (org-get-agenda-file-buffer f))
11230 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11231 (progn
11232 (if (bufferp f) (setq f (buffer-file-name
11233 (buffer-base-buffer f))))
11234 (setq f (and f (expand-file-name f)))
11235 (if (eq org-refile-use-outline-path 'file)
11236 (push (list (file-name-nondirectory f) f nil nil) tgs))
11237 (save-excursion
11238 (save-restriction
11239 (widen)
11240 (goto-char (point-min))
11241 (while (re-search-forward descre nil t)
11242 (goto-char (setq pos0 (point-at-bol)))
11243 (catch 'next
11244 (when org-refile-target-verify-function
11245 (save-match-data
11246 (or (funcall org-refile-target-verify-function)
11247 (throw 'next t))))
11248 (when (and (looking-at org-complex-heading-regexp)
11249 (not (member (match-string 4) excluded-entries))
11250 (match-string 4))
11251 (setq level (org-reduced-level
11252 (- (match-end 1) (match-beginning 1)))
11253 txt (org-link-display-format (match-string 4))
11254 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11255 re (format org-complex-heading-regexp-format
11256 (regexp-quote (match-string 4))))
11257 (when org-refile-use-outline-path
11258 (setq txt (mapconcat
11259 'org-protect-slash
11260 (append
11261 (if (eq org-refile-use-outline-path
11262 'file)
11263 (list (file-name-nondirectory
11264 (buffer-file-name
11265 (buffer-base-buffer))))
11266 (if (eq org-refile-use-outline-path
11267 'full-file-path)
11268 (list (buffer-file-name
11269 (buffer-base-buffer)))))
11270 (org-get-outline-path fast-path-p
11271 level txt)
11272 (list txt))
11273 "/")))
11274 (push (list txt f re (org-refile-marker (point)))
11275 tgs)))
11276 (when (= (point) pos0)
11277 ;; verification function has not moved point
11278 (goto-char (point-at-eol))))))))
11279 (when org-refile-use-cache
11280 (org-refile-cache-put tgs (buffer-file-name) descre))
11281 (setq targets (append tgs targets))))))
11282 (message "Getting targets...done")
11283 (nreverse targets)))
11285 (defun org-protect-slash (s)
11286 (while (string-match "/" s)
11287 (setq s (replace-match "\\" t t s)))
11290 (defvar org-olpa (make-vector 20 nil))
11292 (defun org-get-outline-path (&optional fastp level heading)
11293 "Return the outline path to the current entry, as a list.
11295 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11296 routine which makes outline path derivations for an entire file,
11297 avoiding backtracing. Refile target collection makes use of that."
11298 (if fastp
11299 (progn
11300 (if (> level 19)
11301 (error "Outline path failure, more than 19 levels"))
11302 (loop for i from level upto 19 do
11303 (aset org-olpa i nil))
11304 (prog1
11305 (delq nil (append org-olpa nil))
11306 (aset org-olpa level heading)))
11307 (let (rtn case-fold-search)
11308 (save-excursion
11309 (save-restriction
11310 (widen)
11311 (while (org-up-heading-safe)
11312 (when (looking-at org-complex-heading-regexp)
11313 (push (org-match-string-no-properties 4) rtn)))
11314 rtn)))))
11316 (defun org-format-outline-path (path &optional width prefix separator)
11317 "Format the outline path PATH for display.
11318 WIDTH is the maximum number of characters that is available.
11319 PREFIX is a prefix to be included in the returned string,
11320 such as the file name.
11321 SEPARATOR is inserted between the different parts of the path,
11322 the default is \"/\"."
11323 (setq width (or width 79))
11324 (if prefix (setq width (- width (length prefix))))
11325 (if (not path)
11326 (or prefix "")
11327 (let* ((nsteps (length path))
11328 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11329 (maxwidth (if (<= total-width width)
11330 10000 ;; everything fits
11331 ;; we need to shorten the level headings
11332 (/ (- width nsteps) nsteps)))
11333 (org-odd-levels-only nil)
11334 (n 0)
11335 (total (1+ (length prefix))))
11336 (setq maxwidth (max maxwidth 10))
11337 (concat prefix
11338 (if prefix (or separator "/"))
11339 (mapconcat
11340 (lambda (h)
11341 (setq n (1+ n))
11342 (if (and (= n nsteps) (< maxwidth 10000))
11343 (setq maxwidth (- total-width total)))
11344 (if (< (length h) maxwidth)
11345 (progn (setq total (+ total (length h) 1)) h)
11346 (setq h (substring h 0 (- maxwidth 2))
11347 total (+ total maxwidth 1))
11348 (if (string-match "[ \t]+\\'" h)
11349 (setq h (substring h 0 (match-beginning 0))))
11350 (setq h (concat h "..")))
11351 (org-add-props h nil 'face
11352 (nth (% (1- n) org-n-level-faces)
11353 org-level-faces))
11355 path (or separator "/"))))))
11357 (defun org-display-outline-path (&optional file current separator just-return-string)
11358 "Display the current outline path in the echo area.
11360 If FILE is non-nil, prepend the output with the file name.
11361 If CURRENT is non-nil, append the current heading to the output.
11362 SEPARATOR is passed through to `org-format-outline-path'. It separates
11363 the different parts of the path and defaults to \"/\".
11364 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11365 (interactive "P")
11366 (let* (case-fold-search
11367 message-log-max ; Don't populate the *Messages* buffer
11368 (bfn (buffer-file-name (buffer-base-buffer)))
11369 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11370 res)
11371 (if current (setq path (append path
11372 (save-excursion
11373 (org-back-to-heading t)
11374 (if (looking-at org-complex-heading-regexp)
11375 (list (match-string 4)))))))
11376 (setq res
11377 (org-format-outline-path
11378 path
11379 (1- (frame-width))
11380 (and file bfn (concat (file-name-nondirectory bfn) separator))
11381 separator))
11382 (if just-return-string
11383 (org-no-properties res)
11384 (message "%s" res))))
11386 (defvar org-refile-history nil
11387 "History for refiling operations.")
11389 (defvar org-after-refile-insert-hook nil
11390 "Hook run after `org-refile' has inserted its stuff at the new location.
11391 Note that this is still *before* the stuff will be removed from
11392 the *old* location.")
11394 (defvar org-capture-last-stored-marker)
11395 (defvar org-refile-keep nil
11396 "Non-nil means `org-refile' will copy instead of refile.")
11398 (defun org-copy ()
11399 "Like `org-refile', but copy."
11400 (interactive)
11401 (let ((org-refile-keep t))
11402 (funcall 'org-refile nil nil nil "Copy")))
11404 (defun org-refile (&optional goto default-buffer rfloc msg)
11405 "Move the entry or entries at point to another heading.
11406 The list of target headings is compiled using the information in
11407 `org-refile-targets', which see.
11409 At the target location, the entry is filed as a subitem of the target
11410 heading. Depending on `org-reverse-note-order', the new subitem will
11411 either be the first or the last subitem.
11413 If there is an active region, all entries in that region will be moved.
11414 However, the region must fulfill the requirement that the first heading
11415 is the first one sets the top-level of the moved text - at most siblings
11416 below it are allowed.
11418 With prefix arg GOTO, the command will only visit the target location
11419 and not actually move anything.
11421 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11422 go to the location where the last refiling operation has put the subtree.
11423 With a prefix argument of `2', refile to the running clock.
11425 RFLOC can be a refile location obtained in a different way.
11427 MSG is a string to replace \"Refile\" in the default prompt with
11428 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11430 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11432 If you are using target caching (see `org-refile-use-cache'),
11433 you have to clear the target cache in order to find new targets.
11434 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11435 prefix argument (`C-u C-u C-u C-c C-w')."
11437 (interactive "P")
11438 (if (member goto '(0 (64)))
11439 (org-refile-cache-clear)
11440 (let* ((actionmsg (or msg "Refile"))
11441 (cbuf (current-buffer))
11442 (regionp (org-region-active-p))
11443 (region-start (and regionp (region-beginning)))
11444 (region-end (and regionp (region-end)))
11445 (region-length (and regionp (- region-end region-start)))
11446 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11447 pos it nbuf file re level reversed)
11448 (setq last-command nil)
11449 (when regionp
11450 (goto-char region-start)
11451 (or (bolp) (goto-char (point-at-bol)))
11452 (setq region-start (point))
11453 (unless (or (org-kill-is-subtree-p
11454 (buffer-substring region-start region-end))
11455 (prog1 org-refile-active-region-within-subtree
11456 (org-toggle-heading)))
11457 (user-error "The region is not a (sequence of) subtree(s)")))
11458 (if (equal goto '(16))
11459 (org-refile-goto-last-stored)
11460 (when (or
11461 (and (equal goto 2)
11462 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11463 (prog1
11464 (setq it (list (or org-clock-heading "running clock")
11465 (buffer-file-name
11466 (marker-buffer org-clock-hd-marker))
11468 (marker-position org-clock-hd-marker)))
11469 (setq goto nil)))
11470 (setq it (or rfloc
11471 (let (heading-text)
11472 (save-excursion
11473 (unless goto
11474 (org-back-to-heading t)
11475 (setq heading-text
11476 (nth 4 (org-heading-components))))
11478 (org-refile-get-location
11479 (cond (goto "Goto")
11480 (regionp (concat actionmsg " region to"))
11481 (t (concat actionmsg " subtree \""
11482 heading-text "\" to")))
11483 default-buffer
11484 (and (not (equal '(4) goto))
11485 org-refile-allow-creating-parent-nodes)
11486 goto))))))
11487 (setq file (nth 1 it)
11488 re (nth 2 it)
11489 pos (nth 3 it))
11490 (if (and (not goto)
11492 (equal (buffer-file-name) file)
11493 (if regionp
11494 (and (>= pos region-start)
11495 (<= pos region-end))
11496 (and (>= pos (point))
11497 (< pos (save-excursion
11498 (org-end-of-subtree t t))))))
11499 (error "Cannot refile to position inside the tree or region"))
11501 (setq nbuf (or (find-buffer-visiting file)
11502 (find-file-noselect file)))
11503 (if goto
11504 (progn
11505 (org-pop-to-buffer-same-window nbuf)
11506 (goto-char pos)
11507 (org-show-context 'org-goto))
11508 (if regionp
11509 (progn
11510 (org-kill-new (buffer-substring region-start region-end))
11511 (org-save-markers-in-region region-start region-end))
11512 (org-copy-subtree 1 nil t))
11513 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11514 (find-file-noselect file)))
11515 (setq reversed (org-notes-order-reversed-p))
11516 (save-excursion
11517 (save-restriction
11518 (widen)
11519 (if pos
11520 (progn
11521 (goto-char pos)
11522 (looking-at org-outline-regexp)
11523 (setq level (org-get-valid-level (funcall outline-level) 1))
11524 (goto-char
11525 (if reversed
11526 (or (outline-next-heading) (point-max))
11527 (or (save-excursion (org-get-next-sibling))
11528 (org-end-of-subtree t t)
11529 (point-max)))))
11530 (setq level 1)
11531 (if (not reversed)
11532 (goto-char (point-max))
11533 (goto-char (point-min))
11534 (or (outline-next-heading) (goto-char (point-max)))))
11535 (if (not (bolp)) (newline))
11536 (org-paste-subtree level)
11537 (when org-log-refile
11538 (org-add-log-setup 'refile nil nil 'findpos
11539 org-log-refile)
11540 (unless (eq org-log-refile 'note)
11541 (save-excursion (org-add-log-note))))
11542 (and org-auto-align-tags
11543 (let ((org-loop-over-headlines-in-active-region nil))
11544 (org-set-tags nil t)))
11545 (with-demoted-errors
11546 (bookmark-set "org-refile-last-stored"))
11547 ;; If we are refiling for capture, make sure that the
11548 ;; last-capture pointers point here
11549 (when (org-bound-and-true-p org-refile-for-capture)
11550 (with-demoted-errors
11551 (bookmark-set "org-capture-last-stored-marker"))
11552 (move-marker org-capture-last-stored-marker (point)))
11553 (if (fboundp 'deactivate-mark) (deactivate-mark))
11554 (run-hooks 'org-after-refile-insert-hook))))
11555 (unless org-refile-keep
11556 (if regionp
11557 (delete-region (point) (+ (point) region-length))
11558 (org-cut-subtree)))
11559 (when (featurep 'org-inlinetask)
11560 (org-inlinetask-remove-END-maybe))
11561 (setq org-markers-to-move nil)
11562 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11564 (defun org-refile-goto-last-stored ()
11565 "Go to the location where the last refile was stored."
11566 (interactive)
11567 (bookmark-jump "org-refile-last-stored")
11568 (message "This is the location of the last refile"))
11570 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11571 no-exclude)
11572 "Prompt the user for a refile location, using PROMPT.
11573 PROMPT should not be suffixed with a colon and a space, because
11574 this function appends the default value from
11575 `org-refile-history' automatically, if that is not empty.
11576 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11577 this is used for the GOTO interface."
11578 (let ((org-refile-targets org-refile-targets)
11579 (org-refile-use-outline-path org-refile-use-outline-path)
11580 excluded-entries)
11581 (when (and (derived-mode-p 'org-mode)
11582 (not org-refile-use-cache)
11583 (not no-exclude))
11584 (org-map-tree
11585 (lambda()
11586 (setq excluded-entries
11587 (append excluded-entries (list (org-get-heading t t)))))))
11588 (setq org-refile-target-table
11589 (org-refile-get-targets default-buffer excluded-entries)))
11590 (unless org-refile-target-table
11591 (user-error "No refile targets"))
11592 (let* ((cbuf (current-buffer))
11593 (partial-completion-mode nil)
11594 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11595 (cfunc (if (and org-refile-use-outline-path
11596 org-outline-path-complete-in-steps)
11597 'org-olpath-completing-read
11598 'org-icompleting-read))
11599 (extra (if org-refile-use-outline-path "/" ""))
11600 (cbnex (concat (buffer-name) extra))
11601 (filename (and cfn (expand-file-name cfn)))
11602 (tbl (mapcar
11603 (lambda (x)
11604 (if (and (not (member org-refile-use-outline-path
11605 '(file full-file-path)))
11606 (not (equal filename (nth 1 x))))
11607 (cons (concat (car x) extra " ("
11608 (file-name-nondirectory (nth 1 x)) ")")
11609 (cdr x))
11610 (cons (concat (car x) extra) (cdr x))))
11611 org-refile-target-table))
11612 (completion-ignore-case t)
11613 cdef
11614 (prompt (concat prompt
11615 (or (and (car org-refile-history)
11616 (concat " (default " (car org-refile-history) ")"))
11617 (and (assoc cbnex tbl) (setq cdef cbnex)
11618 (concat " (default " cbnex ")"))) ": "))
11619 pa answ parent-target child parent old-hist)
11620 (setq old-hist org-refile-history)
11621 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11622 nil 'org-refile-history (or cdef (car org-refile-history))))
11623 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11624 (org-refile-check-position pa)
11625 (if pa
11626 (progn
11627 (when (or (not org-refile-history)
11628 (not (eq old-hist org-refile-history))
11629 (not (equal (car pa) (car org-refile-history))))
11630 (setq org-refile-history
11631 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11632 org-refile-history
11633 (cdr org-refile-history))))
11634 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11635 (pop org-refile-history)))
11637 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11638 (progn
11639 (setq parent (match-string 1 answ)
11640 child (match-string 2 answ))
11641 (setq parent-target (or (assoc parent tbl)
11642 (assoc (concat parent "/") tbl)))
11643 (when (and parent-target
11644 (or (eq new-nodes t)
11645 (and (eq new-nodes 'confirm)
11646 (y-or-n-p (format "Create new node \"%s\"? "
11647 child)))))
11648 (org-refile-new-child parent-target child)))
11649 (user-error "Invalid target location")))))
11651 (declare-function org-string-nw-p "org-macs" (s))
11652 (defun org-refile-check-position (refile-pointer)
11653 "Check if the refile pointer matches the headline to which it points."
11654 (let* ((file (nth 1 refile-pointer))
11655 (re (nth 2 refile-pointer))
11656 (pos (nth 3 refile-pointer))
11657 buffer)
11658 (if (and (not (markerp pos)) (not file))
11659 (user-error "Please save the buffer to a file before refiling")
11660 (when (org-string-nw-p re)
11661 (setq buffer (if (markerp pos)
11662 (marker-buffer pos)
11663 (or (find-buffer-visiting file)
11664 (find-file-noselect file))))
11665 (with-current-buffer buffer
11666 (save-excursion
11667 (save-restriction
11668 (widen)
11669 (goto-char pos)
11670 (beginning-of-line 1)
11671 (unless (org-looking-at-p re)
11672 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11674 (defun org-refile-new-child (parent-target child)
11675 "Use refile target PARENT-TARGET to add new CHILD below it."
11676 (unless parent-target
11677 (error "Cannot find parent for new node"))
11678 (let ((file (nth 1 parent-target))
11679 (pos (nth 3 parent-target))
11680 level)
11681 (with-current-buffer (or (find-buffer-visiting file)
11682 (find-file-noselect file))
11683 (save-excursion
11684 (save-restriction
11685 (widen)
11686 (if pos
11687 (goto-char pos)
11688 (goto-char (point-max))
11689 (if (not (bolp)) (newline)))
11690 (when (looking-at org-outline-regexp)
11691 (setq level (funcall outline-level))
11692 (org-end-of-subtree t t))
11693 (org-back-over-empty-lines)
11694 (insert "\n" (make-string
11695 (if pos (org-get-valid-level level 1) 1) ?*)
11696 " " child "\n")
11697 (beginning-of-line 0)
11698 (list (concat (car parent-target) "/" child) file "" (point)))))))
11700 (defun org-olpath-completing-read (prompt collection &rest args)
11701 "Read an outline path like a file name."
11702 (let ((thetable collection)
11703 (org-completion-use-ido nil) ; does not work with ido.
11704 (org-completion-use-iswitchb nil)) ; or iswitchb
11705 (apply
11706 'org-icompleting-read prompt
11707 (lambda (string predicate &optional flag)
11708 (let (rtn r f (l (length string)))
11709 (cond
11710 ((eq flag nil)
11711 ;; try completion
11712 (try-completion string thetable))
11713 ((eq flag t)
11714 ;; all-completions
11715 (setq rtn (all-completions string thetable predicate))
11716 (mapcar
11717 (lambda (x)
11718 (setq r (substring x l))
11719 (if (string-match " ([^)]*)$" x)
11720 (setq f (match-string 0 x))
11721 (setq f ""))
11722 (if (string-match "/" r)
11723 (concat string (substring r 0 (match-end 0)) f)
11725 rtn))
11726 ((eq flag 'lambda)
11727 ;; exact match?
11728 (assoc string thetable)))))
11729 args)))
11731 ;;;; Dynamic blocks
11733 (defun org-find-dblock (name)
11734 "Find the first dynamic block with name NAME in the buffer.
11735 If not found, stay at current position and return nil."
11736 (let ((case-fold-search t) pos)
11737 (save-excursion
11738 (goto-char (point-min))
11739 (setq pos (and (re-search-forward
11740 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11741 (match-beginning 0))))
11742 (if pos (goto-char pos))
11743 pos))
11745 (defconst org-dblock-start-re
11746 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11747 "Matches the start line of a dynamic block, with parameters.")
11749 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11750 "Matches the end of a dynamic block.")
11752 (defun org-create-dblock (plist)
11753 "Create a dynamic block section, with parameters taken from PLIST.
11754 PLIST must contain a :name entry which is used as name of the block."
11755 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11756 (end-of-line 1)
11757 (newline))
11758 (let ((col (current-column))
11759 (name (plist-get plist :name)))
11760 (insert "#+BEGIN: " name)
11761 (while plist
11762 (if (eq (car plist) :name)
11763 (setq plist (cddr plist))
11764 (insert " " (prin1-to-string (pop plist)))))
11765 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11766 (beginning-of-line -2)))
11768 (defun org-prepare-dblock ()
11769 "Prepare dynamic block for refresh.
11770 This empties the block, puts the cursor at the insert position and returns
11771 the property list including an extra property :name with the block name."
11772 (unless (looking-at org-dblock-start-re)
11773 (user-error "Not at a dynamic block"))
11774 (let* ((begdel (1+ (match-end 0)))
11775 (name (org-no-properties (match-string 1)))
11776 (params (append (list :name name)
11777 (read (concat "(" (match-string 3) ")")))))
11778 (save-excursion
11779 (beginning-of-line 1)
11780 (skip-chars-forward " \t")
11781 (setq params (plist-put params :indentation-column (current-column))))
11782 (unless (re-search-forward org-dblock-end-re nil t)
11783 (error "Dynamic block not terminated"))
11784 (setq params
11785 (append params
11786 (list :content (buffer-substring
11787 begdel (match-beginning 0)))))
11788 (delete-region begdel (match-beginning 0))
11789 (goto-char begdel)
11790 (open-line 1)
11791 params))
11793 (defun org-map-dblocks (&optional command)
11794 "Apply COMMAND to all dynamic blocks in the current buffer.
11795 If COMMAND is not given, use `org-update-dblock'."
11796 (let ((cmd (or command 'org-update-dblock)))
11797 (save-excursion
11798 (goto-char (point-min))
11799 (while (re-search-forward org-dblock-start-re nil t)
11800 (goto-char (match-beginning 0))
11801 (save-excursion
11802 (condition-case nil
11803 (funcall cmd)
11804 (error (message "Error during update of dynamic block"))))
11805 (unless (re-search-forward org-dblock-end-re nil t)
11806 (error "Dynamic block not terminated"))))))
11808 (defun org-dblock-update (&optional arg)
11809 "User command for updating dynamic blocks.
11810 Update the dynamic block at point. With prefix ARG, update all dynamic
11811 blocks in the buffer."
11812 (interactive "P")
11813 (if arg
11814 (org-update-all-dblocks)
11815 (or (looking-at org-dblock-start-re)
11816 (org-beginning-of-dblock))
11817 (org-update-dblock)))
11819 (defun org-update-dblock ()
11820 "Update the dynamic block at point.
11821 This means to empty the block, parse for parameters and then call
11822 the correct writing function."
11823 (interactive)
11824 (save-window-excursion
11825 (let* ((pos (point))
11826 (line (org-current-line))
11827 (params (org-prepare-dblock))
11828 (name (plist-get params :name))
11829 (indent (plist-get params :indentation-column))
11830 (cmd (intern (concat "org-dblock-write:" name))))
11831 (message "Updating dynamic block `%s' at line %d..." name line)
11832 (funcall cmd params)
11833 (message "Updating dynamic block `%s' at line %d...done" name line)
11834 (goto-char pos)
11835 (when (and indent (> indent 0))
11836 (setq indent (make-string indent ?\ ))
11837 (save-excursion
11838 (org-beginning-of-dblock)
11839 (forward-line 1)
11840 (while (not (looking-at org-dblock-end-re))
11841 (insert indent)
11842 (beginning-of-line 2))
11843 (when (looking-at org-dblock-end-re)
11844 (and (looking-at "[ \t]+")
11845 (replace-match ""))
11846 (insert indent)))))))
11848 (defun org-beginning-of-dblock ()
11849 "Find the beginning of the dynamic block at point.
11850 Error if there is no such block at point."
11851 (let ((pos (point))
11852 beg)
11853 (end-of-line 1)
11854 (if (and (re-search-backward org-dblock-start-re nil t)
11855 (setq beg (match-beginning 0))
11856 (re-search-forward org-dblock-end-re nil t)
11857 (> (match-end 0) pos))
11858 (goto-char beg)
11859 (goto-char pos)
11860 (error "Not in a dynamic block"))))
11862 (defun org-update-all-dblocks ()
11863 "Update all dynamic blocks in the buffer.
11864 This function can be used in a hook."
11865 (interactive)
11866 (when (derived-mode-p 'org-mode)
11867 (org-map-dblocks 'org-update-dblock)))
11870 ;;;; Completion
11872 (defun org-get-export-keywords ()
11873 "Return a list of all currently understood export keywords.
11874 Export keywords include options, block names, attributes and
11875 keywords relative to each registered export back-end."
11876 (delq nil
11877 (let (keywords)
11878 (mapc
11879 (lambda (back-end)
11880 (let ((props (cdr back-end)))
11881 ;; Back-end name (for keywords, like #+LATEX:)
11882 (push (upcase (symbol-name (car back-end))) keywords)
11883 ;; Back-end options.
11884 (mapc (lambda (option) (push (cadr option) keywords))
11885 (plist-get (cdr back-end) :options-alist))))
11886 (org-bound-and-true-p org-export-registered-backends))
11887 keywords)))
11889 (defconst org-options-keywords
11890 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11891 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11892 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11893 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11894 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11896 (defcustom org-structure-template-alist
11897 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11898 "<src lang=\"?\">\n\n</src>")
11899 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11900 "<example>\n?\n</example>")
11901 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11902 "<quote>\n?\n</quote>")
11903 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11904 "<verse>\n?\n</verse>")
11905 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11906 "<verbatim>\n?\n</verbatim>")
11907 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11908 "<center>\n?\n</center>")
11909 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11910 "<literal style=\"latex\">\n?\n</literal>")
11911 ("L" "#+LaTeX: "
11912 "<literal style=\"latex\">?</literal>")
11913 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11914 "<literal style=\"html\">\n?\n</literal>")
11915 ("H" "#+HTML: "
11916 "<literal style=\"html\">?</literal>")
11917 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11918 ("A" "#+ASCII: ")
11919 ("i" "#+INDEX: ?"
11920 "#+INDEX: ?")
11921 ("I" "#+INCLUDE: %file ?"
11922 "<include file=%file markup=\"?\">"))
11923 "Structure completion elements.
11924 This is a list of abbreviation keys and values. The value gets inserted
11925 if you type `<' followed by the key and then press the completion key,
11926 usually `M-TAB'. %file will be replaced by a file name after prompting
11927 for the file using completion. The cursor will be placed at the position
11928 of the `?` in the template.
11929 There are two templates for each key, the first uses the original Org syntax,
11930 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11931 the default when the /org-mtags.el/ module has been loaded. See also the
11932 variable `org-mtags-prefer-muse-templates'."
11933 :group 'org-completion
11934 :type '(repeat
11935 (string :tag "Key")
11936 (string :tag "Template")
11937 (string :tag "Muse Template")))
11939 (defun org-try-structure-completion ()
11940 "Try to complete a structure template before point.
11941 This looks for strings like \"<e\" on an otherwise empty line and
11942 expands them."
11943 (let ((l (buffer-substring (point-at-bol) (point)))
11945 (when (and (looking-at "[ \t]*$")
11946 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11947 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11948 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11949 (match-beginning 1)) a)
11950 t)))
11952 (defun org-complete-expand-structure-template (start cell)
11953 "Expand a structure template."
11954 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11955 (rpl (nth (if musep 2 1) cell))
11956 (ind ""))
11957 (delete-region start (point))
11958 (when (string-match "\\`#\\+" rpl)
11959 (cond
11960 ((bolp))
11961 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11962 (setq ind (buffer-substring (point-at-bol) (point))))
11963 (t (newline))))
11964 (setq start (point))
11965 (if (string-match "%file" rpl)
11966 (setq rpl (replace-match
11967 (concat
11968 "\""
11969 (save-match-data
11970 (abbreviate-file-name (read-file-name "Include file: ")))
11971 "\"")
11972 t t rpl)))
11973 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11974 (concat "\n" ind)))
11975 (insert rpl)
11976 (if (re-search-backward "\\?" start t) (delete-char 1))))
11978 ;;;; TODO, DEADLINE, Comments
11980 (defun org-toggle-comment ()
11981 "Change the COMMENT state of an entry."
11982 (interactive)
11983 (save-excursion
11984 (org-back-to-heading)
11985 (let (case-fold-search)
11986 (cond
11987 ((looking-at (format org-heading-keyword-regexp-format
11988 org-comment-string))
11989 (goto-char (match-end 1))
11990 (looking-at (concat " +" org-comment-string))
11991 (replace-match "" t t)
11992 (when (eolp) (insert " ")))
11993 ((looking-at org-outline-regexp)
11994 (goto-char (match-end 0))
11995 (insert org-comment-string " "))))))
11997 (defvar org-last-todo-state-is-todo nil
11998 "This is non-nil when the last TODO state change led to a TODO state.
11999 If the last change removed the TODO tag or switched to DONE, then
12000 this is nil.")
12002 (defvar org-setting-tags nil) ; dynamically skipped
12004 (defvar org-todo-setup-filter-hook nil
12005 "Hook for functions that pre-filter todo specs.
12006 Each function takes a todo spec and returns either nil or the spec
12007 transformed into canonical form." )
12009 (defvar org-todo-get-default-hook nil
12010 "Hook for functions that get a default item for todo.
12011 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12012 nil or a string to be used for the todo mark." )
12014 (defvar org-agenda-headline-snapshot-before-repeat)
12016 (defun org-current-effective-time ()
12017 "Return current time adjusted for `org-extend-today-until' variable."
12018 (let* ((ct (org-current-time))
12019 (dct (decode-time ct))
12020 (ct1
12021 (cond
12022 (org-use-last-clock-out-time-as-effective-time
12023 (or (org-clock-get-last-clock-out-time) ct))
12024 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12025 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12026 (t ct))))
12027 ct1))
12029 (defun org-todo-yesterday (&optional arg)
12030 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12031 (interactive "P")
12032 (if (eq major-mode 'org-agenda-mode)
12033 (apply 'org-agenda-todo-yesterday arg)
12034 (let* ((hour (third (decode-time
12035 (org-current-time))))
12036 (org-extend-today-until (1+ hour)))
12037 (org-todo arg))))
12039 (defvar org-block-entry-blocking ""
12040 "First entry preventing the TODO state change.")
12042 (defun org-todo (&optional arg)
12043 "Change the TODO state of an item.
12044 The state of an item is given by a keyword at the start of the heading,
12045 like
12046 *** TODO Write paper
12047 *** DONE Call mom
12049 The different keywords are specified in the variable `org-todo-keywords'.
12050 By default the available states are \"TODO\" and \"DONE\".
12051 So for this example: when the item starts with TODO, it is changed to DONE.
12052 When it starts with DONE, the DONE is removed. And when neither TODO nor
12053 DONE are present, add TODO at the beginning of the heading.
12055 With \\[universal-argument] prefix arg, use completion to determine the new \
12056 state.
12057 With numeric prefix arg, switch to that state.
12058 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12059 keywords (nextset).
12060 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12061 With a numeric prefix arg of 0, inhibit note taking for the change.
12063 For calling through lisp, arg is also interpreted in the following way:
12064 'none -> empty state
12065 \"\"(empty string) -> switch to empty state
12066 'done -> switch to DONE
12067 'nextset -> switch to the next set of keywords
12068 'previousset -> switch to the previous set of keywords
12069 \"WAITING\" -> switch to the specified keyword, but only if it
12070 really is a member of `org-todo-keywords'."
12071 (interactive "P")
12072 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12073 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12074 'region-start-level 'region))
12075 org-loop-over-headlines-in-active-region)
12076 (org-map-entries
12077 `(org-todo ,arg)
12078 org-loop-over-headlines-in-active-region
12079 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12080 (if (equal arg '(16)) (setq arg 'nextset))
12081 (let ((org-blocker-hook org-blocker-hook)
12082 commentp
12083 case-fold-search)
12084 (when (equal arg '(64))
12085 (setq arg nil org-blocker-hook nil))
12086 (when (and org-blocker-hook
12087 (or org-inhibit-blocking
12088 (org-entry-get nil "NOBLOCKING")))
12089 (setq org-blocker-hook nil))
12090 (save-excursion
12091 (catch 'exit
12092 (org-back-to-heading t)
12093 (when (looking-at (concat "^\\*+ " org-comment-string))
12094 (org-toggle-comment)
12095 (setq commentp t))
12096 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12097 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12098 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12099 (let* ((match-data (match-data))
12100 (startpos (point-at-bol))
12101 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12102 (org-log-done org-log-done)
12103 (org-log-repeat org-log-repeat)
12104 (org-todo-log-states org-todo-log-states)
12105 (org-inhibit-logging
12106 (if (equal arg 0)
12107 (progn (setq arg nil) 'note) org-inhibit-logging))
12108 (this (match-string 1))
12109 (hl-pos (match-beginning 0))
12110 (head (org-get-todo-sequence-head this))
12111 (ass (assoc head org-todo-kwd-alist))
12112 (interpret (nth 1 ass))
12113 (done-word (nth 3 ass))
12114 (final-done-word (nth 4 ass))
12115 (org-last-state (or this ""))
12116 (completion-ignore-case t)
12117 (member (member this org-todo-keywords-1))
12118 (tail (cdr member))
12119 (org-state (cond
12120 ((and org-todo-key-trigger
12121 (or (and (equal arg '(4))
12122 (eq org-use-fast-todo-selection 'prefix))
12123 (and (not arg) org-use-fast-todo-selection
12124 (not (eq org-use-fast-todo-selection
12125 'prefix)))))
12126 ;; Use fast selection
12127 (org-fast-todo-selection))
12128 ((and (equal arg '(4))
12129 (or (not org-use-fast-todo-selection)
12130 (not org-todo-key-trigger)))
12131 ;; Read a state with completion
12132 (org-icompleting-read
12133 "State: " (mapcar 'list org-todo-keywords-1)
12134 nil t))
12135 ((eq arg 'right)
12136 (if this
12137 (if tail (car tail) nil)
12138 (car org-todo-keywords-1)))
12139 ((eq arg 'left)
12140 (if (equal member org-todo-keywords-1)
12142 (if this
12143 (nth (- (length org-todo-keywords-1)
12144 (length tail) 2)
12145 org-todo-keywords-1)
12146 (org-last org-todo-keywords-1))))
12147 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12148 (setq arg nil))) ; hack to fall back to cycling
12149 (arg
12150 ;; user or caller requests a specific state
12151 (cond
12152 ((equal arg "") nil)
12153 ((eq arg 'none) nil)
12154 ((eq arg 'done) (or done-word (car org-done-keywords)))
12155 ((eq arg 'nextset)
12156 (or (car (cdr (member head org-todo-heads)))
12157 (car org-todo-heads)))
12158 ((eq arg 'previousset)
12159 (let ((org-todo-heads (reverse org-todo-heads)))
12160 (or (car (cdr (member head org-todo-heads)))
12161 (car org-todo-heads))))
12162 ((car (member arg org-todo-keywords-1)))
12163 ((stringp arg)
12164 (user-error "State `%s' not valid in this file" arg))
12165 ((nth (1- (prefix-numeric-value arg))
12166 org-todo-keywords-1))))
12167 ((null member) (or head (car org-todo-keywords-1)))
12168 ((equal this final-done-word) nil) ;; -> make empty
12169 ((null tail) nil) ;; -> first entry
12170 ((memq interpret '(type priority))
12171 (if (eq this-command last-command)
12172 (car tail)
12173 (if (> (length tail) 0)
12174 (or done-word (car org-done-keywords))
12175 nil)))
12177 (car tail))))
12178 (org-state (or
12179 (run-hook-with-args-until-success
12180 'org-todo-get-default-hook org-state org-last-state)
12181 org-state))
12182 (next (if org-state (concat " " org-state " ") " "))
12183 (change-plist (list :type 'todo-state-change :from this :to org-state
12184 :position startpos))
12185 dolog now-done-p)
12186 (when org-blocker-hook
12187 (setq org-last-todo-state-is-todo
12188 (not (member this org-done-keywords)))
12189 (unless (save-excursion
12190 (save-match-data
12191 (org-with-wide-buffer
12192 (run-hook-with-args-until-failure
12193 'org-blocker-hook change-plist))))
12194 (if (org-called-interactively-p 'interactive)
12195 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12196 this org-state org-block-entry-blocking)
12197 ;; fail silently
12198 (message "TODO state change from %s to %s blocked (by \"%s\")"
12199 this org-state org-block-entry-blocking)
12200 (throw 'exit nil))))
12201 (store-match-data match-data)
12202 (replace-match next t t)
12203 (unless (pos-visible-in-window-p hl-pos)
12204 (message "TODO state changed to %s" (org-trim next)))
12205 (unless head
12206 (setq head (org-get-todo-sequence-head org-state)
12207 ass (assoc head org-todo-kwd-alist)
12208 interpret (nth 1 ass)
12209 done-word (nth 3 ass)
12210 final-done-word (nth 4 ass)))
12211 (when (memq arg '(nextset previousset))
12212 (message "Keyword-Set %d/%d: %s"
12213 (- (length org-todo-sets) -1
12214 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12215 (length org-todo-sets)
12216 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12217 (setq org-last-todo-state-is-todo
12218 (not (member org-state org-done-keywords)))
12219 (setq now-done-p (and (member org-state org-done-keywords)
12220 (not (member this org-done-keywords))))
12221 (and logging (org-local-logging logging))
12222 (when (and (or org-todo-log-states org-log-done)
12223 (not (eq org-inhibit-logging t))
12224 (not (memq arg '(nextset previousset))))
12225 ;; we need to look at recording a time and note
12226 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12227 (nth 2 (assoc this org-todo-log-states))))
12228 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12229 (setq dolog 'time))
12230 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12231 (and org-state
12232 (member org-state org-not-done-keywords)
12233 (not (member this org-not-done-keywords))))
12234 ;; This is now a todo state and was not one before
12235 ;; If there was a CLOSED time stamp, get rid of it.
12236 (org-add-planning-info nil nil 'closed))
12237 (when (and now-done-p org-log-done)
12238 ;; It is now done, and it was not done before
12239 (org-add-planning-info 'closed (org-current-effective-time))
12240 (if (and (not dolog) (eq 'note org-log-done))
12241 (org-add-log-setup 'done org-state this 'findpos 'note)))
12242 (when (and org-state dolog)
12243 ;; This is a non-nil state, and we need to log it
12244 (org-add-log-setup 'state org-state this 'findpos dolog)))
12245 ;; Fixup tag positioning
12246 (org-todo-trigger-tag-changes org-state)
12247 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12248 (when org-provide-todo-statistics
12249 (org-update-parent-todo-statistics))
12250 (run-hooks 'org-after-todo-state-change-hook)
12251 (if (and arg (not (member org-state org-done-keywords)))
12252 (setq head (org-get-todo-sequence-head org-state)))
12253 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12254 ;; Do we need to trigger a repeat?
12255 (when now-done-p
12256 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12257 ;; This is for the agenda, take a snapshot of the headline.
12258 (save-match-data
12259 (setq org-agenda-headline-snapshot-before-repeat
12260 (org-get-heading))))
12261 (org-auto-repeat-maybe org-state))
12262 ;; Fixup cursor location if close to the keyword
12263 (if (and (outline-on-heading-p)
12264 (not (bolp))
12265 (save-excursion (beginning-of-line 1)
12266 (looking-at org-todo-line-regexp))
12267 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12268 (progn
12269 (goto-char (or (match-end 2) (match-end 1)))
12270 (and (looking-at " ") (just-one-space))))
12271 (when org-trigger-hook
12272 (save-excursion
12273 (run-hook-with-args 'org-trigger-hook change-plist)))
12274 (when commentp (org-toggle-comment))))))))
12276 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12277 "Block turning an entry into a TODO, using the hierarchy.
12278 This checks whether the current task should be blocked from state
12279 changes. Such blocking occurs when:
12281 1. The task has children which are not all in a completed state.
12283 2. A task has a parent with the property :ORDERED:, and there
12284 are siblings prior to the current task with incomplete
12285 status.
12287 3. The parent of the task is blocked because it has siblings that should
12288 be done first, or is child of a block grandparent TODO entry."
12290 (if (not org-enforce-todo-dependencies)
12291 t ; if locally turned off don't block
12292 (catch 'dont-block
12293 ;; If this is not a todo state change, or if this entry is already DONE,
12294 ;; do not block
12295 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12296 (member (plist-get change-plist :from)
12297 (cons 'done org-done-keywords))
12298 (member (plist-get change-plist :to)
12299 (cons 'todo org-not-done-keywords))
12300 (not (plist-get change-plist :to)))
12301 (throw 'dont-block t))
12302 ;; If this task has children, and any are undone, it's blocked
12303 (save-excursion
12304 (org-back-to-heading t)
12305 (let ((this-level (funcall outline-level)))
12306 (outline-next-heading)
12307 (let ((child-level (funcall outline-level)))
12308 (while (and (not (eobp))
12309 (> child-level this-level))
12310 ;; this todo has children, check whether they are all
12311 ;; completed
12312 (if (and (not (org-entry-is-done-p))
12313 (org-entry-is-todo-p))
12314 (progn (setq org-block-entry-blocking (org-get-heading))
12315 (throw 'dont-block nil)))
12316 (outline-next-heading)
12317 (setq child-level (funcall outline-level))))))
12318 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12319 ;; any previous siblings are undone, it's blocked
12320 (save-excursion
12321 (org-back-to-heading t)
12322 (let* ((pos (point))
12323 (parent-pos (and (org-up-heading-safe) (point))))
12324 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12325 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12326 (forward-line 1)
12327 (re-search-forward org-not-done-heading-regexp pos t))
12328 (setq org-block-entry-blocking (match-string 0))
12329 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12330 ;; Search further up the hierarchy, to see if an ancestor is blocked
12331 (while t
12332 (goto-char parent-pos)
12333 (if (not (looking-at org-not-done-heading-regexp))
12334 (throw 'dont-block t)) ; do not block, parent is not a TODO
12335 (setq pos (point))
12336 (setq parent-pos (and (org-up-heading-safe) (point)))
12337 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12338 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12339 (forward-line 1)
12340 (re-search-forward org-not-done-heading-regexp pos t)
12341 (setq org-block-entry-blocking (org-get-heading)))
12342 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12344 (defcustom org-track-ordered-property-with-tag nil
12345 "Should the ORDERED property also be shown as a tag?
12346 The ORDERED property decides if an entry should require subtasks to be
12347 completed in sequence. Since a property is not very visible, setting
12348 this option means that toggling the ORDERED property with the command
12349 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12350 not relevant for the behavior, but it makes things more visible.
12352 Note that toggling the tag with tags commands will not change the property
12353 and therefore not influence behavior!
12355 This can be t, meaning the tag ORDERED should be used, It can also be a
12356 string to select a different tag for this task."
12357 :group 'org-todo
12358 :type '(choice
12359 (const :tag "No tracking" nil)
12360 (const :tag "Track with ORDERED tag" t)
12361 (string :tag "Use other tag")))
12363 (defun org-toggle-ordered-property ()
12364 "Toggle the ORDERED property of the current entry.
12365 For better visibility, you can track the value of this property with a tag.
12366 See variable `org-track-ordered-property-with-tag'."
12367 (interactive)
12368 (let* ((t1 org-track-ordered-property-with-tag)
12369 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12370 (save-excursion
12371 (org-back-to-heading)
12372 (if (org-entry-get nil "ORDERED")
12373 (progn
12374 (org-delete-property "ORDERED" "PROPERTIES")
12375 (and tag (org-toggle-tag tag 'off))
12376 (message "Subtasks can be completed in arbitrary order"))
12377 (org-entry-put nil "ORDERED" "t")
12378 (and tag (org-toggle-tag tag 'on))
12379 (message "Subtasks must be completed in sequence")))))
12381 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12382 (defun org-block-todo-from-checkboxes (change-plist)
12383 "Block turning an entry into a TODO, using checkboxes.
12384 This checks whether the current task should be blocked from state
12385 changes because there are unchecked boxes in this entry."
12386 (if (not org-enforce-todo-checkbox-dependencies)
12387 t ; if locally turned off don't block
12388 (catch 'dont-block
12389 ;; If this is not a todo state change, or if this entry is already DONE,
12390 ;; do not block
12391 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12392 (member (plist-get change-plist :from)
12393 (cons 'done org-done-keywords))
12394 (member (plist-get change-plist :to)
12395 (cons 'todo org-not-done-keywords))
12396 (not (plist-get change-plist :to)))
12397 (throw 'dont-block t))
12398 ;; If this task has checkboxes that are not checked, it's blocked
12399 (save-excursion
12400 (org-back-to-heading t)
12401 (let ((beg (point)) end)
12402 (outline-next-heading)
12403 (setq end (point))
12404 (goto-char beg)
12405 (if (org-list-search-forward
12406 (concat (org-item-beginning-re)
12407 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12408 "\\[[- ]\\]")
12409 end t)
12410 (progn
12411 (if (boundp 'org-blocked-by-checkboxes)
12412 (setq org-blocked-by-checkboxes t))
12413 (throw 'dont-block nil)))))
12414 t))) ; do not block
12416 (defun org-entry-blocked-p ()
12417 "Is the current entry blocked?"
12418 (org-with-silent-modifications
12419 (if (org-entry-get nil "NOBLOCKING")
12420 nil ;; Never block this entry
12421 (not (run-hook-with-args-until-failure
12422 'org-blocker-hook
12423 (list :type 'todo-state-change
12424 :position (point)
12425 :from 'todo
12426 :to 'done))))))
12428 (defun org-update-statistics-cookies (all)
12429 "Update the statistics cookie, either from TODO or from checkboxes.
12430 This should be called with the cursor in a line with a statistics cookie."
12431 (interactive "P")
12432 (if all
12433 (progn
12434 (org-update-checkbox-count 'all)
12435 (org-map-entries 'org-update-parent-todo-statistics))
12436 (if (not (org-at-heading-p))
12437 (org-update-checkbox-count)
12438 (let ((pos (point-marker))
12439 end l1 l2)
12440 (ignore-errors (org-back-to-heading t))
12441 (if (not (org-at-heading-p))
12442 (org-update-checkbox-count)
12443 (setq l1 (org-outline-level))
12444 (setq end (save-excursion
12445 (outline-next-heading)
12446 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12447 (point)))
12448 (if (and (save-excursion
12449 (re-search-forward
12450 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12451 (not (save-excursion (re-search-forward
12452 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12453 (org-update-checkbox-count)
12454 (if (and l2 (> l2 l1))
12455 (progn
12456 (goto-char end)
12457 (org-update-parent-todo-statistics))
12458 (goto-char pos)
12459 (beginning-of-line 1)
12460 (while (re-search-forward
12461 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12462 (point-at-eol) t)
12463 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12464 (goto-char pos)
12465 (move-marker pos nil)))))
12467 (defvar org-entry-property-inherited-from) ;; defined below
12468 (defun org-update-parent-todo-statistics ()
12469 "Update any statistics cookie in the parent of the current headline.
12470 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12471 the entire subtree and this will travel up the hierarchy and update
12472 statistics everywhere."
12473 (let* ((prop (save-excursion (org-up-heading-safe)
12474 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12475 (recursive (or (not org-hierarchical-todo-statistics)
12476 (and prop (string-match "\\<recursive\\>" prop))))
12477 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12479 (first t)
12480 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12481 level ltoggle l1 new ndel
12482 (cnt-all 0) (cnt-done 0) is-percent kwd
12483 checkbox-beg ov ovs ove cookie-present)
12484 (catch 'exit
12485 (save-excursion
12486 (beginning-of-line 1)
12487 (setq ltoggle (funcall outline-level))
12488 ;; Three situations are to consider:
12490 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12491 ;; to the top-level ancestor on the headline;
12493 ;; 2. If parent has "recursive" property, repeat up to the
12494 ;; headline setting that property, taking inheritance into
12495 ;; account;
12497 ;; 3. Else, move up to direct parent and proceed only once.
12498 (while (and (setq level (org-up-heading-safe))
12499 (or recursive first)
12500 (>= (point) lim))
12501 (setq first nil cookie-present nil)
12502 (unless (and level
12503 (not (string-match
12504 "\\<checkbox\\>"
12505 (downcase (or (org-entry-get nil "COOKIE_DATA")
12506 "")))))
12507 (throw 'exit nil))
12508 (while (re-search-forward box-re (point-at-eol) t)
12509 (setq cnt-all 0 cnt-done 0 cookie-present t)
12510 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12511 (save-match-data
12512 (unless (outline-next-heading) (throw 'exit nil))
12513 (while (and (looking-at org-complex-heading-regexp)
12514 (> (setq l1 (length (match-string 1))) level))
12515 (setq kwd (and (or recursive (= l1 ltoggle))
12516 (match-string 2)))
12517 (if (or (eq org-provide-todo-statistics 'all-headlines)
12518 (and (listp org-provide-todo-statistics)
12519 (or (member kwd org-provide-todo-statistics)
12520 (member kwd org-done-keywords))))
12521 (setq cnt-all (1+ cnt-all))
12522 (if (eq org-provide-todo-statistics t)
12523 (and kwd (setq cnt-all (1+ cnt-all)))))
12524 (and (member kwd org-done-keywords)
12525 (setq cnt-done (1+ cnt-done)))
12526 (outline-next-heading)))
12527 (setq new
12528 (if is-percent
12529 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12530 (format "[%d/%d]" cnt-done cnt-all))
12531 ndel (- (match-end 0) checkbox-beg))
12532 ;; handle overlays when updating cookie from column view
12533 (when (setq ov (car (overlays-at checkbox-beg)))
12534 (setq ovs (overlay-start ov) ove (overlay-end ov))
12535 (delete-overlay ov))
12536 (goto-char checkbox-beg)
12537 (insert new)
12538 (delete-region (point) (+ (point) ndel))
12539 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12540 (when ov (move-overlay ov ovs ove)))
12541 (when cookie-present
12542 (run-hook-with-args 'org-after-todo-statistics-hook
12543 cnt-done (- cnt-all cnt-done))))))
12544 (run-hooks 'org-todo-statistics-hook)))
12546 (defvar org-after-todo-statistics-hook nil
12547 "Hook that is called after a TODO statistics cookie has been updated.
12548 Each function is called with two arguments: the number of not-done entries
12549 and the number of done entries.
12551 For example, the following function, when added to this hook, will switch
12552 an entry to DONE when all children are done, and back to TODO when new
12553 entries are set to a TODO status. Note that this hook is only called
12554 when there is a statistics cookie in the headline!
12556 (defun org-summary-todo (n-done n-not-done)
12557 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12558 (let (org-log-done org-log-states) ; turn off logging
12559 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12562 (defvar org-todo-statistics-hook nil
12563 "Hook that is run whenever Org thinks TODO statistics should be updated.
12564 This hook runs even if there is no statistics cookie present, in which case
12565 `org-after-todo-statistics-hook' would not run.")
12567 (defun org-todo-trigger-tag-changes (state)
12568 "Apply the changes defined in `org-todo-state-tags-triggers'."
12569 (let ((l org-todo-state-tags-triggers)
12570 changes)
12571 (when (or (not state) (equal state ""))
12572 (setq changes (append changes (cdr (assoc "" l)))))
12573 (when (and (stringp state) (> (length state) 0))
12574 (setq changes (append changes (cdr (assoc state l)))))
12575 (when (member state org-not-done-keywords)
12576 (setq changes (append changes (cdr (assoc 'todo l)))))
12577 (when (member state org-done-keywords)
12578 (setq changes (append changes (cdr (assoc 'done l)))))
12579 (dolist (c changes)
12580 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12582 (defun org-local-logging (value)
12583 "Get logging settings from a property VALUE."
12584 (let* (words w a)
12585 ;; directly set the variables, they are already local.
12586 (setq org-log-done nil
12587 org-log-repeat nil
12588 org-todo-log-states nil)
12589 (setq words (org-split-string value))
12590 (while (setq w (pop words))
12591 (cond
12592 ((setq a (assoc w org-startup-options))
12593 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12594 (set (nth 1 a) (nth 2 a))))
12595 ((setq a (org-extract-log-state-settings w))
12596 (and (member (car a) org-todo-keywords-1)
12597 (push a org-todo-log-states)))))))
12599 (defun org-get-todo-sequence-head (kwd)
12600 "Return the head of the TODO sequence to which KWD belongs.
12601 If KWD is not set, check if there is a text property remembering the
12602 right sequence."
12603 (let (p)
12604 (cond
12605 ((not kwd)
12606 (or (get-text-property (point-at-bol) 'org-todo-head)
12607 (progn
12608 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12609 nil (point-at-eol)))
12610 (get-text-property p 'org-todo-head))))
12611 ((not (member kwd org-todo-keywords-1))
12612 (car org-todo-keywords-1))
12613 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12615 (defun org-fast-todo-selection ()
12616 "Fast TODO keyword selection with single keys.
12617 Returns the new TODO keyword, or nil if no state change should occur."
12618 (let* ((fulltable org-todo-key-alist)
12619 (done-keywords org-done-keywords) ;; needed for the faces.
12620 (maxlen (apply 'max (mapcar
12621 (lambda (x)
12622 (if (stringp (car x)) (string-width (car x)) 0))
12623 fulltable)))
12624 (expert nil)
12625 (fwidth (+ maxlen 3 1 3))
12626 (ncol (/ (- (window-width) 4) fwidth))
12627 tg cnt e c tbl
12628 groups ingroup)
12629 (save-excursion
12630 (save-window-excursion
12631 (if expert
12632 (set-buffer (get-buffer-create " *Org todo*"))
12633 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12634 (erase-buffer)
12635 (org-set-local 'org-done-keywords done-keywords)
12636 (setq tbl fulltable cnt 0)
12637 (while (setq e (pop tbl))
12638 (cond
12639 ((equal e '(:startgroup))
12640 (push '() groups) (setq ingroup t)
12641 (when (not (= cnt 0))
12642 (setq cnt 0)
12643 (insert "\n"))
12644 (insert "{ "))
12645 ((equal e '(:endgroup))
12646 (setq ingroup nil cnt 0)
12647 (insert "}\n"))
12648 ((equal e '(:newline))
12649 (when (not (= cnt 0))
12650 (setq cnt 0)
12651 (insert "\n")
12652 (setq e (car tbl))
12653 (while (equal (car tbl) '(:newline))
12654 (insert "\n")
12655 (setq tbl (cdr tbl)))))
12657 (setq tg (car e) c (cdr e))
12658 (if ingroup (push tg (car groups)))
12659 (setq tg (org-add-props tg nil 'face
12660 (org-get-todo-face tg)))
12661 (if (and (= cnt 0) (not ingroup)) (insert " "))
12662 (insert "[" c "] " tg (make-string
12663 (- fwidth 4 (length tg)) ?\ ))
12664 (when (= (setq cnt (1+ cnt)) ncol)
12665 (insert "\n")
12666 (if ingroup (insert " "))
12667 (setq cnt 0)))))
12668 (insert "\n")
12669 (goto-char (point-min))
12670 (if (not expert) (org-fit-window-to-buffer))
12671 (message "[a-z..]:Set [SPC]:clear")
12672 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12673 (cond
12674 ((or (= c ?\C-g)
12675 (and (= c ?q) (not (rassoc c fulltable))))
12676 (setq quit-flag t))
12677 ((= c ?\ ) nil)
12678 ((setq e (rassoc c fulltable) tg (car e))
12680 (t (setq quit-flag t)))))))
12682 (defun org-entry-is-todo-p ()
12683 (member (org-get-todo-state) org-not-done-keywords))
12685 (defun org-entry-is-done-p ()
12686 (member (org-get-todo-state) org-done-keywords))
12688 (defun org-get-todo-state ()
12689 "Return the TODO keyword of the current subtree."
12690 (save-excursion
12691 (org-back-to-heading t)
12692 (and (looking-at org-todo-line-regexp)
12693 (match-end 2)
12694 (match-string 2))))
12696 (defun org-at-date-range-p (&optional inactive-ok)
12697 "Is the cursor inside a date range?"
12698 (interactive)
12699 (save-excursion
12700 (catch 'exit
12701 (let ((pos (point)))
12702 (skip-chars-backward "^[<\r\n")
12703 (skip-chars-backward "<[")
12704 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12705 (>= (match-end 0) pos)
12706 (throw 'exit t))
12707 (skip-chars-backward "^<[\r\n")
12708 (skip-chars-backward "<[")
12709 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12710 (>= (match-end 0) pos)
12711 (throw 'exit t)))
12712 nil)))
12714 (defun org-get-repeat (&optional tagline)
12715 "Check if there is a deadline/schedule with repeater in this entry."
12716 (save-match-data
12717 (save-excursion
12718 (org-back-to-heading t)
12719 (and (re-search-forward (if tagline
12720 (concat tagline "\\s-*" org-repeat-re)
12721 org-repeat-re)
12722 (org-entry-end-position) t)
12723 (match-string-no-properties 1)))))
12725 (defvar org-last-changed-timestamp)
12726 (defvar org-last-inserted-timestamp)
12727 (defvar org-log-post-message)
12728 (defvar org-log-note-purpose)
12729 (defvar org-log-note-how)
12730 (defvar org-log-note-extra)
12731 (defun org-auto-repeat-maybe (done-word)
12732 "Check if the current headline contains a repeated deadline/schedule.
12733 If yes, set TODO state back to what it was and change the base date
12734 of repeating deadline/scheduled time stamps to new date.
12735 This function is run automatically after each state change to a DONE state."
12736 ;; last-state is dynamically scoped into this function
12737 (let* ((repeat (org-get-repeat))
12738 (aa (assoc org-last-state org-todo-kwd-alist))
12739 (interpret (nth 1 aa))
12740 (head (nth 2 aa))
12741 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12742 (msg "Entry repeats: ")
12743 (org-log-done nil)
12744 (org-todo-log-states nil)
12745 re type n what ts time to-state)
12746 (when repeat
12747 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12748 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12749 org-todo-repeat-to-state))
12750 (unless (and to-state (member to-state org-todo-keywords-1))
12751 (setq to-state (if (eq interpret 'type) org-last-state head)))
12752 (org-todo to-state)
12753 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12754 (org-entry-put nil "LAST_REPEAT" (format-time-string
12755 (org-time-stamp-format t t))))
12756 (when org-log-repeat
12757 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12758 (memq 'org-add-log-note post-command-hook))
12759 ;; OK, we are already setup for some record
12760 (if (eq org-log-repeat 'note)
12761 ;; make sure we take a note, not only a time stamp
12762 (setq org-log-note-how 'note))
12763 ;; Set up for taking a record
12764 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12765 org-last-state
12766 'findpos org-log-repeat)))
12767 (org-back-to-heading t)
12768 (org-add-planning-info nil nil 'closed)
12769 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12770 org-deadline-time-regexp "\\)\\|\\("
12771 org-ts-regexp "\\)"))
12772 (while (re-search-forward
12773 re (save-excursion (outline-next-heading) (point)) t)
12774 (setq type (if (match-end 1) org-scheduled-string
12775 (if (match-end 3) org-deadline-string "Plain:"))
12776 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12777 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12778 (setq n (string-to-number (match-string 2 ts))
12779 what (match-string 3 ts))
12780 (if (equal what "w") (setq n (* n 7) what "d"))
12781 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12782 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12783 ;; Preparation, see if we need to modify the start date for the change
12784 (when (match-end 1)
12785 (setq time (save-match-data (org-time-string-to-time ts)))
12786 (cond
12787 ((equal (match-string 1 ts) ".")
12788 ;; Shift starting date to today
12789 (org-timestamp-change
12790 (- (org-today) (time-to-days time))
12791 'day))
12792 ((equal (match-string 1 ts) "+")
12793 (let ((nshiftmax 10) (nshift 0))
12794 (while (or (= nshift 0)
12795 (<= (time-to-days time)
12796 (time-to-days (current-time))))
12797 (when (= (incf nshift) nshiftmax)
12798 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12799 (error "Abort")))
12800 (org-timestamp-change n (cdr (assoc what whata)))
12801 (org-at-timestamp-p t)
12802 (setq ts (match-string 1))
12803 (setq time (save-match-data (org-time-string-to-time ts)))))
12804 (org-timestamp-change (- n) (cdr (assoc what whata)))
12805 ;; rematch, so that we have everything in place for the real shift
12806 (org-at-timestamp-p t)
12807 (setq ts (match-string 1))
12808 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12809 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12810 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12811 (setq org-log-post-message msg)
12812 (message "%s" msg))))
12814 (defun org-show-todo-tree (arg)
12815 "Make a compact tree which shows all headlines marked with TODO.
12816 The tree will show the lines where the regexp matches, and all higher
12817 headlines above the match.
12818 With a \\[universal-argument] prefix, prompt for a regexp to match.
12819 With a numeric prefix N, construct a sparse tree for the Nth element
12820 of `org-todo-keywords-1'."
12821 (interactive "P")
12822 (let ((case-fold-search nil)
12823 (kwd-re
12824 (cond ((null arg) org-not-done-regexp)
12825 ((equal arg '(4))
12826 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12827 (mapcar 'list org-todo-keywords-1))))
12828 (concat "\\("
12829 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12830 "\\)\\>")))
12831 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12832 (regexp-quote (nth (1- (prefix-numeric-value arg))
12833 org-todo-keywords-1)))
12834 (t (user-error "Invalid prefix argument: %s" arg)))))
12835 (message "%d TODO entries found"
12836 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12838 (defun org-deadline (arg &optional time)
12839 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12840 With one universal prefix argument, remove any deadline from the item.
12841 With two universal prefix arguments, prompt for a warning delay.
12842 With argument TIME, set the deadline at the corresponding date. TIME
12843 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12844 (interactive "P")
12845 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12846 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12847 'region-start-level 'region))
12848 org-loop-over-headlines-in-active-region)
12849 (org-map-entries
12850 `(org-deadline ',arg ,time)
12851 org-loop-over-headlines-in-active-region
12852 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12853 (let* ((old-date (org-entry-get nil "DEADLINE"))
12854 (old-date-time (if old-date (org-time-string-to-time old-date)))
12855 (repeater (and old-date
12856 (string-match
12857 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12858 old-date)
12859 (match-string 1 old-date))))
12860 (cond
12861 ((equal arg '(4))
12862 (when (and old-date org-log-redeadline)
12863 (org-add-log-setup 'deldeadline nil old-date 'findpos
12864 org-log-redeadline))
12865 (org-remove-timestamp-with-keyword org-deadline-string)
12866 (message "Item no longer has a deadline."))
12867 ((equal arg '(16))
12868 (save-excursion
12869 (if (re-search-forward
12870 org-deadline-time-regexp
12871 (save-excursion (outline-next-heading) (point)) t)
12872 (let* ((rpl0 (match-string 1))
12873 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12874 (replace-match
12875 (concat org-deadline-string
12876 " <" rpl
12877 (format " -%dd"
12878 (abs
12879 (- (time-to-days
12880 (save-match-data
12881 (org-read-date nil t nil "Warn starting from" old-date-time)))
12882 (time-to-days old-date-time))))
12883 ">") t t))
12884 (user-error "No deadline information to update"))))
12886 (org-add-planning-info 'deadline time 'closed)
12887 (when (and old-date org-log-redeadline
12888 (not (equal old-date
12889 (substring org-last-inserted-timestamp 1 -1))))
12890 (org-add-log-setup 'redeadline nil old-date 'findpos
12891 org-log-redeadline))
12892 (when repeater
12893 (save-excursion
12894 (org-back-to-heading t)
12895 (when (re-search-forward (concat org-deadline-string " "
12896 org-last-inserted-timestamp)
12897 (save-excursion
12898 (outline-next-heading) (point)) t)
12899 (goto-char (1- (match-end 0)))
12900 (insert " " repeater)
12901 (setq org-last-inserted-timestamp
12902 (concat (substring org-last-inserted-timestamp 0 -1)
12903 " " repeater
12904 (substring org-last-inserted-timestamp -1))))))
12905 (message "Deadline on %s" org-last-inserted-timestamp))))))
12907 (defun org-schedule (arg &optional time)
12908 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12909 With one universal prefix argument, remove any scheduling date from the item.
12910 With two universal prefix arguments, prompt for a delay cookie.
12911 With argument TIME, scheduled at the corresponding date. TIME can
12912 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12913 (interactive "P")
12914 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12915 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12916 'region-start-level 'region))
12917 org-loop-over-headlines-in-active-region)
12918 (org-map-entries
12919 `(org-schedule ',arg ,time)
12920 org-loop-over-headlines-in-active-region
12921 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12922 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12923 (old-date-time (if old-date (org-time-string-to-time old-date)))
12924 (repeater (and old-date
12925 (string-match
12926 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12927 old-date)
12928 (match-string 1 old-date))))
12929 (cond
12930 ((equal arg '(4))
12931 (progn
12932 (when (and old-date org-log-reschedule)
12933 (org-add-log-setup 'delschedule nil old-date 'findpos
12934 org-log-reschedule))
12935 (org-remove-timestamp-with-keyword org-scheduled-string)
12936 (message "Item is no longer scheduled.")))
12937 ((equal arg '(16))
12938 (save-excursion
12939 (if (re-search-forward
12940 org-scheduled-time-regexp
12941 (save-excursion (outline-next-heading) (point)) t)
12942 (let* ((rpl0 (match-string 1))
12943 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12944 (replace-match
12945 (concat org-scheduled-string
12946 " <" rpl
12947 (format " -%dd"
12948 (abs
12949 (- (time-to-days
12950 (save-match-data
12951 (org-read-date nil t nil "Delay until" old-date-time)))
12952 (time-to-days old-date-time))))
12953 ">") t t))
12954 (user-error "No scheduled information to update"))))
12956 (org-add-planning-info 'scheduled time 'closed)
12957 (when (and old-date org-log-reschedule
12958 (not (equal old-date
12959 (substring org-last-inserted-timestamp 1 -1))))
12960 (org-add-log-setup 'reschedule nil old-date 'findpos
12961 org-log-reschedule))
12962 (when repeater
12963 (save-excursion
12964 (org-back-to-heading t)
12965 (when (re-search-forward (concat org-scheduled-string " "
12966 org-last-inserted-timestamp)
12967 (save-excursion
12968 (outline-next-heading) (point)) t)
12969 (goto-char (1- (match-end 0)))
12970 (insert " " repeater)
12971 (setq org-last-inserted-timestamp
12972 (concat (substring org-last-inserted-timestamp 0 -1)
12973 " " repeater
12974 (substring org-last-inserted-timestamp -1))))))
12975 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12977 (defun org-get-scheduled-time (pom &optional inherit)
12978 "Get the scheduled time as a time tuple, of a format suitable
12979 for calling org-schedule with, or if there is no scheduling,
12980 returns nil."
12981 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12982 (when time
12983 (apply 'encode-time (org-parse-time-string time)))))
12985 (defun org-get-deadline-time (pom &optional inherit)
12986 "Get the deadline as a time tuple, of a format suitable for
12987 calling org-deadline with, or if there is no scheduling, returns
12988 nil."
12989 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12990 (when time
12991 (apply 'encode-time (org-parse-time-string time)))))
12993 (defun org-remove-timestamp-with-keyword (keyword)
12994 "Remove all time stamps with KEYWORD in the current entry."
12995 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12996 beg)
12997 (save-excursion
12998 (org-back-to-heading t)
12999 (setq beg (point))
13000 (outline-next-heading)
13001 (while (re-search-backward re beg t)
13002 (replace-match "")
13003 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13004 (equal (char-before) ?\ ))
13005 (backward-delete-char 1)
13006 (if (string-match "^[ \t]*$" (buffer-substring
13007 (point-at-bol) (point-at-eol)))
13008 (delete-region (point-at-bol)
13009 (min (point-max) (1+ (point-at-eol))))))))))
13011 (defun org-add-planning-info (what &optional time &rest remove)
13012 "Insert new timestamp with keyword in the line directly after the headline.
13013 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13014 If non is given, the user is prompted for a date.
13015 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13016 be removed."
13017 (interactive)
13018 (let (org-time-was-given org-end-time-was-given ts
13019 end default-time default-input)
13021 (catch 'exit
13022 (when (and (memq what '(scheduled deadline))
13023 (or (not time)
13024 (and (stringp time)
13025 (string-match "^[-+]+[0-9]" time))))
13026 ;; Try to get a default date/time from existing timestamp
13027 (save-excursion
13028 (org-back-to-heading t)
13029 (setq end (save-excursion (outline-next-heading) (point)))
13030 (when (re-search-forward (if (eq what 'scheduled)
13031 org-scheduled-time-regexp
13032 org-deadline-time-regexp)
13033 end t)
13034 (setq ts (match-string 1)
13035 default-time
13036 (apply 'encode-time (org-parse-time-string ts))
13037 default-input (and ts (org-get-compact-tod ts))))))
13038 (when what
13039 (setq time
13040 (if (stringp time)
13041 ;; This is a string (relative or absolute), set proper date
13042 (apply 'encode-time
13043 (org-read-date-analyze
13044 time default-time (decode-time default-time)))
13045 ;; If necessary, get the time from the user
13046 (or time (org-read-date nil 'to-time nil nil
13047 default-time default-input)))))
13049 (when (and org-insert-labeled-timestamps-at-point
13050 (member what '(scheduled deadline)))
13051 (insert
13052 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13053 (org-insert-time-stamp time org-time-was-given
13054 nil nil nil (list org-end-time-was-given))
13055 (setq what nil))
13056 (save-excursion
13057 (save-restriction
13058 (let (col list elt ts buffer-invisibility-spec)
13059 (org-back-to-heading t)
13060 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13061 (goto-char (match-end 1))
13062 (setq col (current-column))
13063 (goto-char (match-end 0))
13064 (if (eobp) (insert "\n") (forward-char 1))
13065 (when (and (not what)
13066 (not (looking-at
13067 (concat "[ \t]*"
13068 org-keyword-time-not-clock-regexp))))
13069 ;; Nothing to add, nothing to remove...... :-)
13070 (throw 'exit nil))
13071 (if (and (not (looking-at org-outline-regexp))
13072 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13073 "[^\r\n]*"))
13074 (not (equal (match-string 1) org-clock-string)))
13075 (narrow-to-region (match-beginning 0) (match-end 0))
13076 (insert-before-markers "\n")
13077 (backward-char 1)
13078 (narrow-to-region (point) (point))
13079 (and org-adapt-indentation (org-indent-to-column col)))
13080 ;; Check if we have to remove something.
13081 (setq list (cons what remove))
13082 (while list
13083 (setq elt (pop list))
13084 (when (or (and (eq elt 'scheduled)
13085 (re-search-forward org-scheduled-time-regexp nil t))
13086 (and (eq elt 'deadline)
13087 (re-search-forward org-deadline-time-regexp nil t))
13088 (and (eq elt 'closed)
13089 (re-search-forward org-closed-time-regexp nil t)))
13090 (replace-match "")
13091 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13092 (and (looking-at "[ \t]+") (replace-match ""))
13093 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13094 (when what
13095 (insert
13096 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13097 (cond ((eq what 'scheduled) org-scheduled-string)
13098 ((eq what 'deadline) org-deadline-string)
13099 ((eq what 'closed) org-closed-string))
13100 " ")
13101 (setq ts (org-insert-time-stamp
13102 time
13103 (or org-time-was-given
13104 (and (eq what 'closed) org-log-done-with-time))
13105 (eq what 'closed)
13106 nil nil (list org-end-time-was-given)))
13107 (insert
13108 (if (not (or (bolp) (eq (char-before) ?\ )
13109 (memq (char-after) '(32 10))
13110 (eobp))) " " ""))
13111 (end-of-line 1))
13112 (goto-char (point-min))
13113 (widen)
13114 (if (and (looking-at "[ \t]*\n")
13115 (equal (char-before) ?\n))
13116 (delete-region (1- (point)) (point-at-eol)))
13117 ts))))))
13119 (defvar org-log-note-marker (make-marker))
13120 (defvar org-log-note-purpose nil)
13121 (defvar org-log-note-state nil)
13122 (defvar org-log-note-previous-state nil)
13123 (defvar org-log-note-how nil)
13124 (defvar org-log-note-extra nil)
13125 (defvar org-log-note-window-configuration nil)
13126 (defvar org-log-note-return-to (make-marker))
13127 (defvar org-log-note-effective-time nil
13128 "Remembered current time so that dynamically scoped
13129 `org-extend-today-until' affects tha timestamps in state change
13130 log")
13132 (defvar org-log-post-message nil
13133 "Message to be displayed after a log note has been stored.
13134 The auto-repeater uses this.")
13136 (defun org-add-note ()
13137 "Add a note to the current entry.
13138 This is done in the same way as adding a state change note."
13139 (interactive)
13140 (org-add-log-setup 'note nil nil 'findpos nil))
13142 (defvar org-property-end-re)
13143 (defun org-add-log-setup (&optional purpose state prev-state
13144 findpos how extra)
13145 "Set up the post command hook to take a note.
13146 If this is about to TODO state change, the new state is expected in STATE.
13147 When FINDPOS is non-nil, find the correct position for the note in
13148 the current entry. If not, assume that it can be inserted at point.
13149 HOW is an indicator what kind of note should be created.
13150 EXTRA is additional text that will be inserted into the notes buffer."
13151 (let* ((org-log-into-drawer (org-log-into-drawer))
13152 (drawer (cond ((stringp org-log-into-drawer)
13153 org-log-into-drawer)
13154 (org-log-into-drawer "LOGBOOK"))))
13155 (save-restriction
13156 (save-excursion
13157 (when findpos
13158 (org-back-to-heading t)
13159 (narrow-to-region (point) (save-excursion
13160 (outline-next-heading) (point)))
13161 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13162 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13163 "[^\r\n]*\\)?"))
13164 (goto-char (match-end 0))
13165 (cond
13166 (drawer
13167 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13168 nil t)
13169 (progn
13170 (goto-char (match-end 0))
13171 (or org-log-states-order-reversed
13172 (and (re-search-forward org-property-end-re nil t)
13173 (goto-char (1- (match-beginning 0))))))
13174 (insert "\n:" drawer ":\n:END:")
13175 (beginning-of-line 0)
13176 (org-indent-line)
13177 (beginning-of-line 2)
13178 (org-indent-line)
13179 (end-of-line 0)))
13180 ((and org-log-state-notes-insert-after-drawers
13181 (save-excursion
13182 (forward-line) (looking-at org-drawer-regexp)))
13183 (forward-line)
13184 (while (looking-at org-drawer-regexp)
13185 (goto-char (match-end 0))
13186 (re-search-forward org-property-end-re (point-max) t)
13187 (forward-line))
13188 (forward-line -1)))
13189 (unless org-log-states-order-reversed
13190 (and (= (char-after) ?\n) (forward-char 1))
13191 (org-skip-over-state-notes)
13192 (skip-chars-backward " \t\n\r")))
13193 (move-marker org-log-note-marker (point))
13194 (setq org-log-note-purpose purpose
13195 org-log-note-state state
13196 org-log-note-previous-state prev-state
13197 org-log-note-how how
13198 org-log-note-extra extra
13199 org-log-note-effective-time (org-current-effective-time))
13200 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13202 (defun org-skip-over-state-notes ()
13203 "Skip past the list of State notes in an entry."
13204 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13205 (when (ignore-errors (goto-char (org-in-item-p)))
13206 (let* ((struct (org-list-struct))
13207 (prevs (org-list-prevs-alist struct)))
13208 (while (looking-at "[ \t]*- State")
13209 (goto-char (or (org-list-get-next-item (point) struct prevs)
13210 (org-list-get-item-end (point) struct)))))))
13212 (defun org-add-log-note (&optional purpose)
13213 "Pop up a window for taking a note, and add this note later at point."
13214 (remove-hook 'post-command-hook 'org-add-log-note)
13215 (setq org-log-note-window-configuration (current-window-configuration))
13216 (delete-other-windows)
13217 (move-marker org-log-note-return-to (point))
13218 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13219 (goto-char org-log-note-marker)
13220 (org-switch-to-buffer-other-window "*Org Note*")
13221 (erase-buffer)
13222 (if (memq org-log-note-how '(time state))
13223 (let (current-prefix-arg) (org-store-log-note))
13224 (let ((org-inhibit-startup t)) (org-mode))
13225 (insert (format "# Insert note for %s.
13226 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13227 (cond
13228 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13229 ((eq org-log-note-purpose 'done) "closed todo item")
13230 ((eq org-log-note-purpose 'state)
13231 (format "state change from \"%s\" to \"%s\""
13232 (or org-log-note-previous-state "")
13233 (or org-log-note-state "")))
13234 ((eq org-log-note-purpose 'reschedule)
13235 "rescheduling")
13236 ((eq org-log-note-purpose 'delschedule)
13237 "no longer scheduled")
13238 ((eq org-log-note-purpose 'redeadline)
13239 "changing deadline")
13240 ((eq org-log-note-purpose 'deldeadline)
13241 "removing deadline")
13242 ((eq org-log-note-purpose 'refile)
13243 "refiling")
13244 ((eq org-log-note-purpose 'note)
13245 "this entry")
13246 (t (error "This should not happen")))))
13247 (if org-log-note-extra (insert org-log-note-extra))
13248 (org-set-local 'org-finish-function 'org-store-log-note)
13249 (run-hooks 'org-log-buffer-setup-hook)))
13251 (defvar org-note-abort nil) ; dynamically scoped
13252 (defun org-store-log-note ()
13253 "Finish taking a log note, and insert it to where it belongs."
13254 (let ((txt (buffer-string)))
13255 (kill-buffer (current-buffer))
13256 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13257 lines ind bul)
13258 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13259 (setq txt (replace-match "" t t txt)))
13260 (if (string-match "\\s-+\\'" txt)
13261 (setq txt (replace-match "" t t txt)))
13262 (setq lines (org-split-string txt "\n"))
13263 (when (and note (string-match "\\S-" note))
13264 (setq note
13265 (org-replace-escapes
13266 note
13267 (list (cons "%u" (user-login-name))
13268 (cons "%U" user-full-name)
13269 (cons "%t" (format-time-string
13270 (org-time-stamp-format 'long 'inactive)
13271 org-log-note-effective-time))
13272 (cons "%T" (format-time-string
13273 (org-time-stamp-format 'long nil)
13274 org-log-note-effective-time))
13275 (cons "%d" (format-time-string
13276 (org-time-stamp-format nil 'inactive)
13277 org-log-note-effective-time))
13278 (cons "%D" (format-time-string
13279 (org-time-stamp-format nil nil)
13280 org-log-note-effective-time))
13281 (cons "%s" (if org-log-note-state
13282 (concat "\"" org-log-note-state "\"")
13283 ""))
13284 (cons "%S" (if org-log-note-previous-state
13285 (concat "\"" org-log-note-previous-state "\"")
13286 "\"\"")))))
13287 (if lines (setq note (concat note " \\\\")))
13288 (push note lines))
13289 (when (or current-prefix-arg org-note-abort)
13290 (when org-log-into-drawer
13291 (org-remove-empty-drawer-at
13292 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13293 org-log-note-marker))
13294 (setq lines nil))
13295 (when lines
13296 (with-current-buffer (marker-buffer org-log-note-marker)
13297 (save-excursion
13298 (goto-char org-log-note-marker)
13299 (move-marker org-log-note-marker nil)
13300 (end-of-line 1)
13301 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13302 (setq ind (save-excursion
13303 (if (ignore-errors (goto-char (org-in-item-p)))
13304 (let ((struct (org-list-struct)))
13305 (org-list-get-ind
13306 (org-list-get-top-point struct) struct))
13307 (skip-chars-backward " \r\t\n")
13308 (cond
13309 ((and (org-at-heading-p)
13310 org-adapt-indentation)
13311 (1+ (org-current-level)))
13312 ((org-at-heading-p) 0)
13313 (t (org-get-indentation))))))
13314 (setq bul (org-list-bullet-string "-"))
13315 (org-indent-line-to ind)
13316 (insert bul (pop lines))
13317 (let ((ind-body (+ (length bul) ind)))
13318 (while lines
13319 (insert "\n")
13320 (org-indent-line-to ind-body)
13321 (insert (pop lines))))
13322 (message "Note stored")
13323 (org-back-to-heading t)
13324 (org-cycle-hide-drawers 'children))
13325 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13326 ;; from within `org-add-log-note' because `buffer-undo-list'
13327 ;; is then modified outside of `org-with-remote-undo'.
13328 (when (eq this-command 'org-agenda-todo)
13329 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13330 ;; Don't add undo information when called from `org-agenda-todo'
13331 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13332 (set-window-configuration org-log-note-window-configuration)
13333 (with-current-buffer (marker-buffer org-log-note-return-to)
13334 (goto-char org-log-note-return-to))
13335 (move-marker org-log-note-return-to nil)
13336 (and org-log-post-message (message "%s" org-log-post-message))))
13338 (defun org-remove-empty-drawer-at (drawer pos)
13339 "Remove an empty drawer DRAWER at position POS.
13340 POS may also be a marker."
13341 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13342 (save-excursion
13343 (save-restriction
13344 (widen)
13345 (goto-char pos)
13346 (if (org-in-regexp
13347 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13348 (replace-match ""))))))
13350 (defvar org-ts-type nil)
13351 (defun org-sparse-tree (&optional arg type)
13352 "Create a sparse tree, prompt for the details.
13353 This command can create sparse trees. You first need to select the type
13354 of match used to create the tree:
13356 t Show all TODO entries.
13357 T Show entries with a specific TODO keyword.
13358 m Show entries selected by a tags/property match.
13359 p Enter a property name and its value (both with completion on existing
13360 names/values) and show entries with that property.
13361 r Show entries matching a regular expression (`/' can be used as well).
13362 b Show deadlines and scheduled items before a date.
13363 a Show deadlines and scheduled items after a date.
13364 d Show deadlines due within `org-deadline-warning-days'.
13365 D Show deadlines and scheduled items between a date range."
13366 (interactive "P")
13367 (let (ans kwd value ts-type)
13368 (setq type (or type org-sparse-tree-default-date-type))
13369 (setq org-ts-type type)
13370 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
13371 (cond ((eq type 'all) "all timestamps")
13372 ((eq type 'scheduled) "only scheduled")
13373 ((eq type 'deadline) "only deadline")
13374 ((eq type 'active) "only active timestamps")
13375 ((eq type 'inactive) "only inactive timestamps")
13376 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13377 ((eq type 'closed) "with a closed time-stamp")
13378 (t "scheduled/deadline")))
13379 (setq ans (read-char-exclusive))
13380 (cond
13381 ((equal ans ?c)
13382 (org-sparse-tree
13383 arg (cadr (member type '(scheduled-or-deadline
13384 all scheduled deadline active inactive closed)))))
13385 ((equal ans ?d)
13386 (call-interactively 'org-check-deadlines))
13387 ((equal ans ?b)
13388 (call-interactively 'org-check-before-date))
13389 ((equal ans ?a)
13390 (call-interactively 'org-check-after-date))
13391 ((equal ans ?D)
13392 (call-interactively 'org-check-dates-range))
13393 ((equal ans ?t)
13394 (call-interactively 'org-show-todo-tree))
13395 ((equal ans ?T)
13396 (org-show-todo-tree '(4)))
13397 ((member ans '(?T ?m))
13398 (call-interactively 'org-match-sparse-tree))
13399 ((member ans '(?p ?P))
13400 (setq kwd (org-icompleting-read "Property: "
13401 (mapcar 'list (org-buffer-property-keys))))
13402 (setq value (org-icompleting-read "Value: "
13403 (mapcar 'list (org-property-values kwd))))
13404 (unless (string-match "\\`{.*}\\'" value)
13405 (setq value (concat "\"" value "\"")))
13406 (org-match-sparse-tree arg (concat kwd "=" value)))
13407 ((member ans '(?r ?R ?/))
13408 (call-interactively 'org-occur))
13409 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13411 (defvar org-occur-highlights nil
13412 "List of overlays used for occur matches.")
13413 (make-variable-buffer-local 'org-occur-highlights)
13414 (defvar org-occur-parameters nil
13415 "Parameters of the active org-occur calls.
13416 This is a list, each call to org-occur pushes as cons cell,
13417 containing the regular expression and the callback, onto the list.
13418 The list can contain several entries if `org-occur' has been called
13419 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13420 will only contain one set of parameters. When the highlights are
13421 removed (for example with `C-c C-c', or with the next edit (depending
13422 on `org-remove-highlights-with-change'), this variable is emptied
13423 as well.")
13424 (make-variable-buffer-local 'org-occur-parameters)
13426 (defun org-occur (regexp &optional keep-previous callback)
13427 "Make a compact tree which shows all matches of REGEXP.
13428 The tree will show the lines where the regexp matches, and all higher
13429 headlines above the match. It will also show the heading after the match,
13430 to make sure editing the matching entry is easy.
13431 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13432 call to `org-occur' will be kept, to allow stacking of calls to this
13433 command.
13434 If CALLBACK is non-nil, it is a function which is called to confirm
13435 that the match should indeed be shown."
13436 (interactive "sRegexp: \nP")
13437 (when (equal regexp "")
13438 (user-error "Regexp cannot be empty"))
13439 (unless keep-previous
13440 (org-remove-occur-highlights nil nil t))
13441 (push (cons regexp callback) org-occur-parameters)
13442 (let ((cnt 0))
13443 (save-excursion
13444 (goto-char (point-min))
13445 (if (or (not keep-previous) ; do not want to keep
13446 (not org-occur-highlights)) ; no previous matches
13447 ;; hide everything
13448 (org-overview))
13449 (while (re-search-forward regexp nil t)
13450 (when (or (not callback)
13451 (save-match-data (funcall callback)))
13452 (setq cnt (1+ cnt))
13453 (when org-highlight-sparse-tree-matches
13454 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13455 (org-show-context 'occur-tree))))
13456 (when org-remove-highlights-with-change
13457 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13458 nil 'local))
13459 (unless org-sparse-tree-open-archived-trees
13460 (org-hide-archived-subtrees (point-min) (point-max)))
13461 (run-hooks 'org-occur-hook)
13462 (if (org-called-interactively-p 'interactive)
13463 (message "%d match(es) for regexp %s" cnt regexp))
13464 cnt))
13466 (defun org-occur-next-match (&optional n reset)
13467 "Function for `next-error-function' to find sparse tree matches.
13468 N is the number of matches to move, when negative move backwards.
13469 RESET is entirely ignored - this function always goes back to the
13470 starting point when no match is found."
13471 (let* ((limit (if (< n 0) (point-min) (point-max)))
13472 (search-func (if (< n 0)
13473 'previous-single-char-property-change
13474 'next-single-char-property-change))
13475 (n (abs n))
13476 (pos (point))
13478 (catch 'exit
13479 (while (setq p1 (funcall search-func (point) 'org-type))
13480 (when (equal p1 limit)
13481 (goto-char pos)
13482 (error "No more matches"))
13483 (when (equal (get-char-property p1 'org-type) 'org-occur)
13484 (setq n (1- n))
13485 (when (= n 0)
13486 (goto-char p1)
13487 (throw 'exit (point))))
13488 (goto-char p1))
13489 (goto-char p1)
13490 (error "No more matches"))))
13492 (defun org-show-context (&optional key)
13493 "Make sure point and context are visible.
13494 How much context is shown depends upon the variables
13495 `org-show-hierarchy-above', `org-show-following-heading',
13496 `org-show-entry-below' and `org-show-siblings'."
13497 (let ((heading-p (org-at-heading-p t))
13498 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13499 (following-p (org-get-alist-option org-show-following-heading key))
13500 (entry-p (org-get-alist-option org-show-entry-below key))
13501 (siblings-p (org-get-alist-option org-show-siblings key)))
13502 ;; Show heading or entry text
13503 (if (and heading-p (not entry-p))
13504 (org-flag-heading nil) ; only show the heading
13505 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13506 (org-show-hidden-entry))) ; show entire entry
13507 (when following-p
13508 ;; Show next sibling, or heading below text
13509 (save-excursion
13510 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13511 (org-flag-heading nil))))
13512 (when siblings-p (org-show-siblings))
13513 (when hierarchy-p
13514 ;; show all higher headings, possibly with siblings
13515 (save-excursion
13516 (while (and (condition-case nil
13517 (progn (org-up-heading-all 1) t)
13518 (error nil))
13519 (not (bobp)))
13520 (org-flag-heading nil)
13521 (when siblings-p (org-show-siblings)))))
13522 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13524 (defvar org-reveal-start-hook nil
13525 "Hook run before revealing a location.")
13527 (defun org-reveal (&optional siblings)
13528 "Show current entry, hierarchy above it, and the following headline.
13529 This can be used to show a consistent set of context around locations
13530 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13531 not t for the search context.
13533 With optional argument SIBLINGS, on each level of the hierarchy all
13534 siblings are shown. This repairs the tree structure to what it would
13535 look like when opened with hierarchical calls to `org-cycle'.
13536 With double optional argument \\[universal-argument] \\[universal-argument], \
13537 go to the parent and show the
13538 entire tree."
13539 (interactive "P")
13540 (run-hooks 'org-reveal-start-hook)
13541 (let ((org-show-hierarchy-above t)
13542 (org-show-following-heading t)
13543 (org-show-siblings (if siblings t org-show-siblings)))
13544 (org-show-context nil))
13545 (when (equal siblings '(16))
13546 (save-excursion
13547 (when (org-up-heading-safe)
13548 (org-show-subtree)
13549 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13551 (defun org-highlight-new-match (beg end)
13552 "Highlight from BEG to END and mark the highlight is an occur headline."
13553 (let ((ov (make-overlay beg end)))
13554 (overlay-put ov 'face 'secondary-selection)
13555 (overlay-put ov 'org-type 'org-occur)
13556 (push ov org-occur-highlights)))
13558 (defun org-remove-occur-highlights (&optional beg end noremove)
13559 "Remove the occur highlights from the buffer.
13560 BEG and END are ignored. If NOREMOVE is nil, remove this function
13561 from the `before-change-functions' in the current buffer."
13562 (interactive)
13563 (unless org-inhibit-highlight-removal
13564 (mapc 'delete-overlay org-occur-highlights)
13565 (setq org-occur-highlights nil)
13566 (setq org-occur-parameters nil)
13567 (unless noremove
13568 (remove-hook 'before-change-functions
13569 'org-remove-occur-highlights 'local))))
13571 ;;;; Priorities
13573 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13574 "Regular expression matching the priority indicator.")
13576 (defvar org-remove-priority-next-time nil)
13578 (defun org-priority-up ()
13579 "Increase the priority of the current item."
13580 (interactive)
13581 (org-priority 'up))
13583 (defun org-priority-down ()
13584 "Decrease the priority of the current item."
13585 (interactive)
13586 (org-priority 'down))
13588 (defun org-priority (&optional action show)
13589 "Change the priority of an item.
13590 ACTION can be `set', `up', `down', or a character."
13591 (interactive "P")
13592 (if (equal action '(4))
13593 (org-show-priority)
13594 (unless org-enable-priority-commands
13595 (user-error "Priority commands are disabled"))
13596 (setq action (or action 'set))
13597 (let (current new news have remove)
13598 (save-excursion
13599 (org-back-to-heading t)
13600 (if (looking-at org-priority-regexp)
13601 (setq current (string-to-char (match-string 2))
13602 have t))
13603 (cond
13604 ((eq action 'remove)
13605 (setq remove t new ?\ ))
13606 ((or (eq action 'set)
13607 (if (featurep 'xemacs) (characterp action) (integerp action)))
13608 (if (not (eq action 'set))
13609 (setq new action)
13610 (message "Priority %c-%c, SPC to remove: "
13611 org-highest-priority org-lowest-priority)
13612 (save-match-data
13613 (setq new (read-char-exclusive))))
13614 (if (and (= (upcase org-highest-priority) org-highest-priority)
13615 (= (upcase org-lowest-priority) org-lowest-priority))
13616 (setq new (upcase new)))
13617 (cond ((equal new ?\ ) (setq remove t))
13618 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13619 (user-error "Priority must be between `%c' and `%c'"
13620 org-highest-priority org-lowest-priority))))
13621 ((eq action 'up)
13622 (setq new (if have
13623 (1- current) ; normal cycling
13624 ;; last priority was empty
13625 (if (eq last-command this-command)
13626 org-lowest-priority ; wrap around empty to lowest
13627 ;; default
13628 (if org-priority-start-cycle-with-default
13629 org-default-priority
13630 (1- org-default-priority))))))
13631 ((eq action 'down)
13632 (setq new (if have
13633 (1+ current) ; normal cycling
13634 ;; last priority was empty
13635 (if (eq last-command this-command)
13636 org-highest-priority ; wrap around empty to highest
13637 ;; default
13638 (if org-priority-start-cycle-with-default
13639 org-default-priority
13640 (1+ org-default-priority))))))
13641 (t (user-error "Invalid action")))
13642 (if (or (< (upcase new) org-highest-priority)
13643 (> (upcase new) org-lowest-priority))
13644 (if (and (memq action '(up down))
13645 (not have) (not (eq last-command this-command)))
13646 ;; `new' is from default priority
13647 (error
13648 "The default can not be set, see `org-default-priority' why")
13649 ;; normal cycling: `new' is beyond highest/lowest priority
13650 ;; and is wrapped around to the empty priority
13651 (setq remove t)))
13652 (setq news (format "%c" new))
13653 (if have
13654 (if remove
13655 (replace-match "" t t nil 1)
13656 (replace-match news t t nil 2))
13657 (if remove
13658 (user-error "No priority cookie found in line")
13659 (let ((case-fold-search nil))
13660 (looking-at org-todo-line-regexp))
13661 (if (match-end 2)
13662 (progn
13663 (goto-char (match-end 2))
13664 (insert " [#" news "]"))
13665 (goto-char (match-beginning 3))
13666 (insert "[#" news "] "))))
13667 (org-preserve-lc (org-set-tags nil 'align)))
13668 (if remove
13669 (message "Priority removed")
13670 (message "Priority of current item set to %s" news)))))
13672 (defun org-show-priority ()
13673 "Show the priority of the current item.
13674 This priority is composed of the main priority given with the [#A] cookies,
13675 and by additional input from the age of a schedules or deadline entry."
13676 (interactive)
13677 (let ((pri (if (eq major-mode 'org-agenda-mode)
13678 (org-get-at-bol 'priority)
13679 (save-excursion
13680 (save-match-data
13681 (beginning-of-line)
13682 (and (looking-at org-heading-regexp)
13683 (org-get-priority (match-string 0))))))))
13684 (message "Priority is %d" (if pri pri -1000))))
13686 (defun org-get-priority (s)
13687 "Find priority cookie and return priority."
13688 (save-match-data
13689 (if (functionp org-get-priority-function)
13690 (funcall org-get-priority-function)
13691 (if (not (string-match org-priority-regexp s))
13692 (* 1000 (- org-lowest-priority org-default-priority))
13693 (* 1000 (- org-lowest-priority
13694 (string-to-char (match-string 2 s))))))))
13696 ;;;; Tags
13698 (defvar org-agenda-archives-mode)
13699 (defvar org-map-continue-from nil
13700 "Position from where mapping should continue.
13701 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13703 (defvar org-scanner-tags nil
13704 "The current tag list while the tags scanner is running.")
13705 (defvar org-trust-scanner-tags nil
13706 "Should `org-get-tags-at' use the tags for the scanner.
13707 This is for internal dynamical scoping only.
13708 When this is non-nil, the function `org-get-tags-at' will return the value
13709 of `org-scanner-tags' instead of building the list by itself. This
13710 can lead to large speed-ups when the tags scanner is used in a file with
13711 many entries, and when the list of tags is retrieved, for example to
13712 obtain a list of properties. Building the tags list for each entry in such
13713 a file becomes an N^2 operation - but with this variable set, it scales
13714 as N.")
13716 (defun org-scan-tags (action matcher todo-only &optional start-level)
13717 "Sca headline tags with inheritance and produce output ACTION.
13719 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13720 or `agenda' to produce an entry list for an agenda view. It can also be
13721 a Lisp form or a function that should be called at each matched headline, in
13722 this case the return value is a list of all return values from these calls.
13724 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13725 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13726 only lines with a not-done TODO keyword are included in the output.
13727 This should be the same variable that was scoped into
13728 and set by `org-make-tags-matcher' when it constructed MATCHER.
13730 START-LEVEL can be a string with asterisks, reducing the scope to
13731 headlines matching this string."
13732 (require 'org-agenda)
13733 (let* ((re (concat "^"
13734 (if start-level
13735 ;; Get the correct level to match
13736 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13737 org-outline-regexp)
13738 " *\\(\\<\\("
13739 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13740 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13741 (props (list 'face 'default
13742 'done-face 'org-agenda-done
13743 'undone-face 'default
13744 'mouse-face 'highlight
13745 'org-not-done-regexp org-not-done-regexp
13746 'org-todo-regexp org-todo-regexp
13747 'org-complex-heading-regexp org-complex-heading-regexp
13748 'help-echo
13749 (format "mouse-2 or RET jump to org file %s"
13750 (abbreviate-file-name
13751 (or (buffer-file-name (buffer-base-buffer))
13752 (buffer-name (buffer-base-buffer)))))))
13753 (case-fold-search nil)
13754 (org-map-continue-from nil)
13755 lspos tags tags-list
13756 (tags-alist (list (cons 0 org-file-tags)))
13757 (llast 0) rtn rtn1 level category i txt
13758 todo marker entry priority)
13759 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13760 (setq action (list 'lambda nil action)))
13761 (save-excursion
13762 (goto-char (point-min))
13763 (when (eq action 'sparse-tree)
13764 (org-overview)
13765 (org-remove-occur-highlights))
13766 (while (re-search-forward re nil t)
13767 (setq org-map-continue-from nil)
13768 (catch :skip
13769 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13770 tags (if (match-end 4) (org-match-string-no-properties 4)))
13771 (goto-char (setq lspos (match-beginning 0)))
13772 (setq level (org-reduced-level (org-outline-level))
13773 category (org-get-category))
13774 (setq i llast llast level)
13775 ;; remove tag lists from same and sublevels
13776 (while (>= i level)
13777 (when (setq entry (assoc i tags-alist))
13778 (setq tags-alist (delete entry tags-alist)))
13779 (setq i (1- i)))
13780 ;; add the next tags
13781 (when tags
13782 (setq tags (org-split-string tags ":")
13783 tags-alist
13784 (cons (cons level tags) tags-alist)))
13785 ;; compile tags for current headline
13786 (setq tags-list
13787 (if org-use-tag-inheritance
13788 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13789 tags)
13790 org-scanner-tags tags-list)
13791 (when org-use-tag-inheritance
13792 (setcdr (car tags-alist)
13793 (mapcar (lambda (x)
13794 (setq x (copy-sequence x))
13795 (org-add-prop-inherited x))
13796 (cdar tags-alist))))
13797 (when (and tags org-use-tag-inheritance
13798 (or (not (eq t org-use-tag-inheritance))
13799 org-tags-exclude-from-inheritance))
13800 ;; selective inheritance, remove uninherited ones
13801 (setcdr (car tags-alist)
13802 (org-remove-uninherited-tags (cdar tags-alist))))
13803 (when (and
13805 ;; eval matcher only when the todo condition is OK
13806 (and (or (not todo-only) (member todo org-not-done-keywords))
13807 (let ((case-fold-search t) (org-trust-scanner-tags t))
13808 (eval matcher)))
13810 ;; Call the skipper, but return t if it does not skip,
13811 ;; so that the `and' form continues evaluating
13812 (progn
13813 (unless (eq action 'sparse-tree) (org-agenda-skip))
13816 ;; Check if timestamps are deselecting this entry
13817 (or (not todo-only)
13818 (and (member todo org-not-done-keywords)
13819 (or (not org-agenda-tags-todo-honor-ignore-options)
13820 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13822 ;; select this headline
13823 (cond
13824 ((eq action 'sparse-tree)
13825 (and org-highlight-sparse-tree-matches
13826 (org-get-heading) (match-end 0)
13827 (org-highlight-new-match
13828 (match-beginning 1) (match-end 1)))
13829 (org-show-context 'tags-tree))
13830 ((eq action 'agenda)
13831 (setq txt (org-agenda-format-item
13833 (concat
13834 (if (eq org-tags-match-list-sublevels 'indented)
13835 (make-string (1- level) ?.) "")
13836 (org-get-heading))
13837 level category
13838 tags-list)
13839 priority (org-get-priority txt))
13840 (goto-char lspos)
13841 (setq marker (org-agenda-new-marker))
13842 (org-add-props txt props
13843 'org-marker marker 'org-hd-marker marker 'org-category category
13844 'todo-state todo
13845 'priority priority 'type "tagsmatch")
13846 (push txt rtn))
13847 ((functionp action)
13848 (setq org-map-continue-from nil)
13849 (save-excursion
13850 (setq rtn1 (funcall action))
13851 (push rtn1 rtn)))
13852 (t (user-error "Invalid action")))
13854 ;; if we are to skip sublevels, jump to end of subtree
13855 (unless org-tags-match-list-sublevels
13856 (org-end-of-subtree t)
13857 (backward-char 1))))
13858 ;; Get the correct position from where to continue
13859 (if org-map-continue-from
13860 (goto-char org-map-continue-from)
13861 (and (= (point) lspos) (end-of-line 1)))))
13862 (when (and (eq action 'sparse-tree)
13863 (not org-sparse-tree-open-archived-trees))
13864 (org-hide-archived-subtrees (point-min) (point-max)))
13865 (nreverse rtn)))
13867 (defun org-remove-uninherited-tags (tags)
13868 "Remove all tags that are not inherited from the list TAGS."
13869 (cond
13870 ((eq org-use-tag-inheritance t)
13871 (if org-tags-exclude-from-inheritance
13872 (org-delete-all org-tags-exclude-from-inheritance tags)
13873 tags))
13874 ((not org-use-tag-inheritance) nil)
13875 ((stringp org-use-tag-inheritance)
13876 (delq nil (mapcar
13877 (lambda (x)
13878 (if (and (string-match org-use-tag-inheritance x)
13879 (not (member x org-tags-exclude-from-inheritance)))
13880 x nil))
13881 tags)))
13882 ((listp org-use-tag-inheritance)
13883 (delq nil (mapcar
13884 (lambda (x)
13885 (if (member x org-use-tag-inheritance) x nil))
13886 tags)))))
13888 (defun org-match-sparse-tree (&optional todo-only match)
13889 "Create a sparse tree according to tags string MATCH.
13890 MATCH can contain positive and negative selection of tags, like
13891 \"+WORK+URGENT-WITHBOSS\".
13892 If optional argument TODO-ONLY is non-nil, only select lines that are
13893 also TODO lines."
13894 (interactive "P")
13895 (org-agenda-prepare-buffers (list (current-buffer)))
13896 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13898 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13900 (defvar org-cached-props nil)
13901 (defun org-cached-entry-get (pom property)
13902 (if (or (eq t org-use-property-inheritance)
13903 (and (stringp org-use-property-inheritance)
13904 (string-match org-use-property-inheritance property))
13905 (and (listp org-use-property-inheritance)
13906 (member property org-use-property-inheritance)))
13907 ;; Caching is not possible, check it directly
13908 (org-entry-get pom property 'inherit)
13909 ;; Get all properties, so that we can do complicated checks easily
13910 (cdr (assoc property (or org-cached-props
13911 (setq org-cached-props
13912 (org-entry-properties pom)))))))
13914 (defun org-global-tags-completion-table (&optional files)
13915 "Return the list of all tags in all agenda buffer/files.
13916 Optional FILES argument is a list of files which can be used
13917 instead of the agenda files."
13918 (save-excursion
13919 (org-uniquify
13920 (delq nil
13921 (apply 'append
13922 (mapcar
13923 (lambda (file)
13924 (set-buffer (find-file-noselect file))
13925 (append (org-get-buffer-tags)
13926 (mapcar (lambda (x) (if (stringp (car-safe x))
13927 (list (car-safe x)) nil))
13928 org-tag-alist)))
13929 (if (and files (car files))
13930 files
13931 (org-agenda-files))))))))
13933 (defun org-make-tags-matcher (match)
13934 "Create the TAGS/TODO matcher form for the selection string MATCH.
13936 The variable `todo-only' is scoped dynamically into this function.
13937 It will be set to t if the matcher restricts matching to TODO entries,
13938 otherwise will not be touched.
13940 Returns a cons of the selection string MATCH and the constructed
13941 lisp form implementing the matcher. The matcher is to be evaluated
13942 at an Org entry, with point on the headline, and returns t if the
13943 entry matches the selection string MATCH. The returned lisp form
13944 references two variables with information about the entry, which
13945 must be bound around the form's evaluation: todo, the TODO keyword
13946 at the entry (or nil of none); and tags-list, the list of all tags
13947 at the entry including inherited ones. Additionally, the category
13948 of the entry (if any) must be specified as the text property
13949 'org-category on the headline.
13951 See also `org-scan-tags'.
13953 (declare (special todo-only))
13954 (unless (boundp 'todo-only)
13955 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13956 (unless match
13957 ;; Get a new match request, with completion against the global
13958 ;; tags table and the local tags in current buffer
13959 (let ((org-last-tags-completion-table
13960 (org-uniquify
13961 (delq nil (append (org-get-buffer-tags)
13962 (org-global-tags-completion-table))))))
13963 (setq match (org-completing-read-no-i
13964 "Match: " 'org-tags-completion-function nil nil nil
13965 'org-tags-history))))
13967 ;; Parse the string and create a lisp form
13968 (let ((match0 match)
13969 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13970 minus tag mm
13971 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13972 orterms term orlist re-p str-p level-p level-op time-p
13973 prop-p pn pv po gv rest)
13974 ;; Expand group tags
13975 (setq match (org-tags-expand match))
13976 (if (string-match "/+" match)
13977 ;; match contains also a todo-matching request
13978 (progn
13979 (setq tagsmatch (substring match 0 (match-beginning 0))
13980 todomatch (substring match (match-end 0)))
13981 (if (string-match "^!" todomatch)
13982 (setq todo-only t todomatch (substring todomatch 1)))
13983 (if (string-match "^\\s-*$" todomatch)
13984 (setq todomatch nil)))
13985 ;; only matching tags
13986 (setq tagsmatch match todomatch nil))
13988 ;; Make the tags matcher
13989 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13990 (setq tagsmatcher t)
13991 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13992 (while (setq term (pop orterms))
13993 (while (and (equal (substring term -1) "\\") orterms)
13994 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13995 (while (string-match re term)
13996 (setq rest (substring term (match-end 0))
13997 minus (and (match-end 1)
13998 (equal (match-string 1 term) "-"))
13999 tag (save-match-data (replace-regexp-in-string
14000 "\\\\-" "-"
14001 (match-string 2 term)))
14002 re-p (equal (string-to-char tag) ?{)
14003 level-p (match-end 4)
14004 prop-p (match-end 5)
14005 mm (cond
14006 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14007 (level-p
14008 (setq level-op (org-op-to-function (match-string 3 term)))
14009 `(,level-op level ,(string-to-number
14010 (match-string 4 term))))
14011 (prop-p
14012 (setq pn (match-string 5 term)
14013 po (match-string 6 term)
14014 pv (match-string 7 term)
14015 re-p (equal (string-to-char pv) ?{)
14016 str-p (equal (string-to-char pv) ?\")
14017 time-p (save-match-data
14018 (string-match "^\"[[<].*[]>]\"$" pv))
14019 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14020 (if time-p (setq pv (org-matcher-time pv)))
14021 (setq po (org-op-to-function po (if time-p 'time str-p)))
14022 (cond
14023 ((equal pn "CATEGORY")
14024 (setq gv '(get-text-property (point) 'org-category)))
14025 ((equal pn "TODO")
14026 (setq gv 'todo))
14028 (setq gv `(org-cached-entry-get nil ,pn))))
14029 (if re-p
14030 (if (eq po 'org<>)
14031 `(not (string-match ,pv (or ,gv "")))
14032 `(string-match ,pv (or ,gv "")))
14033 (if str-p
14034 `(,po (or ,gv "") ,pv)
14035 `(,po (string-to-number (or ,gv ""))
14036 ,(string-to-number pv) ))))
14037 (t `(member ,tag tags-list)))
14038 mm (if minus (list 'not mm) mm)
14039 term rest)
14040 (push mm tagsmatcher))
14041 (push (if (> (length tagsmatcher) 1)
14042 (cons 'and tagsmatcher)
14043 (car tagsmatcher))
14044 orlist)
14045 (setq tagsmatcher nil))
14046 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14047 (setq tagsmatcher
14048 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14049 ;; Make the todo matcher
14050 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14051 (setq todomatcher t)
14052 (setq orterms (org-split-string todomatch "|") orlist nil)
14053 (while (setq term (pop orterms))
14054 (while (string-match re term)
14055 (setq minus (and (match-end 1)
14056 (equal (match-string 1 term) "-"))
14057 kwd (match-string 2 term)
14058 re-p (equal (string-to-char kwd) ?{)
14059 term (substring term (match-end 0))
14060 mm (if re-p
14061 `(string-match ,(substring kwd 1 -1) todo)
14062 (list 'equal 'todo kwd))
14063 mm (if minus (list 'not mm) mm))
14064 (push mm todomatcher))
14065 (push (if (> (length todomatcher) 1)
14066 (cons 'and todomatcher)
14067 (car todomatcher))
14068 orlist)
14069 (setq todomatcher nil))
14070 (setq todomatcher (if (> (length orlist) 1)
14071 (cons 'or orlist) (car orlist))))
14073 ;; Return the string and lisp forms of the matcher
14074 (setq matcher (if todomatcher
14075 (list 'and tagsmatcher todomatcher)
14076 tagsmatcher))
14077 (when todo-only
14078 (setq matcher (list 'and '(member todo org-not-done-keywords)
14079 matcher)))
14080 (cons match0 matcher)))
14082 (defun org-tags-expand (match &optional single-as-list downcased)
14083 "Expand group tags in MATCH.
14085 This replaces every group tag in MATCH with a regexp tag search.
14086 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14087 will be replaced like this:
14089 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14090 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14091 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14093 Replacing by a regexp preserves the structure of the match.
14094 E.g., this expansion
14096 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14098 will match anything tagged with \"Lab\" and \"Home\", or tagged
14099 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14101 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14102 assumed to be a single group tag, and the function will return
14103 the list of tags in this group.
14105 When DOWNCASE is non-nil, expand downcased TAGS."
14106 (if org-group-tags
14107 (let* ((case-fold-search t)
14108 (stable org-mode-syntax-table)
14109 (tal (or org-tag-groups-alist-for-agenda
14110 org-tag-groups-alist))
14111 (tal (if downcased
14112 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14113 (tml (mapcar 'car tal))
14114 (rtnmatch match) rpl)
14115 ;; @ and _ are allowed as word-components in tags
14116 (modify-syntax-entry ?@ "w" stable)
14117 (modify-syntax-entry ?_ "w" stable)
14118 (while (and tml
14119 (string-match
14120 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14121 (regexp-opt tml) "\\>\\)") rtnmatch))
14122 (let* ((dir (match-string 1 rtnmatch))
14123 (tag (match-string 2 rtnmatch))
14124 (tag (if downcased (downcase tag) tag)))
14125 (setq tml (delete tag tml))
14126 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14127 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14128 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14129 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14130 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14131 (if single-as-list
14132 (or (reverse rpl) (list rtnmatch))
14133 rtnmatch))
14134 (if single-as-list (list (if downcased (downcase match) match))
14135 match)))
14137 (defun org-op-to-function (op &optional stringp)
14138 "Turn an operator into the appropriate function."
14139 (setq op
14140 (cond
14141 ((equal op "<" ) '(< string< org-time<))
14142 ((equal op ">" ) '(> org-string> org-time>))
14143 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14144 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14145 ((member op '("=" "==")) '(= string= org-time=))
14146 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14147 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14149 (defun org<> (a b) (not (= a b)))
14150 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14151 (defun org-string>= (a b) (not (string< a b)))
14152 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14153 (defun org-string<> (a b) (not (string= a b)))
14154 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14155 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14156 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14157 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14158 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14159 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14160 (defun org-2ft (s)
14161 "Convert S to a floating point time.
14162 If S is already a number, just return it. If it is a string, parse
14163 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14164 (cond
14165 ((numberp s) s)
14166 ((stringp s)
14167 (condition-case nil
14168 (float-time (apply 'encode-time (org-parse-time-string s)))
14169 (error 0.)))
14170 (t 0.)))
14172 (defun org-time-today ()
14173 "Time in seconds today at 0:00.
14174 Returns the float number of seconds since the beginning of the
14175 epoch to the beginning of today (00:00)."
14176 (float-time (apply 'encode-time
14177 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14179 (defun org-matcher-time (s)
14180 "Interpret a time comparison value."
14181 (save-match-data
14182 (cond
14183 ((string= s "<now>") (float-time))
14184 ((string= s "<today>") (org-time-today))
14185 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14186 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14187 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14188 (+ (org-time-today)
14189 (* (string-to-number (match-string 1 s))
14190 (cdr (assoc (match-string 2 s)
14191 '(("d" . 86400.0) ("w" . 604800.0)
14192 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14193 (t (org-2ft s)))))
14195 (defun org-match-any-p (re list)
14196 "Does re match any element of list?"
14197 (setq list (mapcar (lambda (x) (string-match re x)) list))
14198 (delq nil list))
14200 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14201 (defvar org-tags-overlay (make-overlay 1 1))
14202 (org-detach-overlay org-tags-overlay)
14204 (defun org-get-local-tags-at (&optional pos)
14205 "Get a list of tags defined in the current headline."
14206 (org-get-tags-at pos 'local))
14208 (defun org-get-local-tags ()
14209 "Get a list of tags defined in the current headline."
14210 (org-get-tags-at nil 'local))
14212 (defun org-get-tags-at (&optional pos local)
14213 "Get a list of all headline tags applicable at POS.
14214 POS defaults to point. If tags are inherited, the list contains
14215 the targets in the same sequence as the headlines appear, i.e.
14216 the tags of the current headline come last.
14217 When LOCAL is non-nil, only return tags from the current headline,
14218 ignore inherited ones."
14219 (interactive)
14220 (if (and org-trust-scanner-tags
14221 (or (not pos) (equal pos (point)))
14222 (not local))
14223 org-scanner-tags
14224 (let (tags ltags lastpos parent)
14225 (save-excursion
14226 (save-restriction
14227 (widen)
14228 (goto-char (or pos (point)))
14229 (save-match-data
14230 (catch 'done
14231 (condition-case nil
14232 (progn
14233 (org-back-to-heading t)
14234 (while (not (equal lastpos (point)))
14235 (setq lastpos (point))
14236 (when (looking-at
14237 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14238 (setq ltags (org-split-string
14239 (org-match-string-no-properties 1) ":"))
14240 (when parent
14241 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14242 (setq tags (append
14243 (if parent
14244 (org-remove-uninherited-tags ltags)
14245 ltags)
14246 tags)))
14247 (or org-use-tag-inheritance (throw 'done t))
14248 (if local (throw 'done t))
14249 (or (org-up-heading-safe) (error nil))
14250 (setq parent t)))
14251 (error nil)))))
14252 (if local
14253 tags
14254 (reverse (delete-dups
14255 (reverse (append
14256 (org-remove-uninherited-tags
14257 org-file-tags) tags)))))))))
14259 (defun org-add-prop-inherited (s)
14260 (add-text-properties 0 (length s) '(inherited t) s)
14263 (defun org-toggle-tag (tag &optional onoff)
14264 "Toggle the tag TAG for the current line.
14265 If ONOFF is `on' or `off', don't toggle but set to this state."
14266 (let (res current)
14267 (save-excursion
14268 (org-back-to-heading t)
14269 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14270 (point-at-eol) t)
14271 (progn
14272 (setq current (match-string 1))
14273 (replace-match ""))
14274 (setq current ""))
14275 (setq current (nreverse (org-split-string current ":")))
14276 (cond
14277 ((eq onoff 'on)
14278 (setq res t)
14279 (or (member tag current) (push tag current)))
14280 ((eq onoff 'off)
14281 (or (not (member tag current)) (setq current (delete tag current))))
14282 (t (if (member tag current)
14283 (setq current (delete tag current))
14284 (setq res t)
14285 (push tag current))))
14286 (end-of-line 1)
14287 (if current
14288 (progn
14289 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14290 (org-set-tags nil t))
14291 (delete-horizontal-space))
14292 (run-hooks 'org-after-tags-change-hook))
14293 res))
14295 (defun org-align-tags-here (to-col)
14296 ;; Assumes that this is a headline
14297 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14298 (beginning-of-line 1)
14299 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14300 (< pos (match-beginning 2)))
14301 (progn
14302 (setq tags-l (- (match-end 2) (match-beginning 2)))
14303 (goto-char (match-beginning 1))
14304 (insert " ")
14305 (delete-region (point) (1+ (match-beginning 2)))
14306 (setq ncol (max (current-column)
14307 (1+ col)
14308 (if (> to-col 0)
14309 to-col
14310 (- (abs to-col) tags-l))))
14311 (setq p (point))
14312 (insert (make-string (- ncol (current-column)) ?\ ))
14313 (setq ncol (current-column))
14314 (when indent-tabs-mode (tabify p (point-at-eol)))
14315 (org-move-to-column (min ncol col) t))
14316 (goto-char pos))))
14318 (defun org-set-tags-command (&optional arg just-align)
14319 "Call the set-tags command for the current entry."
14320 (interactive "P")
14321 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14322 (org-set-tags arg just-align)
14323 (save-excursion
14324 (unless (and (org-region-active-p)
14325 org-loop-over-headlines-in-active-region)
14326 (org-back-to-heading t))
14327 (org-set-tags arg just-align))))
14329 (defun org-set-tags-to (data)
14330 "Set the tags of the current entry to DATA, replacing the current tags.
14331 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14332 If DATA is nil or the empty string, any tags will be removed."
14333 (interactive "sTags: ")
14334 (setq data
14335 (cond
14336 ((eq data nil) "")
14337 ((equal data "") "")
14338 ((stringp data)
14339 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14340 ":"))
14341 ((listp data)
14342 (concat ":" (mapconcat 'identity data ":") ":"))))
14343 (when data
14344 (save-excursion
14345 (org-back-to-heading t)
14346 (when (looking-at org-complex-heading-regexp)
14347 (if (match-end 5)
14348 (progn
14349 (goto-char (match-beginning 5))
14350 (insert data)
14351 (delete-region (point) (point-at-eol))
14352 (org-set-tags nil 'align))
14353 (goto-char (point-at-eol))
14354 (insert " " data)
14355 (org-set-tags nil 'align)))
14356 (beginning-of-line 1)
14357 (if (looking-at ".*?\\([ \t]+\\)$")
14358 (delete-region (match-beginning 1) (match-end 1))))))
14360 (defun org-align-all-tags ()
14361 "Align the tags i all headings."
14362 (interactive)
14363 (save-excursion
14364 (or (ignore-errors (org-back-to-heading t))
14365 (outline-next-heading))
14366 (if (org-at-heading-p)
14367 (org-set-tags t)
14368 (message "No headings"))))
14370 (defvar org-indent-indentation-per-level)
14371 (defun org-set-tags (&optional arg just-align)
14372 "Set the tags for the current headline.
14373 With prefix ARG, realign all tags in headings in the current buffer."
14374 (interactive "P")
14375 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14376 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14377 'region-start-level 'region))
14378 org-loop-over-headlines-in-active-region)
14379 (org-map-entries
14380 ;; We don't use ARG and JUST-ALIGN here these args are not
14381 ;; useful when looping over headlines
14382 `(org-set-tags)
14383 org-loop-over-headlines-in-active-region
14384 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14385 (let* ((re org-outline-regexp-bol)
14386 (current (unless arg (org-get-tags-string)))
14387 (col (current-column))
14388 (org-setting-tags t)
14389 table current-tags inherited-tags ; computed below when needed
14390 tags p0 c0 c1 rpl di tc level)
14391 (if arg
14392 (save-excursion
14393 (goto-char (point-min))
14394 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14395 (while (re-search-forward re nil t)
14396 (org-set-tags nil t)
14397 (end-of-line 1)))
14398 (message "All tags realigned to column %d" org-tags-column))
14399 (if just-align
14400 (setq tags current)
14401 ;; Get a new set of tags from the user
14402 (save-excursion
14403 (setq table (append org-tag-persistent-alist
14404 (or org-tag-alist (org-get-buffer-tags))
14405 (and
14406 org-complete-tags-always-offer-all-agenda-tags
14407 (org-global-tags-completion-table
14408 (org-agenda-files))))
14409 org-last-tags-completion-table table
14410 current-tags (org-split-string current ":")
14411 inherited-tags (nreverse
14412 (nthcdr (length current-tags)
14413 (nreverse (org-get-tags-at))))
14414 tags
14415 (if (or (eq t org-use-fast-tag-selection)
14416 (and org-use-fast-tag-selection
14417 (delq nil (mapcar 'cdr table))))
14418 (org-fast-tag-selection
14419 current-tags inherited-tags table
14420 (if org-fast-tag-selection-include-todo
14421 org-todo-key-alist))
14422 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14423 (org-trim
14424 (org-icompleting-read "Tags: "
14425 'org-tags-completion-function
14426 nil nil current 'org-tags-history))))))
14427 (while (string-match "[-+&]+" tags)
14428 ;; No boolean logic, just a list
14429 (setq tags (replace-match ":" t t tags))))
14431 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14433 (if org-tags-sort-function
14434 (setq tags (mapconcat 'identity
14435 (sort (org-split-string
14436 tags (org-re "[^[:alnum:]_@#%]+"))
14437 org-tags-sort-function) ":")))
14439 (if (string-match "\\`[\t ]*\\'" tags)
14440 (setq tags "")
14441 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14442 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14444 ;; Insert new tags at the correct column
14445 (beginning-of-line 1)
14446 (setq level (or (and (looking-at org-outline-regexp)
14447 (- (match-end 0) (point) 1))
14449 (cond
14450 ((and (equal current "") (equal tags "")))
14451 ((re-search-forward
14452 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14453 (point-at-eol) t)
14454 (if (equal tags "")
14455 (setq rpl "")
14456 (goto-char (match-beginning 0))
14457 (setq c0 (current-column)
14458 ;; compute offset for the case of org-indent-mode active
14459 di (if org-indent-mode
14460 (* (1- org-indent-indentation-per-level) (1- level))
14462 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14463 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14464 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14465 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14466 (replace-match rpl t t)
14467 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14468 tags)
14469 (t (error "Tags alignment failed")))
14470 (org-move-to-column col)
14471 (unless just-align
14472 (run-hooks 'org-after-tags-change-hook))))))
14474 (defun org-change-tag-in-region (beg end tag off)
14475 "Add or remove TAG for each entry in the region.
14476 This works in the agenda, and also in an org-mode buffer."
14477 (interactive
14478 (list (region-beginning) (region-end)
14479 (let ((org-last-tags-completion-table
14480 (if (derived-mode-p 'org-mode)
14481 (org-uniquify
14482 (delq nil (append (org-get-buffer-tags)
14483 (org-global-tags-completion-table))))
14484 (org-global-tags-completion-table))))
14485 (org-icompleting-read
14486 "Tag: " 'org-tags-completion-function nil nil nil
14487 'org-tags-history))
14488 (progn
14489 (message "[s]et or [r]emove? ")
14490 (equal (read-char-exclusive) ?r))))
14491 (if (fboundp 'deactivate-mark) (deactivate-mark))
14492 (let ((agendap (equal major-mode 'org-agenda-mode))
14493 l1 l2 m buf pos newhead (cnt 0))
14494 (goto-char end)
14495 (setq l2 (1- (org-current-line)))
14496 (goto-char beg)
14497 (setq l1 (org-current-line))
14498 (loop for l from l1 to l2 do
14499 (org-goto-line l)
14500 (setq m (get-text-property (point) 'org-hd-marker))
14501 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14502 (and agendap m))
14503 (setq buf (if agendap (marker-buffer m) (current-buffer))
14504 pos (if agendap m (point)))
14505 (with-current-buffer buf
14506 (save-excursion
14507 (save-restriction
14508 (goto-char pos)
14509 (setq cnt (1+ cnt))
14510 (org-toggle-tag tag (if off 'off 'on))
14511 (setq newhead (org-get-heading)))))
14512 (and agendap (org-agenda-change-all-lines newhead m))))
14513 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14515 (defun org-tags-completion-function (string predicate &optional flag)
14516 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14517 (confirm (lambda (x) (stringp (car x)))))
14518 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14519 (setq s1 (match-string 1 string)
14520 s2 (match-string 2 string))
14521 (setq s1 "" s2 string))
14522 (cond
14523 ((eq flag nil)
14524 ;; try completion
14525 (setq rtn (try-completion s2 ctable confirm))
14526 (if (stringp rtn)
14527 (setq rtn
14528 (concat s1 s2 (substring rtn (length s2))
14529 (if (and org-add-colon-after-tag-completion
14530 (assoc rtn ctable))
14531 ":" ""))))
14532 rtn)
14533 ((eq flag t)
14534 ;; all-completions
14535 (all-completions s2 ctable confirm))
14536 ((eq flag 'lambda)
14537 ;; exact match?
14538 (assoc s2 ctable)))))
14540 (defun org-fast-tag-insert (kwd tags face &optional end)
14541 "Insert KDW, and the TAGS, the latter with face FACE.
14542 Also insert END."
14543 (insert (format "%-12s" (concat kwd ":"))
14544 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14545 (or end "")))
14547 (defun org-fast-tag-show-exit (flag)
14548 (save-excursion
14549 (org-goto-line 3)
14550 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14551 (replace-match ""))
14552 (when flag
14553 (end-of-line 1)
14554 (org-move-to-column (- (window-width) 19) t)
14555 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14557 (defun org-set-current-tags-overlay (current prefix)
14558 "Add an overlay to CURRENT tag with PREFIX."
14559 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14560 (if (featurep 'xemacs)
14561 (org-overlay-display org-tags-overlay (concat prefix s)
14562 'secondary-selection)
14563 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14564 (org-overlay-display org-tags-overlay (concat prefix s)))))
14566 (defvar org-last-tag-selection-key nil)
14567 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14568 "Fast tag selection with single keys.
14569 CURRENT is the current list of tags in the headline, INHERITED is the
14570 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14571 possibly with grouping information. TODO-TABLE is a similar table with
14572 TODO keywords, should these have keys assigned to them.
14573 If the keys are nil, a-z are automatically assigned.
14574 Returns the new tags string, or nil to not change the current settings."
14575 (let* ((fulltable (append table todo-table))
14576 (maxlen (apply 'max (mapcar
14577 (lambda (x)
14578 (if (stringp (car x)) (string-width (car x)) 0))
14579 fulltable)))
14580 (buf (current-buffer))
14581 (expert (eq org-fast-tag-selection-single-key 'expert))
14582 (buffer-tags nil)
14583 (fwidth (+ maxlen 3 1 3))
14584 (ncol (/ (- (window-width) 4) fwidth))
14585 (i-face 'org-done)
14586 (c-face 'org-todo)
14587 tg cnt e c char c1 c2 ntable tbl rtn
14588 ov-start ov-end ov-prefix
14589 (exit-after-next org-fast-tag-selection-single-key)
14590 (done-keywords org-done-keywords)
14591 groups ingroup)
14592 (save-excursion
14593 (beginning-of-line 1)
14594 (if (looking-at
14595 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14596 (setq ov-start (match-beginning 1)
14597 ov-end (match-end 1)
14598 ov-prefix "")
14599 (setq ov-start (1- (point-at-eol))
14600 ov-end (1+ ov-start))
14601 (skip-chars-forward "^\n\r")
14602 (setq ov-prefix
14603 (concat
14604 (buffer-substring (1- (point)) (point))
14605 (if (> (current-column) org-tags-column)
14607 (make-string (- org-tags-column (current-column)) ?\ ))))))
14608 (move-overlay org-tags-overlay ov-start ov-end)
14609 (save-window-excursion
14610 (if expert
14611 (set-buffer (get-buffer-create " *Org tags*"))
14612 (delete-other-windows)
14613 (split-window-vertically)
14614 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14615 (erase-buffer)
14616 (org-set-local 'org-done-keywords done-keywords)
14617 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14618 (org-fast-tag-insert "Current" current c-face "\n\n")
14619 (org-fast-tag-show-exit exit-after-next)
14620 (org-set-current-tags-overlay current ov-prefix)
14621 (setq tbl fulltable char ?a cnt 0)
14622 (while (setq e (pop tbl))
14623 (cond
14624 ((equal (car e) :startgroup)
14625 (push '() groups) (setq ingroup t)
14626 (when (not (= cnt 0))
14627 (setq cnt 0)
14628 (insert "\n"))
14629 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14630 ((equal (car e) :endgroup)
14631 (setq ingroup nil cnt 0)
14632 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14633 ((equal e '(:newline))
14634 (when (not (= cnt 0))
14635 (setq cnt 0)
14636 (insert "\n")
14637 (setq e (car tbl))
14638 (while (equal (car tbl) '(:newline))
14639 (insert "\n")
14640 (setq tbl (cdr tbl)))))
14641 ((equal e '(:grouptags)) nil)
14643 (setq tg (copy-sequence (car e)) c2 nil)
14644 (if (cdr e)
14645 (setq c (cdr e))
14646 ;; automatically assign a character.
14647 (setq c1 (string-to-char
14648 (downcase (substring
14649 tg (if (= (string-to-char tg) ?@) 1 0)))))
14650 (if (or (rassoc c1 ntable) (rassoc c1 table))
14651 (while (or (rassoc char ntable) (rassoc char table))
14652 (setq char (1+ char)))
14653 (setq c2 c1))
14654 (setq c (or c2 char)))
14655 (if ingroup (push tg (car groups)))
14656 (setq tg (org-add-props tg nil 'face
14657 (cond
14658 ((not (assoc tg table))
14659 (org-get-todo-face tg))
14660 ((member tg current) c-face)
14661 ((member tg inherited) i-face))))
14662 (if (equal (caar tbl) :grouptags)
14663 (org-add-props tg nil 'face 'org-tag-group))
14664 (if (and (= cnt 0) (not ingroup)) (insert " "))
14665 (insert "[" c "] " tg (make-string
14666 (- fwidth 4 (length tg)) ?\ ))
14667 (push (cons tg c) ntable)
14668 (when (= (setq cnt (1+ cnt)) ncol)
14669 (insert "\n")
14670 (if ingroup (insert " "))
14671 (setq cnt 0)))))
14672 (setq ntable (nreverse ntable))
14673 (insert "\n")
14674 (goto-char (point-min))
14675 (if (not expert) (org-fit-window-to-buffer))
14676 (setq rtn
14677 (catch 'exit
14678 (while t
14679 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14680 (if (not groups) "no " "")
14681 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14682 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14683 (setq org-last-tag-selection-key c)
14684 (cond
14685 ((= c ?\r) (throw 'exit t))
14686 ((= c ?!)
14687 (setq groups (not groups))
14688 (goto-char (point-min))
14689 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14690 ((= c ?\C-c)
14691 (if (not expert)
14692 (org-fast-tag-show-exit
14693 (setq exit-after-next (not exit-after-next)))
14694 (setq expert nil)
14695 (delete-other-windows)
14696 (set-window-buffer (split-window-vertically) " *Org tags*")
14697 (org-switch-to-buffer-other-window " *Org tags*")
14698 (org-fit-window-to-buffer)))
14699 ((or (= c ?\C-g)
14700 (and (= c ?q) (not (rassoc c ntable))))
14701 (org-detach-overlay org-tags-overlay)
14702 (setq quit-flag t))
14703 ((= c ?\ )
14704 (setq current nil)
14705 (if exit-after-next (setq exit-after-next 'now)))
14706 ((= c ?\t)
14707 (condition-case nil
14708 (setq tg (org-icompleting-read
14709 "Tag: "
14710 (or buffer-tags
14711 (with-current-buffer buf
14712 (org-get-buffer-tags)))))
14713 (quit (setq tg "")))
14714 (when (string-match "\\S-" tg)
14715 (add-to-list 'buffer-tags (list tg))
14716 (if (member tg current)
14717 (setq current (delete tg current))
14718 (push tg current)))
14719 (if exit-after-next (setq exit-after-next 'now)))
14720 ((setq e (rassoc c todo-table) tg (car e))
14721 (with-current-buffer buf
14722 (save-excursion (org-todo tg)))
14723 (if exit-after-next (setq exit-after-next 'now)))
14724 ((setq e (rassoc c ntable) tg (car e))
14725 (if (member tg current)
14726 (setq current (delete tg current))
14727 (loop for g in groups do
14728 (if (member tg g)
14729 (mapc (lambda (x)
14730 (setq current (delete x current)))
14731 g)))
14732 (push tg current))
14733 (if exit-after-next (setq exit-after-next 'now))))
14735 ;; Create a sorted list
14736 (setq current
14737 (sort current
14738 (lambda (a b)
14739 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14740 (if (eq exit-after-next 'now) (throw 'exit t))
14741 (goto-char (point-min))
14742 (beginning-of-line 2)
14743 (delete-region (point) (point-at-eol))
14744 (org-fast-tag-insert "Current" current c-face)
14745 (org-set-current-tags-overlay current ov-prefix)
14746 (while (re-search-forward
14747 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14748 (setq tg (match-string 1))
14749 (add-text-properties
14750 (match-beginning 1) (match-end 1)
14751 (list 'face
14752 (cond
14753 ((member tg current) c-face)
14754 ((member tg inherited) i-face)
14755 (t (get-text-property (match-beginning 1) 'face))))))
14756 (goto-char (point-min)))))
14757 (org-detach-overlay org-tags-overlay)
14758 (if rtn
14759 (mapconcat 'identity current ":")
14760 nil))))
14762 (defun org-get-tags-string ()
14763 "Get the TAGS string in the current headline."
14764 (unless (org-at-heading-p t)
14765 (user-error "Not on a heading"))
14766 (save-excursion
14767 (beginning-of-line 1)
14768 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14769 (org-match-string-no-properties 1)
14770 "")))
14772 (defun org-get-tags ()
14773 "Get the list of tags specified in the current headline."
14774 (org-split-string (org-get-tags-string) ":"))
14776 (defun org-get-buffer-tags ()
14777 "Get a table of all tags used in the buffer, for completion."
14778 (let (tags)
14779 (save-excursion
14780 (goto-char (point-min))
14781 (while (re-search-forward
14782 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14783 (when (equal (char-after (point-at-bol 0)) ?*)
14784 (mapc (lambda (x) (add-to-list 'tags x))
14785 (org-split-string (org-match-string-no-properties 1) ":")))))
14786 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14787 (mapcar 'list tags)))
14789 ;;;; The mapping API
14791 (defun org-map-entries (func &optional match scope &rest skip)
14792 "Call FUNC at each headline selected by MATCH in SCOPE.
14794 FUNC is a function or a lisp form. The function will be called without
14795 arguments, with the cursor positioned at the beginning of the headline.
14796 The return values of all calls to the function will be collected and
14797 returned as a list.
14799 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14800 does not need to preserve point. After evaluation, the cursor will be
14801 moved to the end of the line (presumably of the headline of the
14802 processed entry) and search continues from there. Under some
14803 circumstances, this may not produce the wanted results. For example,
14804 if you have removed (e.g. archived) the current (sub)tree it could
14805 mean that the next entry will be skipped entirely. In such cases, you
14806 can specify the position from where search should continue by making
14807 FUNC set the variable `org-map-continue-from' to the desired buffer
14808 position.
14810 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14811 Only headlines that are matched by this query will be considered during
14812 the iteration. When MATCH is nil or t, all headlines will be
14813 visited by the iteration.
14815 SCOPE determines the scope of this command. It can be any of:
14817 nil The current buffer, respecting the restriction if any
14818 tree The subtree started with the entry at point
14819 region The entries within the active region, if any
14820 region-start-level
14821 The entries within the active region, but only those at
14822 the same level than the first one.
14823 file The current buffer, without restriction
14824 file-with-archives
14825 The current buffer, and any archives associated with it
14826 agenda All agenda files
14827 agenda-with-archives
14828 All agenda files with any archive files associated with them
14829 \(file1 file2 ...)
14830 If this is a list, all files in the list will be scanned
14832 The remaining args are treated as settings for the skipping facilities of
14833 the scanner. The following items can be given here:
14835 archive skip trees with the archive tag
14836 comment skip trees with the COMMENT keyword
14837 function or Emacs Lisp form:
14838 will be used as value for `org-agenda-skip-function', so
14839 whenever the function returns a position, FUNC will not be
14840 called for that entry and search will continue from the
14841 position returned
14843 If your function needs to retrieve the tags including inherited tags
14844 at the *current* entry, you can use the value of the variable
14845 `org-scanner-tags' which will be much faster than getting the value
14846 with `org-get-tags-at'. If your function gets properties with
14847 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14848 to t around the call to `org-entry-properties' to get the same speedup.
14849 Note that if your function moves around to retrieve tags and properties at
14850 a *different* entry, you cannot use these techniques."
14851 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14852 (not (org-region-active-p)))
14853 (let* ((org-agenda-archives-mode nil) ; just to make sure
14854 (org-agenda-skip-archived-trees (memq 'archive skip))
14855 (org-agenda-skip-comment-trees (memq 'comment skip))
14856 (org-agenda-skip-function
14857 (car (org-delete-all '(comment archive) skip)))
14858 (org-tags-match-list-sublevels t)
14859 (start-level (eq scope 'region-start-level))
14860 matcher file res
14861 org-todo-keywords-for-agenda
14862 org-done-keywords-for-agenda
14863 org-todo-keyword-alist-for-agenda
14864 org-drawers-for-agenda
14865 org-tag-alist-for-agenda
14866 todo-only)
14868 (cond
14869 ((eq match t) (setq matcher t))
14870 ((eq match nil) (setq matcher t))
14871 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14873 (save-window-excursion
14874 (save-restriction
14875 (cond ((eq scope 'tree)
14876 (org-back-to-heading t)
14877 (org-narrow-to-subtree)
14878 (setq scope nil))
14879 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14880 (org-region-active-p))
14881 ;; If needed, set start-level to a string like "2"
14882 (when start-level
14883 (save-excursion
14884 (goto-char (region-beginning))
14885 (unless (org-at-heading-p) (outline-next-heading))
14886 (setq start-level (org-current-level))))
14887 (narrow-to-region (region-beginning)
14888 (save-excursion
14889 (goto-char (region-end))
14890 (unless (and (bolp) (org-at-heading-p))
14891 (outline-next-heading))
14892 (point)))
14893 (setq scope nil)))
14895 (if (not scope)
14896 (progn
14897 (org-agenda-prepare-buffers
14898 (list (buffer-file-name (current-buffer))))
14899 (setq res (org-scan-tags func matcher todo-only start-level)))
14900 ;; Get the right scope
14901 (cond
14902 ((and scope (listp scope) (symbolp (car scope)))
14903 (setq scope (eval scope)))
14904 ((eq scope 'agenda)
14905 (setq scope (org-agenda-files t)))
14906 ((eq scope 'agenda-with-archives)
14907 (setq scope (org-agenda-files t))
14908 (setq scope (org-add-archive-files scope)))
14909 ((eq scope 'file)
14910 (setq scope (list (buffer-file-name))))
14911 ((eq scope 'file-with-archives)
14912 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14913 (org-agenda-prepare-buffers scope)
14914 (while (setq file (pop scope))
14915 (with-current-buffer (org-find-base-buffer-visiting file)
14916 (save-excursion
14917 (save-restriction
14918 (widen)
14919 (goto-char (point-min))
14920 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14921 res)))
14923 ;;;; Properties
14925 ;;; Setting and retrieving properties
14927 (defconst org-special-properties
14928 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14929 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14930 "The special properties valid in Org-mode.
14932 These are properties that are not defined in the property drawer,
14933 but in some other way.")
14935 (defconst org-default-properties
14936 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14937 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14938 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14939 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14940 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14941 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14942 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14943 "Some properties that are used by Org-mode for various purposes.
14944 Being in this list makes sure that they are offered for completion.")
14946 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14947 "Regular expression matching the first line of a property drawer.")
14949 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14950 "Regular expression matching the last line of a property drawer.")
14952 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14953 "Regular expression matching the first line of a property drawer.")
14955 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14956 "Regular expression matching the first line of a property drawer.")
14958 (defconst org-property-drawer-re
14959 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14960 org-property-end-re "\\)\n?")
14961 "Matches an entire property drawer.")
14963 (defconst org-clock-drawer-re
14964 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14965 org-property-end-re "\\)\n?")
14966 "Matches an entire clock drawer.")
14968 (defsubst org-re-property (property)
14969 "Return a regexp matching a PROPERTY line.
14970 Match group 1 will be set to the value."
14971 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14973 (defsubst org-re-property-keyword (property)
14974 "Return a regexp matching a PROPERTY line, possibly with no
14975 value for the property."
14976 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14978 (defun org-property-action ()
14979 "Do an action on properties."
14980 (interactive)
14981 (let (c)
14982 (org-at-property-p)
14983 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14984 (setq c (read-char-exclusive))
14985 (cond
14986 ((equal c ?s)
14987 (call-interactively 'org-set-property))
14988 ((equal c ?d)
14989 (call-interactively 'org-delete-property))
14990 ((equal c ?D)
14991 (call-interactively 'org-delete-property-globally))
14992 ((equal c ?c)
14993 (call-interactively 'org-compute-property-at-point))
14994 (t (user-error "No such property action %c" c)))))
14996 (defun org-inc-effort ()
14997 "Increment the value of the effort property in the current entry."
14998 (interactive)
14999 (org-set-effort nil t))
15001 (defvar org-clock-effort) ;; Defined in org-clock.el
15002 (defvar org-clock-current-task) ;; Defined in org-clock.el
15003 (defun org-set-effort (&optional value increment)
15004 "Set the effort property of the current entry.
15005 With numerical prefix arg, use the nth allowed value, 0 stands for the
15006 10th allowed value.
15008 When INCREMENT is non-nil, set the property to the next allowed value."
15009 (interactive "P")
15010 (if (equal value 0) (setq value 10))
15011 (let* ((completion-ignore-case t)
15012 (prop org-effort-property)
15013 (cur (org-entry-get nil prop))
15014 (allowed (org-property-get-allowed-values nil prop 'table))
15015 (existing (mapcar 'list (org-property-values prop)))
15016 (heading (nth 4 (org-heading-components)))
15018 (val (cond
15019 ((stringp value) value)
15020 ((and allowed (integerp value))
15021 (or (car (nth (1- value) allowed))
15022 (car (org-last allowed))))
15023 ((and allowed increment)
15024 (or (caadr (member (list cur) allowed))
15025 (user-error "Allowed effort values are not set")))
15026 (allowed
15027 (message "Select 1-9,0, [RET%s]: %s"
15028 (if cur (concat "=" cur) "")
15029 (mapconcat 'car allowed " "))
15030 (setq rpl (read-char-exclusive))
15031 (if (equal rpl ?\r)
15033 (setq rpl (- rpl ?0))
15034 (if (equal rpl 0) (setq rpl 10))
15035 (if (and (> rpl 0) (<= rpl (length allowed)))
15036 (car (nth (1- rpl) allowed))
15037 (org-completing-read "Effort: " allowed nil))))
15039 (let (org-completion-use-ido org-completion-use-iswitchb)
15040 (org-completing-read
15041 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15042 (concat "[" cur "]") "")
15043 ": ")
15044 existing nil nil "" nil cur))))))
15045 (unless (equal (org-entry-get nil prop) val)
15046 (org-entry-put nil prop val))
15047 (save-excursion
15048 (org-back-to-heading t)
15049 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15050 (when (string= heading org-clock-current-task)
15051 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15052 (org-clock-update-mode-line))
15053 (message "%s is now %s" prop val)))
15055 (defun org-at-property-p ()
15056 "Is cursor inside a property drawer?"
15057 (save-excursion
15058 (beginning-of-line 1)
15059 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15060 (save-match-data ;; Used by calling procedures
15061 (let ((p (point))
15062 (range (unless (org-before-first-heading-p)
15063 (org-get-property-block))))
15064 (and range (<= (car range) p) (< p (cdr range))))))))
15066 (defun org-get-property-block (&optional beg end force)
15067 "Return the (beg . end) range of the body of the property drawer.
15068 BEG and END are the beginning and end of the current subtree, or of
15069 the part before the first headline. If they are not given, they will
15070 be found. If the drawer does not exist and FORCE is non-nil, create
15071 the drawer."
15072 (catch 'exit
15073 (save-excursion
15074 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15075 (progn (org-back-to-heading t) (point))))
15076 (end (or end (and (not (outline-next-heading)) (point-max))
15077 (point))))
15078 (goto-char beg)
15079 (if (re-search-forward org-property-start-re end t)
15080 (setq beg (1+ (match-end 0)))
15081 (if force
15082 (save-excursion
15083 (org-insert-property-drawer)
15084 (setq end (progn (outline-next-heading) (point))))
15085 (throw 'exit nil))
15086 (goto-char beg)
15087 (if (re-search-forward org-property-start-re end t)
15088 (setq beg (1+ (match-end 0)))))
15089 (if (re-search-forward org-property-end-re end t)
15090 (setq end (match-beginning 0))
15091 (or force (throw 'exit nil))
15092 (goto-char beg)
15093 (setq end beg)
15094 (org-indent-line)
15095 (insert ":END:\n"))
15096 (cons beg end)))))
15098 (defun org-entry-properties (&optional pom which specific)
15099 "Get all properties of the entry at point-or-marker POM.
15100 This includes the TODO keyword, the tags, time strings for deadline,
15101 scheduled, and clocking, and any additional properties defined in the
15102 entry. The return value is an alist, keys may occur multiple times
15103 if the property key was used several times.
15104 POM may also be nil, in which case the current entry is used.
15105 If WHICH is nil or `all', get all properties. If WHICH is
15106 `special' or `standard', only get that subclass. If WHICH
15107 is a string only get exactly this property. SPECIFIC can be a string, the
15108 specific property we are interested in. Specifying it can speed
15109 things up because then unnecessary parsing is avoided."
15110 (setq which (or which 'all))
15111 (org-with-point-at pom
15112 (let ((clockstr (substring org-clock-string 0 -1))
15113 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15114 (case-fold-search nil)
15115 beg end range props sum-props key key1 value string clocksum clocksumt)
15116 (save-excursion
15117 (when (condition-case nil
15118 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15119 (error nil))
15120 (setq beg (point))
15121 (setq sum-props (get-text-property (point) 'org-summaries))
15122 (setq clocksum (get-text-property (point) :org-clock-minutes)
15123 clocksumt (get-text-property (point) :org-clock-minutes-today))
15124 (outline-next-heading)
15125 (setq end (point))
15126 (when (memq which '(all special))
15127 ;; Get the special properties, like TODO and tags
15128 (goto-char beg)
15129 (when (and (or (not specific) (string= specific "TODO"))
15130 (looking-at org-todo-line-regexp) (match-end 2))
15131 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15132 (when (and (or (not specific) (string= specific "PRIORITY"))
15133 (looking-at org-priority-regexp))
15134 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15135 (when (or (not specific) (string= specific "FILE"))
15136 (push (cons "FILE" buffer-file-name) props))
15137 (when (and (or (not specific) (string= specific "TAGS"))
15138 (setq value (org-get-tags-string))
15139 (string-match "\\S-" value))
15140 (push (cons "TAGS" value) props))
15141 (when (and (or (not specific) (string= specific "ALLTAGS"))
15142 (setq value (org-get-tags-at)))
15143 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15144 ":"))
15145 props))
15146 (when (or (not specific) (string= specific "BLOCKED"))
15147 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15148 (when (or (not specific)
15149 (member specific
15150 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15151 "TIMESTAMP" "TIMESTAMP_IA")))
15152 (catch 'match
15153 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15154 (setq key (if (match-end 1)
15155 (substring (org-match-string-no-properties 1)
15156 0 -1))
15157 string (if (equal key clockstr)
15158 (org-trim
15159 (buffer-substring-no-properties
15160 (match-beginning 3) (goto-char
15161 (point-at-eol))))
15162 (substring (org-match-string-no-properties 3)
15163 1 -1)))
15164 ;; Get the correct property name from the key. This is
15165 ;; necessary if the user has configured time keywords.
15166 (setq key1 (concat key ":"))
15167 (cond
15168 ((not key)
15169 (setq key
15170 (if (= (char-after (match-beginning 3)) ?\[)
15171 "TIMESTAMP_IA" "TIMESTAMP")))
15172 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15173 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15174 ((equal key1 org-closed-string) (setq key "CLOSED"))
15175 ((equal key1 org-clock-string) (setq key "CLOCK")))
15176 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15177 (progn
15178 (push (cons key string) props)
15179 ;; no need to search further if match is found
15180 (throw 'match t))
15181 (when (or (equal key "CLOCK") (not (assoc key props)))
15182 (push (cons key string) props)))))))
15184 (when (memq which '(all standard))
15185 ;; Get the standard properties, like :PROP: ...
15186 (setq range (org-get-property-block beg end))
15187 (when range
15188 (goto-char (car range))
15189 (while (re-search-forward
15190 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15191 (cdr range) t)
15192 (setq key (org-match-string-no-properties 1)
15193 value (org-trim (or (org-match-string-no-properties 2) "")))
15194 (unless (member key excluded)
15195 (push (cons key (or value "")) props)))))
15196 (if clocksum
15197 (push (cons "CLOCKSUM"
15198 (org-columns-number-to-string (/ (float clocksum) 60.)
15199 'add_times))
15200 props))
15201 (if clocksumt
15202 (push (cons "CLOCKSUM_T"
15203 (org-columns-number-to-string (/ (float clocksumt) 60.)
15204 'add_times))
15205 props))
15206 (unless (assoc "CATEGORY" props)
15207 (push (cons "CATEGORY" (org-get-category)) props))
15208 (append sum-props (nreverse props)))))))
15210 (defun org-entry-get (pom property &optional inherit literal-nil)
15211 "Get value of PROPERTY for entry or content at point-or-marker POM.
15212 If INHERIT is non-nil and the entry does not have the property,
15213 then also check higher levels of the hierarchy.
15214 If INHERIT is the symbol `selective', use inheritance only if the setting
15215 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15216 If the property is present but empty, the return value is the empty string.
15217 If the property is not present at all, nil is returned.
15219 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15220 do not interpret it as the list atom nil. This is used for inheritance
15221 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15222 (org-with-point-at pom
15223 (if (and inherit (if (eq inherit 'selective)
15224 (org-property-inherit-p property)
15226 (org-entry-get-with-inheritance property literal-nil)
15227 (if (member property org-special-properties)
15228 ;; We need a special property. Use `org-entry-properties' to
15229 ;; retrieve it, but specify the wanted property
15230 (cdr (assoc property (org-entry-properties nil 'special property)))
15231 (let ((range (org-get-property-block)))
15232 (when (and range (not (eq (car range) (cdr range))))
15233 (let* ((props (list (or (assoc property org-file-properties)
15234 (assoc property org-global-properties)
15235 (assoc property org-global-properties-fixed))))
15236 (ap (lambda (key)
15237 (when (re-search-forward
15238 (org-re-property key) (cdr range) t)
15239 (setq props
15240 (org-update-property-plist
15242 (if (match-end 1)
15243 (org-match-string-no-properties 1) "")
15244 props)))))
15245 val)
15246 (goto-char (car range))
15247 (funcall ap property)
15248 (goto-char (car range))
15249 (while (funcall ap (concat property "+")))
15250 (setq val (cdr (assoc property props)))
15251 (when val (if literal-nil val (org-not-nil val))))))))))
15253 (defun org-property-or-variable-value (var &optional inherit)
15254 "Check if there is a property fixing the value of VAR.
15255 If yes, return this value. If not, return the current value of the variable."
15256 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15257 (if (and prop (stringp prop) (string-match "\\S-" prop))
15258 (read prop)
15259 (symbol-value var))))
15261 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15262 "Delete the property PROPERTY from entry at point-or-marker POM.
15263 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15264 an empty drawer to delete."
15265 (org-with-point-at pom
15266 (if (member property org-special-properties)
15267 nil ; cannot delete these properties.
15268 (let ((range (org-get-property-block)))
15269 (if (and range
15270 (goto-char (car range))
15271 (re-search-forward
15272 (org-re-property property)
15273 (cdr range) t))
15274 (progn
15275 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15276 (and delete-empty-drawer
15277 (org-remove-empty-drawer-at
15278 delete-empty-drawer (car range)))
15280 nil)))))
15282 ;; Multi-values properties are properties that contain multiple values
15283 ;; These values are assumed to be single words, separated by whitespace.
15284 (defun org-entry-add-to-multivalued-property (pom property value)
15285 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15286 (let* ((old (org-entry-get pom property))
15287 (values (and old (org-split-string old "[ \t]"))))
15288 (setq value (org-entry-protect-space value))
15289 (unless (member value values)
15290 (setq values (append values (list value)))
15291 (org-entry-put pom property
15292 (mapconcat 'identity values " ")))))
15294 (defun org-entry-remove-from-multivalued-property (pom property value)
15295 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15296 (let* ((old (org-entry-get pom property))
15297 (values (and old (org-split-string old "[ \t]"))))
15298 (setq value (org-entry-protect-space value))
15299 (when (member value values)
15300 (setq values (delete value values))
15301 (org-entry-put pom property
15302 (mapconcat 'identity values " ")))))
15304 (defun org-entry-member-in-multivalued-property (pom property value)
15305 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15306 (let* ((old (org-entry-get pom property))
15307 (values (and old (org-split-string old "[ \t]"))))
15308 (setq value (org-entry-protect-space value))
15309 (member value values)))
15311 (defun org-entry-get-multivalued-property (pom property)
15312 "Return a list of values in a multivalued property."
15313 (let* ((value (org-entry-get pom property))
15314 (values (and value (org-split-string value "[ \t]"))))
15315 (mapcar 'org-entry-restore-space values)))
15317 (defun org-entry-put-multivalued-property (pom property &rest values)
15318 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15319 VALUES should be a list of strings. Spaces will be protected."
15320 (org-entry-put pom property
15321 (mapconcat 'org-entry-protect-space values " "))
15322 (let* ((value (org-entry-get pom property))
15323 (values (and value (org-split-string value "[ \t]"))))
15324 (mapcar 'org-entry-restore-space values)))
15326 (defun org-entry-protect-space (s)
15327 "Protect spaces and newline in string S."
15328 (while (string-match " " s)
15329 (setq s (replace-match "%20" t t s)))
15330 (while (string-match "\n" s)
15331 (setq s (replace-match "%0A" t t s)))
15334 (defun org-entry-restore-space (s)
15335 "Restore spaces and newline in string S."
15336 (while (string-match "%20" s)
15337 (setq s (replace-match " " t t s)))
15338 (while (string-match "%0A" s)
15339 (setq s (replace-match "\n" t t s)))
15342 (defvar org-entry-property-inherited-from (make-marker)
15343 "Marker pointing to the entry from where a property was inherited.
15344 Each call to `org-entry-get-with-inheritance' will set this marker to the
15345 location of the entry where the inheritance search matched. If there was
15346 no match, the marker will point nowhere.
15347 Note that also `org-entry-get' calls this function, if the INHERIT flag
15348 is set.")
15350 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15351 "Get PROPERTY of entry or content at point, search higher levels if needed.
15352 The search will stop at the first ancestor which has the property defined.
15353 If the value found is \"nil\", return nil to show that the property
15354 should be considered as undefined (this is the meaning of nil here).
15355 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15356 (move-marker org-entry-property-inherited-from nil)
15357 (let (tmp)
15358 (save-excursion
15359 (save-restriction
15360 (widen)
15361 (catch 'ex
15362 (while t
15363 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15364 (or (ignore-errors (org-back-to-heading t))
15365 (goto-char (point-min)))
15366 (move-marker org-entry-property-inherited-from (point))
15367 (throw 'ex tmp))
15368 (or (ignore-errors (org-up-heading-safe))
15369 (throw 'ex nil))))))
15370 (setq tmp (or tmp
15371 (cdr (assoc property org-file-properties))
15372 (cdr (assoc property org-global-properties))
15373 (cdr (assoc property org-global-properties-fixed))))
15374 (if literal-nil tmp (org-not-nil tmp))))
15376 (defvar org-property-changed-functions nil
15377 "Hook called when the value of a property has changed.
15378 Each hook function should accept two arguments, the name of the property
15379 and the new value.")
15381 (defun org-entry-put (pom property value)
15382 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15383 (org-with-point-at pom
15384 (org-back-to-heading t)
15385 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15386 range)
15387 (cond
15388 ((equal property "TODO")
15389 (when (and (stringp value) (string-match "\\S-" value)
15390 (not (member value org-todo-keywords-1)))
15391 (user-error "\"%s\" is not a valid TODO state" value))
15392 (if (or (not value)
15393 (not (string-match "\\S-" value)))
15394 (setq value 'none))
15395 (org-todo value)
15396 (org-set-tags nil 'align))
15397 ((equal property "PRIORITY")
15398 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15399 (string-to-char value) ?\ ))
15400 (org-set-tags nil 'align))
15401 ((equal property "CLOCKSUM")
15402 (if (not (re-search-forward
15403 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15404 (error "Cannot find a clock log")
15405 (goto-char (- (match-end 1) 2))
15406 (cond
15407 ((eq value 'earlier) (org-timestamp-down))
15408 ((eq value 'later) (org-timestamp-up)))
15409 (org-clock-sum-current-item)))
15410 ((equal property "SCHEDULED")
15411 (if (re-search-forward org-scheduled-time-regexp end t)
15412 (cond
15413 ((eq value 'earlier) (org-timestamp-change -1 'day))
15414 ((eq value 'later) (org-timestamp-change 1 'day))
15415 (t (call-interactively 'org-schedule)))
15416 (call-interactively 'org-schedule)))
15417 ((equal property "DEADLINE")
15418 (if (re-search-forward org-deadline-time-regexp end t)
15419 (cond
15420 ((eq value 'earlier) (org-timestamp-change -1 'day))
15421 ((eq value 'later) (org-timestamp-change 1 'day))
15422 (t (call-interactively 'org-deadline)))
15423 (call-interactively 'org-deadline)))
15424 ((member property org-special-properties)
15425 (error "The %s property can not yet be set with `org-entry-put'"
15426 property))
15427 (t ; a non-special property
15428 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15429 (setq range (org-get-property-block beg end 'force))
15430 (goto-char (car range))
15431 (if (re-search-forward
15432 (org-re-property-keyword property) (cdr range) t)
15433 (progn
15434 (delete-region (match-beginning 0) (match-end 0))
15435 (goto-char (match-beginning 0)))
15436 (goto-char (cdr range))
15437 (insert "\n")
15438 (backward-char 1)
15439 (org-indent-line))
15440 (insert ":" property ":")
15441 (and value (insert " " value))
15442 (org-indent-line)))))
15443 (run-hook-with-args 'org-property-changed-functions property value)))
15445 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15446 "Get all property keys in the current buffer.
15447 With INCLUDE-SPECIALS, also list the special properties that reflect things
15448 like tags and TODO state.
15449 With INCLUDE-DEFAULTS, also include properties that has special meaning
15450 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15451 and others.
15452 With INCLUDE-COLUMNS, also include property names given in COLUMN
15453 formats in the current buffer."
15454 (let (rtn range cfmt s p)
15455 (save-excursion
15456 (save-restriction
15457 (widen)
15458 (goto-char (point-min))
15459 (while (re-search-forward org-property-start-re nil t)
15460 (setq range (org-get-property-block))
15461 (goto-char (car range))
15462 (while (re-search-forward
15463 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15464 (cdr range) t)
15465 (add-to-list 'rtn (org-match-string-no-properties 1)))
15466 (outline-next-heading))))
15468 (when include-specials
15469 (setq rtn (append org-special-properties rtn)))
15471 (when include-defaults
15472 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15473 (add-to-list 'rtn org-effort-property))
15475 (when include-columns
15476 (save-excursion
15477 (save-restriction
15478 (widen)
15479 (goto-char (point-min))
15480 (while (re-search-forward
15481 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15482 nil t)
15483 (setq cfmt (match-string 2) s 0)
15484 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15485 cfmt s)
15486 (setq s (match-end 0)
15487 p (match-string 1 cfmt))
15488 (unless (or (equal p "ITEM")
15489 (member p org-special-properties))
15490 (add-to-list 'rtn (match-string 1 cfmt))))))))
15492 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15494 (defun org-property-values (key)
15495 "Return a list of all values of property KEY in the current buffer."
15496 (save-excursion
15497 (save-restriction
15498 (widen)
15499 (goto-char (point-min))
15500 (let ((re (org-re-property key))
15501 values)
15502 (while (re-search-forward re nil t)
15503 (add-to-list 'values (org-trim (match-string 1))))
15504 (delete "" values)))))
15506 (defun org-insert-property-drawer ()
15507 "Insert a property drawer into the current entry."
15508 (org-back-to-heading t)
15509 (looking-at org-outline-regexp)
15510 (let ((indent (if org-adapt-indentation
15511 (- (match-end 0) (match-beginning 0))
15513 (beg (point))
15514 (re (concat "^[ \t]*" org-keyword-time-regexp))
15515 end hiddenp)
15516 (outline-next-heading)
15517 (setq end (point))
15518 (goto-char beg)
15519 (while (re-search-forward re end t))
15520 (setq hiddenp (outline-invisible-p))
15521 (end-of-line 1)
15522 (and (equal (char-after) ?\n) (forward-char 1))
15523 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15524 (if (member (match-string 1) '("CLOCK:" ":END:"))
15525 ;; just skip this line
15526 (beginning-of-line 2)
15527 ;; Drawer start, find the end
15528 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15529 (beginning-of-line 1)))
15530 (org-skip-over-state-notes)
15531 (skip-chars-backward " \t\n\r")
15532 (if (eq (char-before) ?*) (forward-char 1))
15533 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15534 (beginning-of-line 0)
15535 (org-indent-to-column indent)
15536 (beginning-of-line 2)
15537 (org-indent-to-column indent)
15538 (beginning-of-line 0)
15539 (if hiddenp
15540 (save-excursion
15541 (org-back-to-heading t)
15542 (hide-entry))
15543 (org-flag-drawer t))))
15545 (defun org-insert-drawer (&optional arg drawer)
15546 "Insert a drawer at point.
15548 Optional argument DRAWER, when non-nil, is a string representing
15549 drawer's name. Otherwise, the user is prompted for a name.
15551 If a region is active, insert the drawer around that region
15552 instead.
15554 Point is left between drawer's boundaries."
15555 (interactive "P")
15556 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15557 "LOGBOOK"))
15558 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15559 ;; internally by Org. They are meant to be inserted
15560 ;; automatically.
15561 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15562 ;; Remove system drawers from list. Note: For some reason,
15563 ;; `org-completing-read' ignores the predicate while
15564 ;; `completing-read' handles it fine.
15565 (drawer (if arg "PROPERTIES"
15566 (or drawer
15567 (completing-read
15568 "Drawer: " org-drawers
15569 (lambda (d) (not (member d system-drawers))))))))
15570 (cond
15571 ;; With C-u, fall back on `org-insert-property-drawer'
15572 (arg (org-insert-property-drawer))
15573 ;; With an active region, insert a drawer at point.
15574 ((not (org-region-active-p))
15575 (progn
15576 (unless (bolp) (insert "\n"))
15577 (insert (format ":%s:\n\n:END:\n" drawer))
15578 (forward-line -2)))
15579 ;; Otherwise, insert the drawer at point
15581 (let ((rbeg (region-beginning))
15582 (rend (copy-marker (region-end))))
15583 (unwind-protect
15584 (progn
15585 (goto-char rbeg)
15586 (beginning-of-line)
15587 (when (save-excursion
15588 (re-search-forward org-outline-regexp-bol rend t))
15589 (user-error "Drawers cannot contain headlines"))
15590 ;; Position point at the beginning of the first
15591 ;; non-blank line in region. Insert drawer's opening
15592 ;; there, then indent it.
15593 (org-skip-whitespace)
15594 (beginning-of-line)
15595 (insert ":" drawer ":\n")
15596 (forward-line -1)
15597 (indent-for-tab-command)
15598 ;; Move point to the beginning of the first blank line
15599 ;; after the last non-blank line in region. Insert
15600 ;; drawer's closing, then indent it.
15601 (goto-char rend)
15602 (skip-chars-backward " \r\t\n")
15603 (insert "\n:END:")
15604 (deactivate-mark t)
15605 (indent-for-tab-command)
15606 (unless (eolp) (insert "\n")))
15607 ;; Clear marker, whatever the outcome of insertion is.
15608 (set-marker rend nil)))))))
15610 (defvar org-property-set-functions-alist nil
15611 "Property set function alist.
15612 Each entry should have the following format:
15614 (PROPERTY . READ-FUNCTION)
15616 The read function will be called with the same argument as
15617 `org-completing-read'.")
15619 (defun org-set-property-function (property)
15620 "Get the function that should be used to set PROPERTY.
15621 This is computed according to `org-property-set-functions-alist'."
15622 (or (cdr (assoc property org-property-set-functions-alist))
15623 'org-completing-read))
15625 (defun org-read-property-value (property)
15626 "Read PROPERTY value from user."
15627 (let* ((completion-ignore-case t)
15628 (allowed (org-property-get-allowed-values nil property 'table))
15629 (cur (org-entry-get nil property))
15630 (prompt (concat property " value"
15631 (if (and cur (string-match "\\S-" cur))
15632 (concat " [" cur "]") "") ": "))
15633 (set-function (org-set-property-function property))
15634 (val (if allowed
15635 (funcall set-function prompt allowed nil
15636 (not (get-text-property 0 'org-unrestricted
15637 (caar allowed))))
15638 (let (org-completion-use-ido org-completion-use-iswitchb)
15639 (funcall set-function prompt
15640 (mapcar 'list (org-property-values property))
15641 nil nil "" nil cur)))))
15642 (if (equal val "")
15644 val)))
15646 (defvar org-last-set-property nil)
15647 (defvar org-last-set-property-value nil)
15648 (defun org-read-property-name ()
15649 "Read a property name."
15650 (let* ((completion-ignore-case t)
15651 (keys (org-buffer-property-keys nil t t))
15652 (default-prop (or (save-excursion
15653 (save-match-data
15654 (beginning-of-line)
15655 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15656 (null (string= (match-string 1) "END"))
15657 (match-string 1))))
15658 org-last-set-property))
15659 (property (org-icompleting-read
15660 (concat "Property"
15661 (if default-prop (concat " [" default-prop "]") "")
15662 ": ")
15663 (mapcar 'list keys)
15664 nil nil nil nil
15665 default-prop)))
15666 (if (member property keys)
15667 property
15668 (or (cdr (assoc (downcase property)
15669 (mapcar (lambda (x) (cons (downcase x) x))
15670 keys)))
15671 property))))
15673 (defun org-set-property-and-value (use-last)
15674 "Allow to set [PROPERTY]: [value] direction from prompt.
15675 When use-default, don't even ask, just use the last
15676 \"[PROPERTY]: [value]\" string from the history."
15677 (interactive "P")
15678 (let* ((completion-ignore-case t)
15679 (pv (or (and use-last org-last-set-property-value)
15680 (org-completing-read
15681 "Enter a \"[Property]: [value]\" pair: "
15682 nil nil nil nil nil
15683 org-last-set-property-value)))
15684 prop val)
15685 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15686 (setq prop (match-string 1 pv)
15687 val (match-string 2 pv))
15688 (org-set-property prop val))))
15690 (defun org-set-property (property value)
15691 "In the current entry, set PROPERTY to VALUE.
15692 When called interactively, this will prompt for a property name, offering
15693 completion on existing and default properties. And then it will prompt
15694 for a value, offering completion either on allowed values (via an inherited
15695 xxx_ALL property) or on existing values in other instances of this property
15696 in the current file."
15697 (interactive (list nil nil))
15698 (let* ((property (or property (org-read-property-name)))
15699 (value (or value (org-read-property-value property)))
15700 (fn (cdr (assoc property org-properties-postprocess-alist))))
15701 (setq org-last-set-property property)
15702 (setq org-last-set-property-value (concat property ": " value))
15703 ;; Possibly postprocess the inserted value:
15704 (when fn (setq value (funcall fn value)))
15705 (unless (equal (org-entry-get nil property) value)
15706 (org-entry-put nil property value))))
15708 (defun org-delete-property (property &optional delete-empty-drawer)
15709 "In the current entry, delete PROPERTY.
15710 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15711 an empty drawer to delete."
15712 (interactive
15713 (let* ((completion-ignore-case t)
15714 (prop (org-icompleting-read "Property: "
15715 (org-entry-properties nil 'standard))))
15716 (list prop)))
15717 (message "Property %s %s" property
15718 (if (org-entry-delete nil property delete-empty-drawer)
15719 "deleted"
15720 "was not present in the entry")))
15722 (defun org-delete-property-globally (property)
15723 "Remove PROPERTY globally, from all entries."
15724 (interactive
15725 (let* ((completion-ignore-case t)
15726 (prop (org-icompleting-read
15727 "Globally remove property: "
15728 (mapcar 'list (org-buffer-property-keys)))))
15729 (list prop)))
15730 (save-excursion
15731 (save-restriction
15732 (widen)
15733 (goto-char (point-min))
15734 (let ((cnt 0))
15735 (while (re-search-forward
15736 (org-re-property property)
15737 nil t)
15738 (setq cnt (1+ cnt))
15739 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15740 (message "Property \"%s\" removed from %d entries" property cnt)))))
15742 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15744 (defun org-compute-property-at-point ()
15745 "Compute the property at point.
15746 This looks for an enclosing column format, extracts the operator and
15747 then applies it to the property in the column format's scope."
15748 (interactive)
15749 (unless (org-at-property-p)
15750 (user-error "Not at a property"))
15751 (let ((prop (org-match-string-no-properties 2)))
15752 (org-columns-get-format-and-top-level)
15753 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15754 (user-error "No operator defined for property %s" prop))
15755 (org-columns-compute prop)))
15757 (defvar org-property-allowed-value-functions nil
15758 "Hook for functions supplying allowed values for a specific property.
15759 The functions must take a single argument, the name of the property, and
15760 return a flat list of allowed values. If \":ETC\" is one of
15761 the values, this means that these values are intended as defaults for
15762 completion, but that other values should be allowed too.
15763 The functions must return nil if they are not responsible for this
15764 property.")
15766 (defun org-property-get-allowed-values (pom property &optional table)
15767 "Get allowed values for the property PROPERTY.
15768 When TABLE is non-nil, return an alist that can directly be used for
15769 completion."
15770 (let (vals)
15771 (cond
15772 ((equal property "TODO")
15773 (setq vals (org-with-point-at pom
15774 (append org-todo-keywords-1 '("")))))
15775 ((equal property "PRIORITY")
15776 (let ((n org-lowest-priority))
15777 (while (>= n org-highest-priority)
15778 (push (char-to-string n) vals)
15779 (setq n (1- n)))))
15780 ((member property org-special-properties))
15781 ((setq vals (run-hook-with-args-until-success
15782 'org-property-allowed-value-functions property)))
15784 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15785 (when (and vals (string-match "\\S-" vals))
15786 (setq vals (car (read-from-string (concat "(" vals ")"))))
15787 (setq vals (mapcar (lambda (x)
15788 (cond ((stringp x) x)
15789 ((numberp x) (number-to-string x))
15790 ((symbolp x) (symbol-name x))
15791 (t "???")))
15792 vals)))))
15793 (when (member ":ETC" vals)
15794 (setq vals (remove ":ETC" vals))
15795 (org-add-props (car vals) '(org-unrestricted t)))
15796 (if table (mapcar 'list vals) vals)))
15798 (defun org-property-previous-allowed-value (&optional previous)
15799 "Switch to the next allowed value for this property."
15800 (interactive)
15801 (org-property-next-allowed-value t))
15803 (defun org-property-next-allowed-value (&optional previous)
15804 "Switch to the next allowed value for this property."
15805 (interactive)
15806 (unless (org-at-property-p)
15807 (user-error "Not at a property"))
15808 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15809 (key (match-string 2))
15810 (value (match-string 3))
15811 (allowed (or (org-property-get-allowed-values (point) key)
15812 (and (member value '("[ ]" "[-]" "[X]"))
15813 '("[ ]" "[X]"))))
15814 (heading (save-match-data (nth 4 (org-heading-components))))
15815 nval)
15816 (unless allowed
15817 (user-error "Allowed values for this property have not been defined"))
15818 (if previous (setq allowed (reverse allowed)))
15819 (if (member value allowed)
15820 (setq nval (car (cdr (member value allowed)))))
15821 (setq nval (or nval (car allowed)))
15822 (if (equal nval value)
15823 (user-error "Only one allowed value for this property"))
15824 (org-at-property-p)
15825 (replace-match (concat " :" key ": " nval) t t)
15826 (org-indent-line)
15827 (beginning-of-line 1)
15828 (skip-chars-forward " \t")
15829 (when (equal prop org-effort-property)
15830 (save-excursion
15831 (org-back-to-heading t)
15832 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15833 (when (string= org-clock-current-task heading)
15834 (setq org-clock-effort nval)
15835 (org-clock-update-mode-line)))
15836 (run-hook-with-args 'org-property-changed-functions key nval)))
15838 (defun org-find-olp (path &optional this-buffer)
15839 "Return a marker pointing to the entry at outline path OLP.
15840 If anything goes wrong, throw an error.
15841 You can wrap this call to catch the error like this:
15843 (condition-case msg
15844 (org-mobile-locate-entry (match-string 4))
15845 (error (nth 1 msg)))
15847 The return value will then be either a string with the error message,
15848 or a marker if everything is OK.
15850 If THIS-BUFFER is set, the outline path does not contain a file,
15851 only headings."
15852 (let* ((file (if this-buffer buffer-file-name (pop path)))
15853 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15854 (level 1)
15855 (lmin 1)
15856 (lmax 1)
15857 limit re end found pos heading cnt flevel)
15858 (unless buffer (error "File not found :%s" file))
15859 (with-current-buffer buffer
15860 (save-excursion
15861 (save-restriction
15862 (widen)
15863 (setq limit (point-max))
15864 (goto-char (point-min))
15865 (while (setq heading (pop path))
15866 (setq re (format org-complex-heading-regexp-format
15867 (regexp-quote heading)))
15868 (setq cnt 0 pos (point))
15869 (while (re-search-forward re end t)
15870 (setq level (- (match-end 1) (match-beginning 1)))
15871 (if (and (>= level lmin) (<= level lmax))
15872 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15873 (when (= cnt 0) (error "Heading not found on level %d: %s"
15874 lmax heading))
15875 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15876 lmax heading))
15877 (goto-char found)
15878 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15879 (setq end (save-excursion (org-end-of-subtree t t))))
15880 (when (org-at-heading-p)
15881 (point-marker)))))))
15883 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15884 "Find node HEADING in BUFFER.
15885 Return a marker to the heading if it was found, or nil if not.
15886 If POS-ONLY is set, return just the position instead of a marker.
15888 The heading text must match exact, but it may have a TODO keyword,
15889 a priority cookie and tags in the standard locations."
15890 (with-current-buffer (or buffer (current-buffer))
15891 (save-excursion
15892 (save-restriction
15893 (widen)
15894 (goto-char (point-min))
15895 (let (case-fold-search)
15896 (if (re-search-forward
15897 (format org-complex-heading-regexp-format
15898 (regexp-quote heading)) nil t)
15899 (if pos-only
15900 (match-beginning 0)
15901 (move-marker (make-marker) (match-beginning 0)))))))))
15903 (defun org-find-exact-heading-in-directory (heading &optional dir)
15904 "Find Org node headline HEADING in all .org files in directory DIR.
15905 When the target headline is found, return a marker to this location."
15906 (let ((files (directory-files (or dir default-directory)
15907 nil "\\`[^.#].*\\.org\\'"))
15908 file visiting m buffer)
15909 (catch 'found
15910 (while (setq file (pop files))
15911 (message "trying %s" file)
15912 (setq visiting (org-find-base-buffer-visiting file))
15913 (setq buffer (or visiting (find-file-noselect file)))
15914 (setq m (org-find-exact-headline-in-buffer
15915 heading buffer))
15916 (when (and (not m) (not visiting)) (kill-buffer buffer))
15917 (and m (throw 'found m))))))
15919 (defun org-find-entry-with-id (ident)
15920 "Locate the entry that contains the ID property with exact value IDENT.
15921 IDENT can be a string, a symbol or a number, this function will search for
15922 the string representation of it.
15923 Return the position where this entry starts, or nil if there is no such entry."
15924 (interactive "sID: ")
15925 (let ((id (cond
15926 ((stringp ident) ident)
15927 ((symbol-name ident) (symbol-name ident))
15928 ((numberp ident) (number-to-string ident))
15929 (t (error "IDENT %s must be a string, symbol or number" ident))))
15930 (case-fold-search nil))
15931 (save-excursion
15932 (save-restriction
15933 (widen)
15934 (goto-char (point-min))
15935 (when (re-search-forward
15936 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15937 nil t)
15938 (org-back-to-heading t)
15939 (point))))))
15941 ;;;; Timestamps
15943 (defvar org-last-changed-timestamp nil)
15944 (defvar org-last-inserted-timestamp nil
15945 "The last time stamp inserted with `org-insert-time-stamp'.")
15946 (defvar org-time-was-given) ; dynamically scoped parameter
15947 (defvar org-end-time-was-given) ; dynamically scoped parameter
15948 (defvar org-ts-what) ; dynamically scoped parameter
15950 (defun org-time-stamp (arg &optional inactive)
15951 "Prompt for a date/time and insert a time stamp.
15952 If the user specifies a time like HH:MM or if this command is
15953 called with at least one prefix argument, the time stamp contains
15954 the date and the time. Otherwise, only the date is be included.
15956 All parts of a date not specified by the user is filled in from
15957 the current date/time. So if you just press return without
15958 typing anything, the time stamp will represent the current
15959 date/time.
15961 If there is already a timestamp at the cursor, it will be
15962 modified.
15964 With two universal prefix arguments, insert an active timestamp
15965 with the current time without prompting the user."
15966 (interactive "P")
15967 (let* ((ts nil)
15968 (default-time
15969 ;; Default time is either today, or, when entering a range,
15970 ;; the range start.
15971 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15972 (save-excursion
15973 (re-search-backward
15974 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15975 (- (point) 20) t)))
15976 (apply 'encode-time (org-parse-time-string (match-string 1)))
15977 (current-time)))
15978 (default-input (and ts (org-get-compact-tod ts)))
15979 (repeater (save-excursion
15980 (save-match-data
15981 (beginning-of-line)
15982 (when (re-search-forward
15983 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15984 (save-excursion (progn (end-of-line) (point))) t)
15985 (match-string 0)))))
15986 org-time-was-given org-end-time-was-given time)
15987 (cond
15988 ((and (org-at-timestamp-p t)
15989 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15990 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15991 (insert "--")
15992 (setq time (let ((this-command this-command))
15993 (org-read-date arg 'totime nil nil
15994 default-time default-input inactive)))
15995 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15996 ((org-at-timestamp-p t)
15997 (setq time (let ((this-command this-command))
15998 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15999 (when (org-at-timestamp-p t) ; just to get the match data
16000 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16001 (replace-match "")
16002 (setq org-last-changed-timestamp
16003 (org-insert-time-stamp
16004 time (or org-time-was-given arg)
16005 inactive nil nil (list org-end-time-was-given)))
16006 (when repeater (goto-char (1- (point))) (insert " " repeater)
16007 (setq org-last-changed-timestamp
16008 (concat (substring org-last-inserted-timestamp 0 -1)
16009 " " repeater ">"))))
16010 (message "Timestamp updated"))
16011 ((equal arg '(16))
16012 (org-insert-time-stamp (current-time) t))
16014 (setq time (let ((this-command this-command))
16015 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16016 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16017 nil nil (list org-end-time-was-given))))))
16019 ;; FIXME: can we use this for something else, like computing time differences?
16020 (defun org-get-compact-tod (s)
16021 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16022 (let* ((t1 (match-string 1 s))
16023 (h1 (string-to-number (match-string 2 s)))
16024 (m1 (string-to-number (match-string 3 s)))
16025 (t2 (and (match-end 4) (match-string 5 s)))
16026 (h2 (and t2 (string-to-number (match-string 6 s))))
16027 (m2 (and t2 (string-to-number (match-string 7 s))))
16028 dh dm)
16029 (if (not t2)
16031 (setq dh (- h2 h1) dm (- m2 m1))
16032 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16033 (concat t1 "+" (number-to-string dh)
16034 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16036 (defun org-time-stamp-inactive (&optional arg)
16037 "Insert an inactive time stamp.
16038 An inactive time stamp is enclosed in square brackets instead of angle
16039 brackets. It is inactive in the sense that it does not trigger agenda entries,
16040 does not link to the calendar and cannot be changed with the S-cursor keys.
16041 So these are more for recording a certain time/date."
16042 (interactive "P")
16043 (org-time-stamp arg 'inactive))
16045 (defvar org-date-ovl (make-overlay 1 1))
16046 (overlay-put org-date-ovl 'face 'org-date-selected)
16047 (org-detach-overlay org-date-ovl)
16049 (defvar org-ans1) ; dynamically scoped parameter
16050 (defvar org-ans2) ; dynamically scoped parameter
16052 (defvar org-plain-time-of-day-regexp) ; defined below
16054 (defvar org-overriding-default-time nil) ; dynamically scoped
16055 (defvar org-read-date-overlay nil)
16056 (defvar org-dcst nil) ; dynamically scoped
16057 (defvar org-read-date-history nil)
16058 (defvar org-read-date-final-answer nil)
16059 (defvar org-read-date-analyze-futurep nil)
16060 (defvar org-read-date-analyze-forced-year nil)
16061 (defvar org-read-date-inactive)
16063 (defvar org-read-date-minibuffer-local-map
16064 (let ((map (make-sparse-keymap)))
16065 (set-keymap-parent map minibuffer-local-map)
16066 (org-defkey map (kbd ".")
16067 (lambda () (interactive)
16068 (org-eval-in-calendar '(calendar-goto-today))))
16069 (org-defkey map [(meta shift left)]
16070 (lambda () (interactive)
16071 (org-eval-in-calendar '(calendar-backward-month 1))))
16072 (org-defkey map [(meta shift right)]
16073 (lambda () (interactive)
16074 (org-eval-in-calendar '(calendar-forward-month 1))))
16075 (org-defkey map [(meta shift up)]
16076 (lambda () (interactive)
16077 (org-eval-in-calendar '(calendar-backward-year 1))))
16078 (org-defkey map [(meta shift down)]
16079 (lambda () (interactive)
16080 (org-eval-in-calendar '(calendar-forward-year 1))))
16081 (org-defkey map [?\e (shift left)]
16082 (lambda () (interactive)
16083 (org-eval-in-calendar '(calendar-backward-month 1))))
16084 (org-defkey map [?\e (shift right)]
16085 (lambda () (interactive)
16086 (org-eval-in-calendar '(calendar-forward-month 1))))
16087 (org-defkey map [?\e (shift up)]
16088 (lambda () (interactive)
16089 (org-eval-in-calendar '(calendar-backward-year 1))))
16090 (org-defkey map [?\e (shift down)]
16091 (lambda () (interactive)
16092 (org-eval-in-calendar '(calendar-forward-year 1))))
16093 (org-defkey map [(shift up)]
16094 (lambda () (interactive)
16095 (org-eval-in-calendar '(calendar-backward-week 1))))
16096 (org-defkey map [(shift down)]
16097 (lambda () (interactive)
16098 (org-eval-in-calendar '(calendar-forward-week 1))))
16099 (org-defkey map [(shift left)]
16100 (lambda () (interactive)
16101 (org-eval-in-calendar '(calendar-backward-day 1))))
16102 (org-defkey map [(shift right)]
16103 (lambda () (interactive)
16104 (org-eval-in-calendar '(calendar-forward-day 1))))
16105 (org-defkey map "!"
16106 (lambda () (interactive)
16107 (org-eval-in-calendar '(diary-view-entries))
16108 (message "")))
16109 (org-defkey map ">"
16110 (lambda () (interactive)
16111 (org-eval-in-calendar '(scroll-calendar-left 1))))
16112 (org-defkey map "<"
16113 (lambda () (interactive)
16114 (org-eval-in-calendar '(scroll-calendar-right 1))))
16115 (org-defkey map "\C-v"
16116 (lambda () (interactive)
16117 (org-eval-in-calendar
16118 '(calendar-scroll-left-three-months 1))))
16119 (org-defkey map "\M-v"
16120 (lambda () (interactive)
16121 (org-eval-in-calendar
16122 '(calendar-scroll-right-three-months 1))))
16123 map)
16124 "Keymap for minibuffer commands when using `org-read-date'.")
16126 (defun org-read-date (&optional org-with-time to-time from-string prompt
16127 default-time default-input inactive)
16128 "Read a date, possibly a time, and make things smooth for the user.
16129 The prompt will suggest to enter an ISO date, but you can also enter anything
16130 which will at least partially be understood by `parse-time-string'.
16131 Unrecognized parts of the date will default to the current day, month, year,
16132 hour and minute. If this command is called to replace a timestamp at point,
16133 or to enter the second timestamp of a range, the default time is taken
16134 from the existing stamp. Furthermore, the command prefers the future,
16135 so if you are giving a date where the year is not given, and the day-month
16136 combination is already past in the current year, it will assume you
16137 mean next year. For details, see the manual. A few examples:
16139 3-2-5 --> 2003-02-05
16140 feb 15 --> currentyear-02-15
16141 2/15 --> currentyear-02-15
16142 sep 12 9 --> 2009-09-12
16143 12:45 --> today 12:45
16144 22 sept 0:34 --> currentyear-09-22 0:34
16145 12 --> currentyear-currentmonth-12
16146 Fri --> nearest Friday after today
16147 -Tue --> last Tuesday
16148 etc.
16150 Furthermore you can specify a relative date by giving, as the *first* thing
16151 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16152 change in days weeks, months, years.
16153 With a single plus or minus, the date is relative to today. With a double
16154 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16155 +4d --> four days from today
16156 +4 --> same as above
16157 +2w --> two weeks from today
16158 ++5 --> five days from default date
16160 The function understands only English month and weekday abbreviations.
16162 While prompting, a calendar is popped up - you can also select the
16163 date with the mouse (button 1). The calendar shows a period of three
16164 months. To scroll it to other months, use the keys `>' and `<'.
16165 If you don't like the calendar, turn it off with
16166 \(setq org-read-date-popup-calendar nil)
16168 With optional argument TO-TIME, the date will immediately be converted
16169 to an internal time.
16170 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16171 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16172 still enter a time, and this function will inform the calling routine
16173 about this change. The calling routine may then choose to change the
16174 format used to insert the time stamp into the buffer to include the time.
16175 With optional argument FROM-STRING, read from this string instead from
16176 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16177 the time/date that is used for everything that is not specified by the
16178 user."
16179 (require 'parse-time)
16180 (let* ((org-time-stamp-rounding-minutes
16181 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16182 (org-dcst org-display-custom-times)
16183 (ct (org-current-time))
16184 (org-def (or org-overriding-default-time default-time ct))
16185 (org-defdecode (decode-time org-def))
16186 (dummy (progn
16187 (when (< (nth 2 org-defdecode) org-extend-today-until)
16188 (setcar (nthcdr 2 org-defdecode) -1)
16189 (setcar (nthcdr 1 org-defdecode) 59)
16190 (setq org-def (apply 'encode-time org-defdecode)
16191 org-defdecode (decode-time org-def)))))
16192 (mouse-autoselect-window nil) ; Don't let the mouse jump
16193 (calendar-frame-setup nil)
16194 (calendar-setup nil)
16195 (calendar-move-hook nil)
16196 (calendar-view-diary-initially-flag nil)
16197 (calendar-view-holidays-initially-flag nil)
16198 (timestr (format-time-string
16199 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16200 (prompt (concat (if prompt (concat prompt " ") "")
16201 (format "Date+time [%s]: " timestr)))
16202 ans (org-ans0 "") org-ans1 org-ans2 final)
16204 (cond
16205 (from-string (setq ans from-string))
16206 (org-read-date-popup-calendar
16207 (save-excursion
16208 (save-window-excursion
16209 (calendar)
16210 (org-eval-in-calendar '(setq cursor-type nil) t)
16211 (unwind-protect
16212 (progn
16213 (calendar-forward-day (- (time-to-days org-def)
16214 (calendar-absolute-from-gregorian
16215 (calendar-current-date))))
16216 (org-eval-in-calendar nil t)
16217 (let* ((old-map (current-local-map))
16218 (map (copy-keymap calendar-mode-map))
16219 (minibuffer-local-map
16220 (copy-keymap org-read-date-minibuffer-local-map)))
16221 (org-defkey map (kbd "RET") 'org-calendar-select)
16222 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16223 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16224 (unwind-protect
16225 (progn
16226 (use-local-map map)
16227 (setq org-read-date-inactive inactive)
16228 (add-hook 'post-command-hook 'org-read-date-display)
16229 (setq org-ans0 (read-string prompt default-input
16230 'org-read-date-history nil))
16231 ;; org-ans0: from prompt
16232 ;; org-ans1: from mouse click
16233 ;; org-ans2: from calendar motion
16234 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16235 (remove-hook 'post-command-hook 'org-read-date-display)
16236 (use-local-map old-map)
16237 (when org-read-date-overlay
16238 (delete-overlay org-read-date-overlay)
16239 (setq org-read-date-overlay nil)))))
16240 (bury-buffer "*Calendar*")))))
16242 (t ; Naked prompt only
16243 (unwind-protect
16244 (setq ans (read-string prompt default-input
16245 'org-read-date-history timestr))
16246 (when org-read-date-overlay
16247 (delete-overlay org-read-date-overlay)
16248 (setq org-read-date-overlay nil)))))
16250 (setq final (org-read-date-analyze ans org-def org-defdecode))
16252 (when org-read-date-analyze-forced-year
16253 (message "Year was forced into %s"
16254 (if org-read-date-force-compatible-dates
16255 "compatible range (1970-2037)"
16256 "range representable on this machine"))
16257 (ding))
16259 ;; One round trip to get rid of 34th of August and stuff like that....
16260 (setq final (decode-time (apply 'encode-time final)))
16262 (setq org-read-date-final-answer ans)
16264 (if to-time
16265 (apply 'encode-time final)
16266 (if (and (boundp 'org-time-was-given) org-time-was-given)
16267 (format "%04d-%02d-%02d %02d:%02d"
16268 (nth 5 final) (nth 4 final) (nth 3 final)
16269 (nth 2 final) (nth 1 final))
16270 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16272 (defvar org-def)
16273 (defvar org-defdecode)
16274 (defvar org-with-time)
16275 (defun org-read-date-display ()
16276 "Display the current date prompt interpretation in the minibuffer."
16277 (when org-read-date-display-live
16278 (when org-read-date-overlay
16279 (delete-overlay org-read-date-overlay))
16280 (when (minibufferp (current-buffer))
16281 (save-excursion
16282 (end-of-line 1)
16283 (while (not (equal (buffer-substring
16284 (max (point-min) (- (point) 4)) (point))
16285 " "))
16286 (insert " ")))
16287 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16288 " " (or org-ans1 org-ans2)))
16289 (org-end-time-was-given nil)
16290 (f (org-read-date-analyze ans org-def org-defdecode))
16291 (fmts (if org-dcst
16292 org-time-stamp-custom-formats
16293 org-time-stamp-formats))
16294 (fmt (if (or org-with-time
16295 (and (boundp 'org-time-was-given) org-time-was-given))
16296 (cdr fmts)
16297 (car fmts)))
16298 (txt (format-time-string fmt (apply 'encode-time f)))
16299 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16300 (txt (concat "=> " txt)))
16301 (when (and org-end-time-was-given
16302 (string-match org-plain-time-of-day-regexp txt))
16303 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16304 org-end-time-was-given
16305 (substring txt (match-end 0)))))
16306 (when org-read-date-analyze-futurep
16307 (setq txt (concat txt " (=>F)")))
16308 (setq org-read-date-overlay
16309 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16310 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16312 (defun org-read-date-analyze (ans org-def org-defdecode)
16313 "Analyze the combined answer of the date prompt."
16314 ;; FIXME: cleanup and comment
16315 (let ((nowdecode (decode-time (current-time)))
16316 delta deltan deltaw deltadef year month day
16317 hour minute second wday pm h2 m2 tl wday1
16318 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16319 (setq org-read-date-analyze-futurep nil
16320 org-read-date-analyze-forced-year nil)
16321 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16322 (setq ans "+0"))
16324 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16325 (setq ans (replace-match "" t t ans)
16326 deltan (car delta)
16327 deltaw (nth 1 delta)
16328 deltadef (nth 2 delta)))
16330 ;; Check if there is an iso week date in there. If yes, store the
16331 ;; info and postpone interpreting it until the rest of the parsing
16332 ;; is done.
16333 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16334 (setq iso-year (if (match-end 1)
16335 (org-small-year-to-year
16336 (string-to-number (match-string 1 ans))))
16337 iso-weekday (if (match-end 3)
16338 (string-to-number (match-string 3 ans)))
16339 iso-week (string-to-number (match-string 2 ans)))
16340 (setq ans (replace-match "" t t ans)))
16342 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16343 (when (string-match
16344 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16345 (setq year (if (match-end 2)
16346 (string-to-number (match-string 2 ans))
16347 (progn (setq kill-year t)
16348 (string-to-number (format-time-string "%Y"))))
16349 month (string-to-number (match-string 3 ans))
16350 day (string-to-number (match-string 4 ans)))
16351 (if (< year 100) (setq year (+ 2000 year)))
16352 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16353 t nil ans)))
16355 ;; Help matching dotted european dates
16356 (when (string-match
16357 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16358 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16359 (setq kill-year t)
16360 (string-to-number (format-time-string "%Y")))
16361 day (string-to-number (match-string 1 ans))
16362 month (string-to-number (match-string 2 ans))
16363 ans (replace-match (format "%04d-%02d-%02d" year month day)
16364 t nil ans)))
16366 ;; Help matching american dates, like 5/30 or 5/30/7
16367 (when (string-match
16368 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16369 (setq year (if (match-end 4)
16370 (string-to-number (match-string 4 ans))
16371 (progn (setq kill-year t)
16372 (string-to-number (format-time-string "%Y"))))
16373 month (string-to-number (match-string 1 ans))
16374 day (string-to-number (match-string 2 ans)))
16375 (if (< year 100) (setq year (+ 2000 year)))
16376 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16377 t nil ans)))
16378 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16379 ;; If there is a time with am/pm, and *no* time without it, we convert
16380 ;; so that matching will be successful.
16381 (loop for i from 1 to 2 do ; twice, for end time as well
16382 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16383 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16384 (setq hour (string-to-number (match-string 1 ans))
16385 minute (if (match-end 3)
16386 (string-to-number (match-string 3 ans))
16388 pm (equal ?p
16389 (string-to-char (downcase (match-string 4 ans)))))
16390 (if (and (= hour 12) (not pm))
16391 (setq hour 0)
16392 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16393 (setq ans (replace-match (format "%02d:%02d" hour minute)
16394 t t ans))))
16396 ;; Check if a time range is given as a duration
16397 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16398 (setq hour (string-to-number (match-string 1 ans))
16399 h2 (+ hour (string-to-number (match-string 3 ans)))
16400 minute (string-to-number (match-string 2 ans))
16401 m2 (+ minute (if (match-end 5) (string-to-number
16402 (match-string 5 ans))0)))
16403 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16404 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16405 t t ans)))
16407 ;; Check if there is a time range
16408 (when (boundp 'org-end-time-was-given)
16409 (setq org-time-was-given nil)
16410 (when (and (string-match org-plain-time-of-day-regexp ans)
16411 (match-end 8))
16412 (setq org-end-time-was-given (match-string 8 ans))
16413 (setq ans (concat (substring ans 0 (match-beginning 7))
16414 (substring ans (match-end 7))))))
16416 (setq tl (parse-time-string ans)
16417 day (or (nth 3 tl) (nth 3 org-defdecode))
16418 month (or (nth 4 tl)
16419 (if (and org-read-date-prefer-future
16420 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16421 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16422 (nth 4 org-defdecode)))
16423 year (or (and (not kill-year) (nth 5 tl))
16424 (if (and org-read-date-prefer-future
16425 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16426 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16427 (nth 5 org-defdecode)))
16428 hour (or (nth 2 tl) (nth 2 org-defdecode))
16429 minute (or (nth 1 tl) (nth 1 org-defdecode))
16430 second (or (nth 0 tl) 0)
16431 wday (nth 6 tl))
16433 (when (and (eq org-read-date-prefer-future 'time)
16434 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16435 (equal day (nth 3 nowdecode))
16436 (equal month (nth 4 nowdecode))
16437 (equal year (nth 5 nowdecode))
16438 (nth 2 tl)
16439 (or (< (nth 2 tl) (nth 2 nowdecode))
16440 (and (= (nth 2 tl) (nth 2 nowdecode))
16441 (nth 1 tl)
16442 (< (nth 1 tl) (nth 1 nowdecode)))))
16443 (setq day (1+ day)
16444 futurep t))
16446 ;; Special date definitions below
16447 (cond
16448 (iso-week
16449 ;; There was an iso week
16450 (require 'cal-iso)
16451 (setq futurep nil)
16452 (setq year (or iso-year year)
16453 day (or iso-weekday wday 1)
16454 wday nil ; to make sure that the trigger below does not match
16455 iso-date (calendar-gregorian-from-absolute
16456 (calendar-absolute-from-iso
16457 (list iso-week day year))))
16458 ; FIXME: Should we also push ISO weeks into the future?
16459 ; (when (and org-read-date-prefer-future
16460 ; (not iso-year)
16461 ; (< (calendar-absolute-from-gregorian iso-date)
16462 ; (time-to-days (current-time))))
16463 ; (setq year (1+ year)
16464 ; iso-date (calendar-gregorian-from-absolute
16465 ; (calendar-absolute-from-iso
16466 ; (list iso-week day year)))))
16467 (setq month (car iso-date)
16468 year (nth 2 iso-date)
16469 day (nth 1 iso-date)))
16470 (deltan
16471 (setq futurep nil)
16472 (unless deltadef
16473 (let ((now (decode-time (current-time))))
16474 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16475 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16476 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16477 ((equal deltaw "m") (setq month (+ month deltan)))
16478 ((equal deltaw "y") (setq year (+ year deltan)))))
16479 ((and wday (not (nth 3 tl)))
16480 ;; Weekday was given, but no day, so pick that day in the week
16481 ;; on or after the derived date.
16482 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16483 (unless (equal wday wday1)
16484 (setq day (+ day (% (- wday wday1 -7) 7))))))
16485 (if (and (boundp 'org-time-was-given)
16486 (nth 2 tl))
16487 (setq org-time-was-given t))
16488 (if (< year 100) (setq year (+ 2000 year)))
16489 ;; Check of the date is representable
16490 (if org-read-date-force-compatible-dates
16491 (progn
16492 (if (< year 1970)
16493 (setq year 1970 org-read-date-analyze-forced-year t))
16494 (if (> year 2037)
16495 (setq year 2037 org-read-date-analyze-forced-year t)))
16496 (condition-case nil
16497 (ignore (encode-time second minute hour day month year))
16498 (error
16499 (setq year (nth 5 org-defdecode))
16500 (setq org-read-date-analyze-forced-year t))))
16501 (setq org-read-date-analyze-futurep futurep)
16502 (list second minute hour day month year)))
16504 (defvar parse-time-weekdays)
16505 (defun org-read-date-get-relative (s today default)
16506 "Check string S for special relative date string.
16507 TODAY and DEFAULT are internal times, for today and for a default.
16508 Return shift list (N what def-flag)
16509 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16510 N is the number of WHATs to shift.
16511 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16512 the DEFAULT date rather than TODAY."
16513 (require 'parse-time)
16514 (when (and
16515 (string-match
16516 (concat
16517 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16518 "\\([0-9]+\\)?"
16519 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16520 "\\([ \t]\\|$\\)") s)
16521 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16522 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16523 (string-to-char (substring (match-string 1 s) -1))
16524 ?+))
16525 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16526 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16527 (what (if (match-end 3) (match-string 3 s) "d"))
16528 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16529 (date (if rel default today))
16530 (wday (nth 6 (decode-time date)))
16531 delta)
16532 (if wday1
16533 (progn
16534 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16535 (if (= delta 0) (setq delta 7))
16536 (if (= dir ?-)
16537 (progn
16538 (setq delta (- delta 7))
16539 (if (= delta 0) (setq delta -7))))
16540 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16541 (list delta "d" rel))
16542 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16544 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16545 "Turn a user-specified date into the internal representation.
16546 The internal representation needed by the calendar is (month day year).
16547 This is a wrapper to handle the brain-dead convention in calendar that
16548 user function argument order change dependent on argument order."
16549 (if (boundp 'calendar-date-style)
16550 (cond
16551 ((eq calendar-date-style 'american)
16552 (list arg1 arg2 arg3))
16553 ((eq calendar-date-style 'european)
16554 (list arg2 arg1 arg3))
16555 ((eq calendar-date-style 'iso)
16556 (list arg2 arg3 arg1)))
16557 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16558 (if (org-bound-and-true-p european-calendar-style)
16559 (list arg2 arg1 arg3)
16560 (list arg1 arg2 arg3)))))
16562 (defun org-eval-in-calendar (form &optional keepdate)
16563 "Eval FORM in the calendar window and return to current window.
16564 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16565 otherwise stick to the current value of `org-ans2'."
16566 (let ((sf (selected-frame))
16567 (sw (selected-window)))
16568 (select-window (get-buffer-window "*Calendar*" t))
16569 (eval form)
16570 (when (and (not keepdate) (calendar-cursor-to-date))
16571 (let* ((date (calendar-cursor-to-date))
16572 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16573 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16574 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16575 (select-window sw)
16576 (org-select-frame-set-input-focus sf)))
16578 (defun org-calendar-select ()
16579 "Return to `org-read-date' with the date currently selected.
16580 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16581 (interactive)
16582 (when (calendar-cursor-to-date)
16583 (let* ((date (calendar-cursor-to-date))
16584 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16585 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16586 (if (active-minibuffer-window) (exit-minibuffer))))
16588 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16589 "Insert a date stamp for the date given by the internal TIME.
16590 WITH-HM means use the stamp format that includes the time of the day.
16591 INACTIVE means use square brackets instead of angular ones, so that the
16592 stamp will not contribute to the agenda.
16593 PRE and POST are optional strings to be inserted before and after the
16594 stamp.
16595 The command returns the inserted time stamp."
16596 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16597 stamp)
16598 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16599 (insert-before-markers (or pre ""))
16600 (when (listp extra)
16601 (setq extra (car extra))
16602 (if (and (stringp extra)
16603 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16604 (setq extra (format "-%02d:%02d"
16605 (string-to-number (match-string 1 extra))
16606 (string-to-number (match-string 2 extra))))
16607 (setq extra nil)))
16608 (when extra
16609 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16610 (insert-before-markers (setq stamp (format-time-string fmt time)))
16611 (insert-before-markers (or post ""))
16612 (setq org-last-inserted-timestamp stamp)))
16614 (defun org-toggle-time-stamp-overlays ()
16615 "Toggle the use of custom time stamp formats."
16616 (interactive)
16617 (setq org-display-custom-times (not org-display-custom-times))
16618 (unless org-display-custom-times
16619 (let ((p (point-min)) (bmp (buffer-modified-p)))
16620 (while (setq p (next-single-property-change p 'display))
16621 (if (and (get-text-property p 'display)
16622 (eq (get-text-property p 'face) 'org-date))
16623 (remove-text-properties
16624 p (setq p (next-single-property-change p 'display))
16625 '(display t))))
16626 (set-buffer-modified-p bmp)))
16627 (if (featurep 'xemacs)
16628 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16629 (org-restart-font-lock)
16630 (setq org-table-may-need-update t)
16631 (if org-display-custom-times
16632 (message "Time stamps are overlaid with custom format")
16633 (message "Time stamp overlays removed")))
16635 (defun org-display-custom-time (beg end)
16636 "Overlay modified time stamp format over timestamp between BEG and END."
16637 (let* ((ts (buffer-substring beg end))
16638 t1 w1 with-hm tf time str w2 (off 0))
16639 (save-match-data
16640 (setq t1 (org-parse-time-string ts t))
16641 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16642 (setq off (- (match-end 0) (match-beginning 0)))))
16643 (setq end (- end off))
16644 (setq w1 (- end beg)
16645 with-hm (and (nth 1 t1) (nth 2 t1))
16646 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16647 time (org-fix-decoded-time t1)
16648 str (org-add-props
16649 (format-time-string
16650 (substring tf 1 -1) (apply 'encode-time time))
16651 nil 'mouse-face 'highlight)
16652 w2 (length str))
16653 (if (not (= w2 w1))
16654 (add-text-properties (1+ beg) (+ 2 beg)
16655 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16656 (if (featurep 'xemacs)
16657 (progn
16658 (put-text-property beg end 'invisible t)
16659 (put-text-property beg end 'end-glyph (make-glyph str)))
16660 (put-text-property beg end 'display str))))
16662 (defun org-translate-time (string)
16663 "Translate all timestamps in STRING to custom format.
16664 But do this only if the variable `org-display-custom-times' is set."
16665 (when org-display-custom-times
16666 (save-match-data
16667 (let* ((start 0)
16668 (re org-ts-regexp-both)
16669 t1 with-hm inactive tf time str beg end)
16670 (while (setq start (string-match re string start))
16671 (setq beg (match-beginning 0)
16672 end (match-end 0)
16673 t1 (save-match-data
16674 (org-parse-time-string (substring string beg end) t))
16675 with-hm (and (nth 1 t1) (nth 2 t1))
16676 inactive (equal (substring string beg (1+ beg)) "[")
16677 tf (funcall (if with-hm 'cdr 'car)
16678 org-time-stamp-custom-formats)
16679 time (org-fix-decoded-time t1)
16680 str (format-time-string
16681 (concat
16682 (if inactive "[" "<") (substring tf 1 -1)
16683 (if inactive "]" ">"))
16684 (apply 'encode-time time))
16685 string (replace-match str t t string)
16686 start (+ start (length str)))))))
16687 string)
16689 (defun org-fix-decoded-time (time)
16690 "Set 0 instead of nil for the first 6 elements of time.
16691 Don't touch the rest."
16692 (let ((n 0))
16693 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16695 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16697 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16698 "Difference between TIMESTAMP-STRING and now in days.
16699 If SECONDS is non-nil, return the difference in seconds."
16700 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16701 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16702 (funcall fdiff (current-time)))))
16704 (defun org-deadline-close (timestamp-string &optional ndays)
16705 "Is the time in TIMESTAMP-STRING close to the current date?"
16706 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16707 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16708 (not (org-entry-is-done-p))))
16710 (defun org-get-wdays (ts &optional delay zero-delay)
16711 "Get the deadline lead time appropriate for timestring TS.
16712 When DELAY is non-nil, get the delay time for scheduled items
16713 instead of the deadline lead time. When ZERO-DELAY is non-nil
16714 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16715 don't try to find the delay cookie in the scheduled timestamp."
16716 (let ((tv (if delay org-scheduled-delay-days
16717 org-deadline-warning-days)))
16718 (cond
16719 ((or (and delay (< tv 0))
16720 (and delay zero-delay (<= tv 0))
16721 (and (not delay) (<= tv 0)))
16722 ;; Enforce this value no matter what
16723 (- tv))
16724 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16725 ;; lead time is specified.
16726 (floor (* (string-to-number (match-string 1 ts))
16727 (cdr (assoc (match-string 2 ts)
16728 '(("d" . 1) ("w" . 7)
16729 ("m" . 30.4) ("y" . 365.25)
16730 ("h" . 0.041667)))))))
16731 ;; go for the default.
16732 (t tv))))
16734 (defun org-calendar-select-mouse (ev)
16735 "Return to `org-read-date' with the date currently selected.
16736 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16737 (interactive "e")
16738 (mouse-set-point ev)
16739 (when (calendar-cursor-to-date)
16740 (let* ((date (calendar-cursor-to-date))
16741 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16742 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16743 (if (active-minibuffer-window) (exit-minibuffer))))
16745 (defun org-check-deadlines (ndays)
16746 "Check if there are any deadlines due or past due.
16747 A deadline is considered due if it happens within `org-deadline-warning-days'
16748 days from today's date. If the deadline appears in an entry marked DONE,
16749 it is not shown. The prefix arg NDAYS can be used to test that many
16750 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16751 (interactive "P")
16752 (let* ((org-warn-days
16753 (cond
16754 ((equal ndays '(4)) 100000)
16755 (ndays (prefix-numeric-value ndays))
16756 (t (abs org-deadline-warning-days))))
16757 (case-fold-search nil)
16758 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16759 (callback
16760 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16762 (message "%d deadlines past-due or due within %d days"
16763 (org-occur regexp nil callback)
16764 org-warn-days)))
16766 (defsubst org-re-timestamp (type)
16767 "Return a regexp for timestamp TYPE.
16768 Allowed values for TYPE are:
16770 all: all timestamps
16771 active: only active timestamps (<...>)
16772 inactive: only inactive timestamps ([...])
16773 scheduled: only scheduled timestamps
16774 deadline: only deadline timestamps
16775 closed: only closed time-stamps
16777 When TYPE is nil, fall back on returning a regexp that matches
16778 both scheduled and deadline timestamps."
16779 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16780 ((eq type 'active) org-ts-regexp)
16781 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16782 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16783 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16784 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16785 ((eq type 'scheduled-or-deadline)
16786 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16788 (defun org-check-before-date (date)
16789 "Check if there are deadlines or scheduled entries before DATE."
16790 (interactive (list (org-read-date)))
16791 (let ((case-fold-search nil)
16792 (regexp (org-re-timestamp org-ts-type))
16793 (callback
16794 (lambda () (time-less-p
16795 (org-time-string-to-time (match-string 1))
16796 (org-time-string-to-time date)))))
16797 (message "%d entries before %s"
16798 (org-occur regexp nil callback) date)))
16800 (defun org-check-after-date (date)
16801 "Check if there are deadlines or scheduled entries after DATE."
16802 (interactive (list (org-read-date)))
16803 (let ((case-fold-search nil)
16804 (regexp (org-re-timestamp org-ts-type))
16805 (callback
16806 (lambda () (not
16807 (time-less-p
16808 (org-time-string-to-time (match-string 1))
16809 (org-time-string-to-time date))))))
16810 (message "%d entries after %s"
16811 (org-occur regexp nil callback) date)))
16813 (defun org-check-dates-range (start-date end-date)
16814 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16815 (interactive (list (org-read-date nil nil nil "Range starts")
16816 (org-read-date nil nil nil "Range end")))
16817 (let ((case-fold-search nil)
16818 (regexp (org-re-timestamp org-ts-type))
16819 (callback
16820 (lambda ()
16821 (let ((match (match-string 1)))
16822 (and
16823 (not (time-less-p
16824 (org-time-string-to-time match)
16825 (org-time-string-to-time start-date)))
16826 (time-less-p
16827 (org-time-string-to-time match)
16828 (org-time-string-to-time end-date)))))))
16829 (message "%d entries between %s and %s"
16830 (org-occur regexp nil callback) start-date end-date)))
16832 (defun org-evaluate-time-range (&optional to-buffer)
16833 "Evaluate a time range by computing the difference between start and end.
16834 Normally the result is just printed in the echo area, but with prefix arg
16835 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16836 If the time range is actually in a table, the result is inserted into the
16837 next column.
16838 For time difference computation, a year is assumed to be exactly 365
16839 days in order to avoid rounding problems."
16840 (interactive "P")
16842 (org-clock-update-time-maybe)
16843 (save-excursion
16844 (unless (org-at-date-range-p t)
16845 (goto-char (point-at-bol))
16846 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16847 (if (not (org-at-date-range-p t))
16848 (user-error "Not at a time-stamp range, and none found in current line")))
16849 (let* ((ts1 (match-string 1))
16850 (ts2 (match-string 2))
16851 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16852 (match-end (match-end 0))
16853 (time1 (org-time-string-to-time ts1))
16854 (time2 (org-time-string-to-time ts2))
16855 (t1 (org-float-time time1))
16856 (t2 (org-float-time time2))
16857 (diff (abs (- t2 t1)))
16858 (negative (< (- t2 t1) 0))
16859 ;; (ys (floor (* 365 24 60 60)))
16860 (ds (* 24 60 60))
16861 (hs (* 60 60))
16862 (fy "%dy %dd %02d:%02d")
16863 (fy1 "%dy %dd")
16864 (fd "%dd %02d:%02d")
16865 (fd1 "%dd")
16866 (fh "%02d:%02d")
16867 y d h m align)
16868 (if havetime
16869 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16871 d (floor (/ diff ds)) diff (mod diff ds)
16872 h (floor (/ diff hs)) diff (mod diff hs)
16873 m (floor (/ diff 60)))
16874 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16876 d (floor (+ (/ diff ds) 0.5))
16877 h 0 m 0))
16878 (if (not to-buffer)
16879 (message "%s" (org-make-tdiff-string y d h m))
16880 (if (org-at-table-p)
16881 (progn
16882 (goto-char match-end)
16883 (setq align t)
16884 (and (looking-at " *|") (goto-char (match-end 0))))
16885 (goto-char match-end))
16886 (if (looking-at
16887 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16888 (replace-match ""))
16889 (if negative (insert " -"))
16890 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16891 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16892 (insert " " (format fh h m))))
16893 (if align (org-table-align))
16894 (message "Time difference inserted")))))
16896 (defun org-make-tdiff-string (y d h m)
16897 (let ((fmt "")
16898 (l nil))
16899 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16900 l (push y l)))
16901 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16902 l (push d l)))
16903 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16904 l (push h l)))
16905 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16906 l (push m l)))
16907 (apply 'format fmt (nreverse l))))
16909 (defun org-time-string-to-time (s &optional buffer pos)
16910 "Convert a timestamp string into internal time."
16911 (condition-case errdata
16912 (apply 'encode-time (org-parse-time-string s))
16913 (error (error "Bad timestamp `%s'%s\nError was: %s"
16914 s (if (not (and buffer pos))
16916 (format " at %d in buffer `%s'" pos buffer))
16917 (cdr errdata)))))
16919 (defun org-time-string-to-seconds (s)
16920 "Convert a timestamp string to a number of seconds."
16921 (org-float-time (org-time-string-to-time s)))
16923 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16924 "Convert a time stamp to an absolute day number.
16925 If there is a specifier for a cyclic time stamp, get the closest
16926 date to DAYNR.
16927 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16928 The variable `date' is bound by the calendar when this is called."
16929 (cond
16930 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16931 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16932 daynr
16933 (+ daynr 1000)))
16934 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16935 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16936 (time-to-days (current-time))) (match-string 0 s)
16937 prefer show-all))
16938 (t (time-to-days
16939 (condition-case errdata
16940 (apply 'encode-time (org-parse-time-string s))
16941 (error (error "Bad timestamp `%s'%s\nError was: %s"
16942 s (if (not (and buffer pos))
16944 (format " at %d in buffer `%s'" pos buffer))
16945 (cdr errdata))))))))
16947 (defun org-days-to-iso-week (days)
16948 "Return the iso week number."
16949 (require 'cal-iso)
16950 (car (calendar-iso-from-absolute days)))
16952 (defun org-small-year-to-year (year)
16953 "Convert 2-digit years into 4-digit years.
16954 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
16955 The year 2000 cannot be abbreviated. Any year larger than 99
16956 is returned unchanged."
16957 (if (< year 38)
16958 (setq year (+ 2000 year))
16959 (if (< year 100)
16960 (setq year (+ 1900 year))))
16961 year)
16963 (defun org-time-from-absolute (d)
16964 "Return the time corresponding to date D.
16965 D may be an absolute day number, or a calendar-type list (month day year)."
16966 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16967 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16969 (defun org-calendar-holiday ()
16970 "List of holidays, for Diary display in Org-mode."
16971 (require 'holidays)
16972 (let ((hl (funcall
16973 (if (fboundp 'calendar-check-holidays)
16974 'calendar-check-holidays 'check-calendar-holidays) date)))
16975 (if hl (mapconcat 'identity hl "; "))))
16977 (defun org-diary-sexp-entry (sexp entry date)
16978 "Process a SEXP diary ENTRY for DATE."
16979 (require 'diary-lib)
16980 (let ((result (if calendar-debug-sexp
16981 (let ((stack-trace-on-error t))
16982 (eval (car (read-from-string sexp))))
16983 (condition-case nil
16984 (eval (car (read-from-string sexp)))
16985 (error
16986 (beep)
16987 (message "Bad sexp at line %d in %s: %s"
16988 (org-current-line)
16989 (buffer-file-name) sexp)
16990 (sleep-for 2))))))
16991 (cond ((stringp result) (split-string result "; "))
16992 ((and (consp result)
16993 (not (consp (cdr result)))
16994 (stringp (cdr result))) (cdr result))
16995 ((and (consp result)
16996 (stringp (car result))) result)
16997 (result entry))))
16999 (defun org-diary-to-ical-string (frombuf)
17000 "Get iCalendar entries from diary entries in buffer FROMBUF.
17001 This uses the icalendar.el library."
17002 (let* ((tmpdir (if (featurep 'xemacs)
17003 (temp-directory)
17004 temporary-file-directory))
17005 (tmpfile (make-temp-name
17006 (expand-file-name "orgics" tmpdir)))
17007 buf rtn b e)
17008 (with-current-buffer frombuf
17009 (icalendar-export-region (point-min) (point-max) tmpfile)
17010 (setq buf (find-buffer-visiting tmpfile))
17011 (set-buffer buf)
17012 (goto-char (point-min))
17013 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17014 (setq b (match-beginning 0)))
17015 (goto-char (point-max))
17016 (if (re-search-backward "^END:VEVENT" nil t)
17017 (setq e (match-end 0)))
17018 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17019 (kill-buffer buf)
17020 (delete-file tmpfile)
17021 rtn))
17023 (defun org-closest-date (start current change prefer show-all)
17024 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17025 When PREFER is `past', return a date that is either CURRENT or past.
17026 When PREFER is `future', return a date that is either CURRENT or future.
17027 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17028 ;; Make the proper lists from the dates
17029 (catch 'exit
17030 (let ((a1 '(("h" . hour)
17031 ("d" . day)
17032 ("w" . week)
17033 ("m" . month)
17034 ("y" . year)))
17035 (shour (nth 2 (org-parse-time-string start)))
17036 dn dw sday cday n1 n2 n0
17037 d m y y1 y2 date1 date2 nmonths nm ny m2)
17039 (setq start (org-date-to-gregorian start)
17040 current (org-date-to-gregorian
17041 (if show-all
17042 current
17043 (time-to-days (current-time))))
17044 sday (calendar-absolute-from-gregorian start)
17045 cday (calendar-absolute-from-gregorian current))
17047 (if (<= cday sday) (throw 'exit sday))
17049 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17050 (setq dn (string-to-number (match-string 1 change))
17051 dw (cdr (assoc (match-string 2 change) a1)))
17052 (user-error "Invalid change specifier: %s" change))
17053 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17054 (cond
17055 ((eq dw 'hour)
17056 (let ((missing-hours
17057 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17058 dn)))
17059 (setq n1 (if (zerop missing-hours) cday
17060 (- cday (1+ (floor (/ missing-hours 24)))))
17061 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17062 ((eq dw 'day)
17063 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17064 n2 (+ n1 dn)))
17065 ((eq dw 'year)
17066 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17067 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17068 (setq date1 (list m d y1)
17069 n1 (calendar-absolute-from-gregorian date1)
17070 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17071 n2 (calendar-absolute-from-gregorian date2)))
17072 ((eq dw 'month)
17073 ;; approx number of month between the two dates
17074 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17075 ;; How often does dn fit in there?
17076 (setq d (nth 1 start) m (car start) y (nth 2 start)
17077 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17078 m (+ m nm)
17079 ny (floor (/ m 12))
17080 y (+ y ny)
17081 m (- m (* ny 12)))
17082 (while (> m 12) (setq m (- m 12) y (1+ y)))
17083 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17084 (setq m2 (+ m dn) y2 y)
17085 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17086 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17087 (while (<= n2 cday)
17088 (setq n1 n2 m m2 y y2)
17089 (setq m2 (+ m dn) y2 y)
17090 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17091 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17092 ;; Make sure n1 is the earlier date
17093 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17094 (if show-all
17095 (cond
17096 ((eq prefer 'past) (if (= cday n2) n2 n1))
17097 ((eq prefer 'future) (if (= cday n1) n1 n2))
17098 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17099 (cond
17100 ((eq prefer 'past) (if (= cday n2) n2 n1))
17101 ((eq prefer 'future) (if (= cday n1) n1 n2))
17102 (t (if (= cday n1) n1 n2)))))))
17104 (defun org-date-to-gregorian (date)
17105 "Turn any specification of DATE into a Gregorian date for the calendar."
17106 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17107 ((and (listp date) (= (length date) 3)) date)
17108 ((stringp date)
17109 (setq date (org-parse-time-string date))
17110 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17111 ((listp date)
17112 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17114 (defun org-parse-time-string (s &optional nodefault)
17115 "Parse the standard Org-mode time string.
17116 This should be a lot faster than the normal `parse-time-string'.
17117 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17118 hour and minute fields will be nil if not given."
17119 (cond ((string-match org-ts-regexp0 s)
17120 (list 0
17121 (if (or (match-beginning 8) (not nodefault))
17122 (string-to-number (or (match-string 8 s) "0")))
17123 (if (or (match-beginning 7) (not nodefault))
17124 (string-to-number (or (match-string 7 s) "0")))
17125 (string-to-number (match-string 4 s))
17126 (string-to-number (match-string 3 s))
17127 (string-to-number (match-string 2 s))
17128 nil nil nil))
17129 ((string-match "^<[^>]+>$" s)
17130 (decode-time (seconds-to-time (org-matcher-time s))))
17131 (t (error "Not a standard Org-mode time string: %s" s))))
17133 (defun org-timestamp-up (&optional arg)
17134 "Increase the date item at the cursor by one.
17135 If the cursor is on the year, change the year. If it is on the month,
17136 the day or the time, change that.
17137 With prefix ARG, change by that many units."
17138 (interactive "p")
17139 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17141 (defun org-timestamp-down (&optional arg)
17142 "Decrease the date item at the cursor by one.
17143 If the cursor is on the year, change the year. If it is on the month,
17144 the day or the time, change that.
17145 With prefix ARG, change by that many units."
17146 (interactive "p")
17147 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17149 (defun org-timestamp-up-day (&optional arg)
17150 "Increase the date in the time stamp by one day.
17151 With prefix ARG, change that many days."
17152 (interactive "p")
17153 (if (and (not (org-at-timestamp-p t))
17154 (org-at-heading-p))
17155 (org-todo 'up)
17156 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17158 (defun org-timestamp-down-day (&optional arg)
17159 "Decrease the date in the time stamp by one day.
17160 With prefix ARG, change that many days."
17161 (interactive "p")
17162 (if (and (not (org-at-timestamp-p t))
17163 (org-at-heading-p))
17164 (org-todo 'down)
17165 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17167 (defun org-at-timestamp-p (&optional inactive-ok)
17168 "Determine if the cursor is in or at a timestamp."
17169 (interactive)
17170 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17171 (pos (point))
17172 (ans (or (looking-at tsr)
17173 (save-excursion
17174 (skip-chars-backward "^[<\n\r\t")
17175 (if (> (point) (point-min)) (backward-char 1))
17176 (and (looking-at tsr)
17177 (> (- (match-end 0) pos) -1))))))
17178 (and ans
17179 (boundp 'org-ts-what)
17180 (setq org-ts-what
17181 (cond
17182 ((= pos (match-beginning 0)) 'bracket)
17183 ;; Point is considered to be "on the bracket" whether
17184 ;; it's really on it or right after it.
17185 ((= pos (1- (match-end 0))) 'bracket)
17186 ((= pos (match-end 0)) 'after)
17187 ((org-pos-in-match-range pos 2) 'year)
17188 ((org-pos-in-match-range pos 3) 'month)
17189 ((org-pos-in-match-range pos 7) 'hour)
17190 ((org-pos-in-match-range pos 8) 'minute)
17191 ((or (org-pos-in-match-range pos 4)
17192 (org-pos-in-match-range pos 5)) 'day)
17193 ((and (> pos (or (match-end 8) (match-end 5)))
17194 (< pos (match-end 0)))
17195 (- pos (or (match-end 8) (match-end 5))))
17196 (t 'day))))
17197 ans))
17199 (defun org-toggle-timestamp-type ()
17200 "Toggle the type (<active> or [inactive]) of a time stamp."
17201 (interactive)
17202 (when (org-at-timestamp-p t)
17203 (let ((beg (match-beginning 0)) (end (match-end 0))
17204 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17205 (save-excursion
17206 (goto-char beg)
17207 (while (re-search-forward "[][<>]" end t)
17208 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17209 t t)))
17210 (message "Timestamp is now %sactive"
17211 (if (equal (char-after beg) ?<) "" "in")))))
17213 (defun org-at-clock-log-p nil
17214 "Is the cursor on the clock log line?"
17215 (save-excursion
17216 (move-beginning-of-line 1)
17217 (looking-at "^[ \t]*CLOCK:")))
17219 (defvar org-clock-history) ; defined in org-clock.el
17220 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17221 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17222 "Change the date in the time stamp at point.
17223 The date will be changed by N times WHAT. WHAT can be `day', `month',
17224 `year', `minute', `second'. If WHAT is not given, the cursor position
17225 in the timestamp determines what will be changed.
17226 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17227 (let ((origin (point)) origin-cat
17228 with-hm inactive
17229 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17230 org-ts-what
17231 extra rem
17232 ts time time0 fixnext clrgx)
17233 (if (not (org-at-timestamp-p t))
17234 (user-error "Not at a timestamp"))
17235 (if (and (not what) (eq org-ts-what 'bracket))
17236 (org-toggle-timestamp-type)
17237 ;; Point isn't on brackets. Remember the part of the time-stamp
17238 ;; the point was in. Indeed, size of time-stamps may change,
17239 ;; but point must be kept in the same category nonetheless.
17240 (setq origin-cat org-ts-what)
17241 (if (and (not what) (not (eq org-ts-what 'day))
17242 org-display-custom-times
17243 (get-text-property (point) 'display)
17244 (not (get-text-property (1- (point)) 'display)))
17245 (setq org-ts-what 'day))
17246 (setq org-ts-what (or what org-ts-what)
17247 inactive (= (char-after (match-beginning 0)) ?\[)
17248 ts (match-string 0))
17249 (replace-match "")
17250 (when (string-match
17251 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17253 (setq extra (match-string 1 ts))
17254 (if suppress-tmp-delay
17255 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17256 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17257 (setq with-hm t))
17258 (setq time0 (org-parse-time-string ts))
17259 (when (and updown
17260 (eq org-ts-what 'minute)
17261 (not current-prefix-arg))
17262 ;; This looks like s-up and s-down. Change by one rounding step.
17263 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17264 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17265 (setcar (cdr time0) (+ (nth 1 time0)
17266 (if (> n 0) (- rem) (- dm rem))))))
17267 (setq time
17268 (encode-time (or (car time0) 0)
17269 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17270 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17271 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17272 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17273 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17274 (nthcdr 6 time0)))
17275 (when (and (member org-ts-what '(hour minute))
17276 extra
17277 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17278 (setq extra (org-modify-ts-extra
17279 extra
17280 (if (eq org-ts-what 'hour) 2 5)
17281 n dm)))
17282 (when (integerp org-ts-what)
17283 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17284 (if (eq what 'calendar)
17285 (let ((cal-date (org-get-date-from-calendar)))
17286 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17287 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17288 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17289 (setcar time0 (or (car time0) 0))
17290 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17291 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17292 (setq time (apply 'encode-time time0))))
17293 ;; Insert the new time-stamp, and ensure point stays in the same
17294 ;; category as before (i.e. not after the last position in that
17295 ;; category).
17296 (let ((pos (point)))
17297 ;; Stay before inserted string. `save-excursion' is of no use.
17298 (setq org-last-changed-timestamp
17299 (org-insert-time-stamp time with-hm inactive nil nil extra))
17300 (goto-char pos))
17301 (save-match-data
17302 (looking-at org-ts-regexp3)
17303 (goto-char (cond
17304 ;; `day' category ends before `hour' if any, or at
17305 ;; the end of the day name.
17306 ((eq origin-cat 'day)
17307 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17308 ((eq origin-cat 'hour) (min (match-end 7) origin))
17309 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17310 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17311 ;; `year' and `month' have both fixed size: point
17312 ;; couldn't have moved into another part.
17313 (t origin))))
17314 ;; Update clock if on a CLOCK line.
17315 (org-clock-update-time-maybe)
17316 ;; Maybe adjust the closest clock in `org-clock-history'
17317 (when org-clock-adjust-closest
17318 (if (not (and (org-at-clock-log-p)
17319 (< 1 (length (delq nil (mapcar 'marker-position
17320 org-clock-history))))))
17321 (message "No clock to adjust")
17322 (cond ((save-excursion ; fix previous clock?
17323 (re-search-backward org-ts-regexp0 nil t)
17324 (org-looking-back (concat org-clock-string " \\[")))
17325 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17326 ((save-excursion ; fix next clock?
17327 (re-search-backward org-ts-regexp0 nil t)
17328 (looking-at (concat org-ts-regexp0 "\\] =>")))
17329 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17330 (save-window-excursion
17331 ;; Find closest clock to point, adjust the previous/next one in history
17332 (let* ((p (save-excursion (org-back-to-heading t)))
17333 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17334 (clfixnth
17335 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17336 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17337 (if (not clfixpos)
17338 (message "No clock to adjust")
17339 (save-excursion
17340 (org-goto-marker-or-bmk clfixpos)
17341 (org-show-subtree)
17342 (when (re-search-forward clrgx nil t)
17343 (goto-char (match-beginning 1))
17344 (let (org-clock-adjust-closest)
17345 (org-timestamp-change n org-ts-what updown))
17346 (message "Clock adjusted in %s for heading: %s"
17347 (file-name-nondirectory (buffer-file-name))
17348 (org-get-heading t t)))))))))
17349 ;; Try to recenter the calendar window, if any.
17350 (if (and org-calendar-follow-timestamp-change
17351 (get-buffer-window "*Calendar*" t)
17352 (memq org-ts-what '(day month year)))
17353 (org-recenter-calendar (time-to-days time))))))
17355 (defun org-modify-ts-extra (s pos n dm)
17356 "Change the different parts of the lead-time and repeat fields in timestamp."
17357 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17358 ng h m new rem)
17359 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17360 (cond
17361 ((or (org-pos-in-match-range pos 2)
17362 (org-pos-in-match-range pos 3))
17363 (setq m (string-to-number (match-string 3 s))
17364 h (string-to-number (match-string 2 s)))
17365 (if (org-pos-in-match-range pos 2)
17366 (setq h (+ h n))
17367 (setq n (* dm (org-no-warnings (signum n))))
17368 (when (not (= 0 (setq rem (% m dm))))
17369 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17370 (setq m (+ m n)))
17371 (if (< m 0) (setq m (+ m 60) h (1- h)))
17372 (if (> m 59) (setq m (- m 60) h (1+ h)))
17373 (setq h (min 24 (max 0 h)))
17374 (setq ng 1 new (format "-%02d:%02d" h m)))
17375 ((org-pos-in-match-range pos 6)
17376 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17377 ((org-pos-in-match-range pos 5)
17378 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17380 ((org-pos-in-match-range pos 9)
17381 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17382 ((org-pos-in-match-range pos 8)
17383 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17385 (when ng
17386 (setq s (concat
17387 (substring s 0 (match-beginning ng))
17389 (substring s (match-end ng))))))
17392 (defun org-recenter-calendar (date)
17393 "If the calendar is visible, recenter it to DATE."
17394 (let ((cwin (get-buffer-window "*Calendar*" t)))
17395 (when cwin
17396 (let ((calendar-move-hook nil))
17397 (with-selected-window cwin
17398 (calendar-goto-date (if (listp date) date
17399 (calendar-gregorian-from-absolute date))))))))
17401 (defun org-goto-calendar (&optional arg)
17402 "Go to the Emacs calendar at the current date.
17403 If there is a time stamp in the current line, go to that date.
17404 A prefix ARG can be used to force the current date."
17405 (interactive "P")
17406 (let ((tsr org-ts-regexp) diff
17407 (calendar-move-hook nil)
17408 (calendar-view-holidays-initially-flag nil)
17409 (calendar-view-diary-initially-flag nil))
17410 (if (or (org-at-timestamp-p)
17411 (save-excursion
17412 (beginning-of-line 1)
17413 (looking-at (concat ".*" tsr))))
17414 (let ((d1 (time-to-days (current-time)))
17415 (d2 (time-to-days
17416 (org-time-string-to-time (match-string 1)))))
17417 (setq diff (- d2 d1))))
17418 (calendar)
17419 (calendar-goto-today)
17420 (if (and diff (not arg)) (calendar-forward-day diff))))
17422 (defun org-get-date-from-calendar ()
17423 "Return a list (month day year) of date at point in calendar."
17424 (with-current-buffer "*Calendar*"
17425 (save-match-data
17426 (calendar-cursor-to-date))))
17428 (defun org-date-from-calendar ()
17429 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17430 If there is already a time stamp at the cursor position, update it."
17431 (interactive)
17432 (if (org-at-timestamp-p t)
17433 (org-timestamp-change 0 'calendar)
17434 (let ((cal-date (org-get-date-from-calendar)))
17435 (org-insert-time-stamp
17436 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17438 (defcustom org-effort-durations
17439 `(("h" . 60)
17440 ("d" . ,(* 60 8))
17441 ("w" . ,(* 60 8 5))
17442 ("m" . ,(* 60 8 5 4))
17443 ("y" . ,(* 60 8 5 40)))
17444 "Conversion factor to minutes for an effort modifier.
17446 Each entry has the form (MODIFIER . MINUTES).
17448 In an effort string, a number followed by MODIFIER is multiplied
17449 by the specified number of MINUTES to obtain an effort in
17450 minutes.
17452 For example, if the value of this variable is ((\"hours\" . 60)), then an
17453 effort string \"2hours\" is equivalent to 120 minutes."
17454 :group 'org-agenda
17455 :version "24.1"
17456 :type '(alist :key-type (string :tag "Modifier")
17457 :value-type (number :tag "Minutes")))
17459 (defun org-minutes-to-clocksum-string (m)
17460 "Format number of minutes as a clocksum string.
17461 The format is determined by `org-time-clocksum-format',
17462 `org-time-clocksum-use-fractional' and
17463 `org-time-clocksum-fractional-format' and
17464 `org-time-clocksum-use-effort-durations'."
17465 (let ((clocksum "")
17466 (m (round m)) ; Don't allow fractions of minutes
17467 h d w mo y fmt n)
17468 (setq h (if org-time-clocksum-use-effort-durations
17469 (cdr (assoc "h" org-effort-durations)) 60)
17470 d (if org-time-clocksum-use-effort-durations
17471 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17472 w (if org-time-clocksum-use-effort-durations
17473 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17474 mo (if org-time-clocksum-use-effort-durations
17475 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17476 y (if org-time-clocksum-use-effort-durations
17477 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17478 ;; fractional format
17479 (if org-time-clocksum-use-fractional
17480 (cond
17481 ;; single format string
17482 ((stringp org-time-clocksum-fractional-format)
17483 (format org-time-clocksum-fractional-format (/ m (float h))))
17484 ;; choice of fractional formats for different time units
17485 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17486 (> (/ (truncate m) (* y d h)) 0))
17487 (format fmt (/ m (* y d (float h)))))
17488 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17489 (> (/ (truncate m) (* mo d h)) 0))
17490 (format fmt (/ m (* mo d (float h)))))
17491 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17492 (> (/ (truncate m) (* w d h)) 0))
17493 (format fmt (/ m (* w d (float h)))))
17494 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17495 (> (/ (truncate m) (* d h)) 0))
17496 (format fmt (/ m (* d (float h)))))
17497 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17498 (> (/ (truncate m) h) 0))
17499 (format fmt (/ m (float h))))
17500 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17501 (format fmt m))
17502 ;; fall back to smallest time unit with a format
17503 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17504 (format fmt (/ m (float h))))
17505 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17506 (format fmt (/ m (* d (float h)))))
17507 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17508 (format fmt (/ m (* w d (float h)))))
17509 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17510 (format fmt (/ m (* mo d (float h)))))
17511 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17512 (format fmt (/ m (* y d (float h))))))
17513 ;; standard (non-fractional) format, with single format string
17514 (if (stringp org-time-clocksum-format)
17515 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17516 ;; separate formats components
17517 (and (setq fmt (plist-get org-time-clocksum-format :years))
17518 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17519 (plist-get org-time-clocksum-format :require-years))
17520 (setq clocksum (concat clocksum (format fmt n))
17521 m (- m (* n y d h))))
17522 (and (setq fmt (plist-get org-time-clocksum-format :months))
17523 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17524 (plist-get org-time-clocksum-format :require-months))
17525 (setq clocksum (concat clocksum (format fmt n))
17526 m (- m (* n mo d h))))
17527 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17528 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17529 (plist-get org-time-clocksum-format :require-weeks))
17530 (setq clocksum (concat clocksum (format fmt n))
17531 m (- m (* n w d h))))
17532 (and (setq fmt (plist-get org-time-clocksum-format :days))
17533 (or (> (setq n (/ (truncate m) (* d h))) 0)
17534 (plist-get org-time-clocksum-format :require-days))
17535 (setq clocksum (concat clocksum (format fmt n))
17536 m (- m (* n d h))))
17537 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17538 (or (> (setq n (/ (truncate m) h)) 0)
17539 (plist-get org-time-clocksum-format :require-hours))
17540 (setq clocksum (concat clocksum (format fmt n))
17541 m (- m (* n h))))
17542 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17543 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17544 (setq clocksum (concat clocksum (format fmt m))))
17545 ;; return formatted time duration
17546 clocksum))))
17548 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17549 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17550 "Org mode version 8.0")
17552 (defun org-hours-to-clocksum-string (n)
17553 (org-minutes-to-clocksum-string (* n 60)))
17555 (defun org-hh:mm-string-to-minutes (s)
17556 "Convert a string H:MM to a number of minutes.
17557 If the string is just a number, interpret it as minutes.
17558 In fact, the first hh:mm or number in the string will be taken,
17559 there can be extra stuff in the string.
17560 If no number is found, the return value is 0."
17561 (cond
17562 ((integerp s) s)
17563 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17564 (+ (* (string-to-number (match-string 1 s)) 60)
17565 (string-to-number (match-string 2 s))))
17566 ((string-match "\\([0-9]+\\)" s)
17567 (string-to-number (match-string 1 s)))
17568 (t 0)))
17570 (defcustom org-image-actual-width t
17571 "Should we use the actual width of images when inlining them?
17573 When set to `t', always use the image width.
17575 When set to a number, use imagemagick (when available) to set
17576 the image's width to this value.
17578 When set to a number in a list, try to get the width from any
17579 #+ATTR.* keyword if it matches a width specification like
17581 #+ATTR_HTML: :width 300px
17583 and fall back on that number if none is found.
17585 When set to nil, try to get the width from an #+ATTR.* keyword
17586 and fall back on the original width if none is found.
17588 This requires Emacs >= 24.1, build with imagemagick support."
17589 :group 'org-appearance
17590 :version "24.4"
17591 :package-version '(Org . "8.0")
17592 :type '(choice
17593 (const :tag "Use the image width" t)
17594 (integer :tag "Use a number of pixels")
17595 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17596 (const :tag "Use #+ATTR* or don't resize" nil)))
17598 (defcustom org-agenda-inhibit-startup nil
17599 "Inhibit startup when preparing agenda buffers.
17600 When this variable is `t' (the default), the initialization of
17601 the Org agenda buffers is inhibited: e.g. the visibility state
17602 is not set, the tables are not re-aligned, etc."
17603 :type 'boolean
17604 :version "24.3"
17605 :group 'org-agenda)
17607 (defun org-duration-string-to-minutes (s &optional output-to-string)
17608 "Convert a duration string S to minutes.
17610 A bare number is interpreted as minutes, modifiers can be set by
17611 customizing `org-effort-durations' (which see).
17613 Entries containing a colon are interpreted as H:MM by
17614 `org-hh:mm-string-to-minutes'."
17615 (let ((result 0)
17616 (re (concat "\\([0-9.]+\\) *\\("
17617 (regexp-opt (mapcar 'car org-effort-durations))
17618 "\\)")))
17619 (while (string-match re s)
17620 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17621 (string-to-number (match-string 1 s))))
17622 (setq s (replace-match "" nil t s)))
17623 (setq result (floor result))
17624 (incf result (org-hh:mm-string-to-minutes s))
17625 (if output-to-string (number-to-string result) result)))
17627 ;;;; Files
17629 (defun org-save-all-org-buffers ()
17630 "Save all Org-mode buffers without user confirmation."
17631 (interactive)
17632 (message "Saving all Org-mode buffers...")
17633 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17634 (when (featurep 'org-id) (org-id-locations-save))
17635 (message "Saving all Org-mode buffers... done"))
17637 (defun org-revert-all-org-buffers ()
17638 "Revert all Org-mode buffers.
17639 Prompt for confirmation when there are unsaved changes.
17640 Be sure you know what you are doing before letting this function
17641 overwrite your changes.
17643 This function is useful in a setup where one tracks org files
17644 with a version control system, to revert on one machine after pulling
17645 changes from another. I believe the procedure must be like this:
17647 1. M-x org-save-all-org-buffers
17648 2. Pull changes from the other machine, resolve conflicts
17649 3. M-x org-revert-all-org-buffers"
17650 (interactive)
17651 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17652 (user-error "Abort"))
17653 (save-excursion
17654 (save-window-excursion
17655 (mapc
17656 (lambda (b)
17657 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17658 (with-current-buffer b buffer-file-name))
17659 (org-pop-to-buffer-same-window b)
17660 (revert-buffer t 'no-confirm)))
17661 (buffer-list))
17662 (when (and (featurep 'org-id) org-id-track-globally)
17663 (org-id-locations-load)))))
17665 ;;;; Agenda files
17667 ;;;###autoload
17668 (defun org-switchb (&optional arg)
17669 "Switch between Org buffers.
17670 With one prefix argument, restrict available buffers to files.
17671 With two prefix arguments, restrict available buffers to agenda files.
17673 Defaults to `iswitchb' for buffer name completion.
17674 Set `org-completion-use-ido' to make it use ido instead."
17675 (interactive "P")
17676 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17677 ((equal arg '(16)) (org-buffer-list 'agenda))
17678 (t (org-buffer-list))))
17679 (org-completion-use-iswitchb org-completion-use-iswitchb)
17680 (org-completion-use-ido org-completion-use-ido))
17681 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17682 (setq org-completion-use-iswitchb t))
17683 (org-pop-to-buffer-same-window
17684 (org-icompleting-read "Org buffer: "
17685 (mapcar 'list (mapcar 'buffer-name blist))
17686 nil t))))
17688 ;;; Define some older names previously used for this functionality
17689 ;;;###autoload
17690 (defalias 'org-ido-switchb 'org-switchb)
17691 ;;;###autoload
17692 (defalias 'org-iswitchb 'org-switchb)
17694 (defun org-buffer-list (&optional predicate exclude-tmp)
17695 "Return a list of Org buffers.
17696 PREDICATE can be `export', `files' or `agenda'.
17698 export restrict the list to Export buffers.
17699 files restrict the list to buffers visiting Org files.
17700 agenda restrict the list to buffers visiting agenda files.
17702 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17703 (let* ((bfn nil)
17704 (agenda-files (and (eq predicate 'agenda)
17705 (mapcar 'file-truename (org-agenda-files t))))
17706 (filter
17707 (cond
17708 ((eq predicate 'files)
17709 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17710 ((eq predicate 'export)
17711 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17712 ((eq predicate 'agenda)
17713 (lambda (b)
17714 (with-current-buffer b
17715 (and (derived-mode-p 'org-mode)
17716 (setq bfn (buffer-file-name b))
17717 (member (file-truename bfn) agenda-files)))))
17718 (t (lambda (b) (with-current-buffer b
17719 (or (derived-mode-p 'org-mode)
17720 (string-match "\*Org .*Export"
17721 (buffer-name b)))))))))
17722 (delq nil
17723 (mapcar
17724 (lambda(b)
17725 (if (and (funcall filter b)
17726 (or (not exclude-tmp)
17727 (not (string-match "tmp" (buffer-name b)))))
17729 nil))
17730 (buffer-list)))))
17732 (defun org-agenda-files (&optional unrestricted archives)
17733 "Get the list of agenda files.
17734 Optional UNRESTRICTED means return the full list even if a restriction
17735 is currently in place.
17736 When ARCHIVES is t, include all archive files that are really being
17737 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17738 `org-agenda-archives-mode' is t."
17739 (let ((files
17740 (cond
17741 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17742 ((stringp org-agenda-files) (org-read-agenda-file-list))
17743 ((listp org-agenda-files) org-agenda-files)
17744 (t (error "Invalid value of `org-agenda-files'")))))
17745 (setq files (apply 'append
17746 (mapcar (lambda (f)
17747 (if (file-directory-p f)
17748 (directory-files
17749 f t org-agenda-file-regexp)
17750 (list f)))
17751 files)))
17752 (when org-agenda-skip-unavailable-files
17753 (setq files (delq nil
17754 (mapcar (function
17755 (lambda (file)
17756 (and (file-readable-p file) file)))
17757 files))))
17758 (when (or (eq archives t)
17759 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17760 (setq files (org-add-archive-files files)))
17761 files))
17763 (defun org-agenda-file-p (&optional file)
17764 "Return non-nil, if FILE is an agenda file.
17765 If FILE is omitted, use the file associated with the current
17766 buffer."
17767 (member (or file (buffer-file-name))
17768 (org-agenda-files t)))
17770 (defun org-edit-agenda-file-list ()
17771 "Edit the list of agenda files.
17772 Depending on setup, this either uses customize to edit the variable
17773 `org-agenda-files', or it visits the file that is holding the list. In the
17774 latter case, the buffer is set up in a way that saving it automatically kills
17775 the buffer and restores the previous window configuration."
17776 (interactive)
17777 (if (stringp org-agenda-files)
17778 (let ((cw (current-window-configuration)))
17779 (find-file org-agenda-files)
17780 (org-set-local 'org-window-configuration cw)
17781 (org-add-hook 'after-save-hook
17782 (lambda ()
17783 (set-window-configuration
17784 (prog1 org-window-configuration
17785 (kill-buffer (current-buffer))))
17786 (org-install-agenda-files-menu)
17787 (message "New agenda file list installed"))
17788 nil 'local)
17789 (message "%s" (substitute-command-keys
17790 "Edit list and finish with \\[save-buffer]")))
17791 (customize-variable 'org-agenda-files)))
17793 (defun org-store-new-agenda-file-list (list)
17794 "Set new value for the agenda file list and save it correctly."
17795 (if (stringp org-agenda-files)
17796 (let ((fe (org-read-agenda-file-list t)) b u)
17797 (while (setq b (find-buffer-visiting org-agenda-files))
17798 (kill-buffer b))
17799 (with-temp-file org-agenda-files
17800 (insert
17801 (mapconcat
17802 (lambda (f) ;; Keep un-expanded entries.
17803 (if (setq u (assoc f fe))
17804 (cdr u)
17806 list "\n")
17807 "\n")))
17808 (let ((org-mode-hook nil) (org-inhibit-startup t)
17809 (org-insert-mode-line-in-empty-file nil))
17810 (setq org-agenda-files list)
17811 (customize-save-variable 'org-agenda-files org-agenda-files))))
17813 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17814 "Read the list of agenda files from a file.
17815 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17816 filenames, used by `org-store-new-agenda-file-list' to write back
17817 un-expanded file names."
17818 (when (file-directory-p org-agenda-files)
17819 (error "`org-agenda-files' cannot be a single directory"))
17820 (when (stringp org-agenda-files)
17821 (with-temp-buffer
17822 (insert-file-contents org-agenda-files)
17823 (mapcar
17824 (lambda (f)
17825 (let ((e (expand-file-name (substitute-in-file-name f)
17826 org-directory)))
17827 (if pair-with-expansion
17828 (cons e f)
17829 e)))
17830 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17832 ;;;###autoload
17833 (defun org-cycle-agenda-files ()
17834 "Cycle through the files in `org-agenda-files'.
17835 If the current buffer visits an agenda file, find the next one in the list.
17836 If the current buffer does not, find the first agenda file."
17837 (interactive)
17838 (let* ((fs (org-agenda-files t))
17839 (files (append fs (list (car fs))))
17840 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17841 file)
17842 (unless files (user-error "No agenda files"))
17843 (catch 'exit
17844 (while (setq file (pop files))
17845 (if (equal (file-truename file) tcf)
17846 (when (car files)
17847 (find-file (car files))
17848 (throw 'exit t))))
17849 (find-file (car fs)))
17850 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17852 (defun org-agenda-file-to-front (&optional to-end)
17853 "Move/add the current file to the top of the agenda file list.
17854 If the file is not present in the list, it is added to the front. If it is
17855 present, it is moved there. With optional argument TO-END, add/move to the
17856 end of the list."
17857 (interactive "P")
17858 (let ((org-agenda-skip-unavailable-files nil)
17859 (file-alist (mapcar (lambda (x)
17860 (cons (file-truename x) x))
17861 (org-agenda-files t)))
17862 (ctf (file-truename
17863 (or buffer-file-name
17864 (user-error "Please save the current buffer to a file"))))
17865 x had)
17866 (setq x (assoc ctf file-alist) had x)
17868 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17869 (if to-end
17870 (setq file-alist (append (delq x file-alist) (list x)))
17871 (setq file-alist (cons x (delq x file-alist))))
17872 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17873 (org-install-agenda-files-menu)
17874 (message "File %s to %s of agenda file list"
17875 (if had "moved" "added") (if to-end "end" "front"))))
17877 (defun org-remove-file (&optional file)
17878 "Remove current file from the list of files in variable `org-agenda-files'.
17879 These are the files which are being checked for agenda entries.
17880 Optional argument FILE means use this file instead of the current."
17881 (interactive)
17882 (let* ((org-agenda-skip-unavailable-files nil)
17883 (file (or file buffer-file-name
17884 (user-error "Current buffer does not visit a file")))
17885 (true-file (file-truename file))
17886 (afile (abbreviate-file-name file))
17887 (files (delq nil (mapcar
17888 (lambda (x)
17889 (if (equal true-file
17890 (file-truename x))
17891 nil x))
17892 (org-agenda-files t)))))
17893 (if (not (= (length files) (length (org-agenda-files t))))
17894 (progn
17895 (org-store-new-agenda-file-list files)
17896 (org-install-agenda-files-menu)
17897 (message "Removed file: %s" afile))
17898 (message "File was not in list: %s (not removed)" afile))))
17900 (defun org-file-menu-entry (file)
17901 (vector file (list 'find-file file) t))
17903 (defun org-check-agenda-file (file)
17904 "Make sure FILE exists. If not, ask user what to do."
17905 (when (not (file-exists-p file))
17906 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17907 (abbreviate-file-name file))
17908 (let ((r (downcase (read-char-exclusive))))
17909 (cond
17910 ((equal r ?r)
17911 (org-remove-file file)
17912 (throw 'nextfile t))
17913 (t (error "Abort"))))))
17915 (defun org-get-agenda-file-buffer (file)
17916 "Get a buffer visiting FILE. If the buffer needs to be created, add
17917 it to the list of buffers which might be released later."
17918 (let ((buf (org-find-base-buffer-visiting file)))
17919 (if buf
17920 buf ; just return it
17921 ;; Make a new buffer and remember it
17922 (setq buf (find-file-noselect file))
17923 (if buf (push buf org-agenda-new-buffers))
17924 buf)))
17926 (defun org-release-buffers (blist)
17927 "Release all buffers in list, asking the user for confirmation when needed.
17928 When a buffer is unmodified, it is just killed. When modified, it is saved
17929 \(if the user agrees) and then killed."
17930 (let (buf file)
17931 (while (setq buf (pop blist))
17932 (setq file (buffer-file-name buf))
17933 (when (and (buffer-modified-p buf)
17934 file
17935 (y-or-n-p (format "Save file %s? " file)))
17936 (with-current-buffer buf (save-buffer)))
17937 (kill-buffer buf))))
17939 (defun org-agenda-prepare-buffers (files)
17940 "Create buffers for all agenda files, protect archived trees and comments."
17941 (interactive)
17942 (let ((pa '(:org-archived t))
17943 (pc '(:org-comment t))
17944 (pall '(:org-archived t :org-comment t))
17945 (inhibit-read-only t)
17946 (org-inhibit-startup org-agenda-inhibit-startup)
17947 (rea (concat ":" org-archive-tag ":"))
17948 file re)
17949 (setq org-tag-alist-for-agenda nil
17950 org-tag-groups-alist-for-agenda nil)
17951 (save-excursion
17952 (save-restriction
17953 (while (setq file (pop files))
17954 (catch 'nextfile
17955 (if (bufferp file)
17956 (set-buffer file)
17957 (org-check-agenda-file file)
17958 (set-buffer (org-get-agenda-file-buffer file)))
17959 (widen)
17960 (org-set-regexps-and-options-for-tags)
17961 (org-refresh-category-properties)
17962 (org-refresh-properties org-effort-property 'org-effort)
17963 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17964 (setq org-todo-keywords-for-agenda
17965 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17966 (setq org-done-keywords-for-agenda
17967 (append org-done-keywords-for-agenda org-done-keywords))
17968 (setq org-todo-keyword-alist-for-agenda
17969 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17970 (setq org-drawers-for-agenda
17971 (append org-drawers-for-agenda org-drawers))
17972 (unless (equal org-tag-alist-for-agenda org-tag-alist)
17973 (setq org-tag-alist-for-agenda
17974 (append org-tag-alist-for-agenda org-tag-alist)))
17975 (if org-group-tags
17976 (setq org-tag-groups-alist-for-agenda
17977 (org-uniquify-alist
17978 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
17979 (org-with-silent-modifications
17980 (save-excursion
17981 (remove-text-properties (point-min) (point-max) pall)
17982 (when org-agenda-skip-archived-trees
17983 (goto-char (point-min))
17984 (while (re-search-forward rea nil t)
17985 (if (org-at-heading-p t)
17986 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17987 (goto-char (point-min))
17988 (setq re (format org-heading-keyword-regexp-format
17989 org-comment-string))
17990 (while (re-search-forward re nil t)
17991 (add-text-properties
17992 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17993 (setq org-todo-keywords-for-agenda
17994 (org-uniquify org-todo-keywords-for-agenda))
17995 (setq org-todo-keyword-alist-for-agenda
17996 (org-uniquify org-todo-keyword-alist-for-agenda))))
17999 ;;;; CDLaTeX minor mode
18001 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18002 "Keymap for the minor `org-cdlatex-mode'.")
18004 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18005 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18006 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18007 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18008 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18010 (defvar org-cdlatex-texmathp-advice-is-done nil
18011 "Flag remembering if we have applied the advice to texmathp already.")
18013 (define-minor-mode org-cdlatex-mode
18014 "Toggle the minor `org-cdlatex-mode'.
18015 This mode supports entering LaTeX environment and math in LaTeX fragments
18016 in Org-mode.
18017 \\{org-cdlatex-mode-map}"
18018 nil " OCDL" nil
18019 (when org-cdlatex-mode
18020 (require 'cdlatex)
18021 (run-hooks 'cdlatex-mode-hook)
18022 (cdlatex-compute-tables))
18023 (unless org-cdlatex-texmathp-advice-is-done
18024 (setq org-cdlatex-texmathp-advice-is-done t)
18025 (defadvice texmathp (around org-math-always-on activate)
18026 "Always return t in org-mode buffers.
18027 This is because we want to insert math symbols without dollars even outside
18028 the LaTeX math segments. If Orgmode thinks that point is actually inside
18029 an embedded LaTeX fragment, let texmathp do its job.
18030 \\[org-cdlatex-mode-map]"
18031 (interactive)
18032 (let (p)
18033 (cond
18034 ((not (derived-mode-p 'org-mode)) ad-do-it)
18035 ((eq this-command 'cdlatex-math-symbol)
18036 (setq ad-return-value t
18037 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18039 (let ((p (org-inside-LaTeX-fragment-p)))
18040 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18041 (setq ad-return-value t
18042 texmathp-why '("Org-mode embedded math" . 0))
18043 (if p ad-do-it)))))))))
18045 (defun turn-on-org-cdlatex ()
18046 "Unconditionally turn on `org-cdlatex-mode'."
18047 (org-cdlatex-mode 1))
18049 (defun org-try-cdlatex-tab ()
18050 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18051 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18052 - inside a LaTeX fragment, or
18053 - after the first word in a line, where an abbreviation expansion could
18054 insert a LaTeX environment."
18055 (when org-cdlatex-mode
18056 (cond
18057 ;; Before any word on the line: No expansion possible.
18058 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18059 ;; Just after first word on the line: Expand it. Make sure it
18060 ;; cannot happen on headlines, though.
18061 ((save-excursion
18062 (skip-chars-backward "a-zA-Z0-9*")
18063 (skip-chars-backward " \t")
18064 (and (bolp) (not (org-at-heading-p))))
18065 (cdlatex-tab) t)
18066 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18068 (defun org-cdlatex-underscore-caret (&optional arg)
18069 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18070 Revert to the normal definition outside of these fragments."
18071 (interactive "P")
18072 (if (org-inside-LaTeX-fragment-p)
18073 (call-interactively 'cdlatex-sub-superscript)
18074 (let (org-cdlatex-mode)
18075 (call-interactively (key-binding (vector last-input-event))))))
18077 (defun org-cdlatex-math-modify (&optional arg)
18078 "Execute `cdlatex-math-modify' in LaTeX fragments.
18079 Revert to the normal definition outside of these fragments."
18080 (interactive "P")
18081 (if (org-inside-LaTeX-fragment-p)
18082 (call-interactively 'cdlatex-math-modify)
18083 (let (org-cdlatex-mode)
18084 (call-interactively (key-binding (vector last-input-event))))))
18088 ;;;; LaTeX fragments
18090 (defvar org-latex-regexps
18091 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18092 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18093 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18094 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18095 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18096 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18097 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18098 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18099 "Regular expressions for matching embedded LaTeX.")
18101 (defun org-inside-LaTeX-fragment-p ()
18102 "Test if point is inside a LaTeX fragment.
18103 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18104 sequence appearing also before point.
18105 Even though the matchers for math are configurable, this function assumes
18106 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18107 delimiters are skipped when they have been removed by customization.
18108 The return value is nil, or a cons cell with the delimiter and the
18109 position of this delimiter.
18111 This function does a reasonably good job, but can locally be fooled by
18112 for example currency specifications. For example it will assume being in
18113 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18114 fragments that are properly closed, but during editing, we have to live
18115 with the uncertainty caused by missing closing delimiters. This function
18116 looks only before point, not after."
18117 (catch 'exit
18118 (let ((pos (point))
18119 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18120 (lim (progn
18121 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18122 (point)))
18123 dd-on str (start 0) m re)
18124 (goto-char pos)
18125 (when dodollar
18126 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18127 re (nth 1 (assoc "$" org-latex-regexps)))
18128 (while (string-match re str start)
18129 (cond
18130 ((= (match-end 0) (length str))
18131 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18132 ((= (match-end 0) (- (length str) 5))
18133 (throw 'exit nil))
18134 (t (setq start (match-end 0))))))
18135 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18136 (goto-char pos)
18137 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18138 (and (match-beginning 2) (throw 'exit nil))
18139 ;; count $$
18140 (while (re-search-backward "\\$\\$" lim t)
18141 (setq dd-on (not dd-on)))
18142 (goto-char pos)
18143 (if dd-on (cons "$$" m))))))
18145 (defun org-inside-latex-macro-p ()
18146 "Is point inside a LaTeX macro or its arguments?"
18147 (save-match-data
18148 (org-in-regexp
18149 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18151 (defvar org-latex-fragment-image-overlays nil
18152 "List of overlays carrying the images of latex fragments.")
18153 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18155 (defun org-remove-latex-fragment-image-overlays ()
18156 "Remove all overlays with LaTeX fragment images in current buffer."
18157 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18158 (setq org-latex-fragment-image-overlays nil))
18160 (defun org-preview-latex-fragment (&optional subtree)
18161 "Preview the LaTeX fragment at point, or all locally or globally.
18162 If the cursor is in a LaTeX fragment, create the image and overlay
18163 it over the source code. If there is no fragment at point, display
18164 all fragments in the current text, from one headline to the next. With
18165 prefix SUBTREE, display all fragments in the current subtree. With a
18166 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18167 the cursor is before the first headline,
18168 display all fragments in the buffer.
18169 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18170 (interactive "P")
18171 (unless buffer-file-name
18172 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18173 (org-remove-latex-fragment-image-overlays)
18174 (save-excursion
18175 (save-restriction
18176 (let (beg end at msg)
18177 (cond
18178 ((or (equal subtree '(16))
18179 (not (save-excursion
18180 (re-search-backward org-outline-regexp-bol nil t))))
18181 (setq beg (point-min) end (point-max)
18182 msg "Creating images for buffer...%s"))
18183 ((equal subtree '(4))
18184 (org-back-to-heading)
18185 (setq beg (point) end (org-end-of-subtree t)
18186 msg "Creating images for subtree...%s"))
18188 (if (setq at (org-inside-LaTeX-fragment-p))
18189 (goto-char (max (point-min) (- (cdr at) 2)))
18190 (org-back-to-heading))
18191 (setq beg (point) end (progn (outline-next-heading) (point))
18192 msg (if at "Creating image...%s"
18193 "Creating images for entry...%s"))))
18194 (message msg "")
18195 (narrow-to-region beg end)
18196 (goto-char beg)
18197 (org-format-latex
18198 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18199 (file-name-nondirectory
18200 buffer-file-name)))
18201 default-directory 'overlays msg at 'forbuffer
18202 org-latex-create-formula-image-program)
18203 (message msg "done. Use `C-c C-c' to remove images.")))))
18205 (defun org-format-latex (prefix &optional dir overlays msg at
18206 forbuffer processing-type)
18207 "Replace LaTeX fragments with links to an image, and produce images.
18208 Some of the options can be changed using the variable
18209 `org-format-latex-options'."
18210 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18211 (let* ((prefixnodir (file-name-nondirectory prefix))
18212 (absprefix (expand-file-name prefix dir))
18213 (todir (file-name-directory absprefix))
18214 (opt org-format-latex-options)
18215 (optnew org-format-latex-options)
18216 (matchers (plist-get opt :matchers))
18217 (re-list org-latex-regexps)
18218 (cnt 0) txt hash link beg end re e checkdir
18219 string
18220 m n block-type block linkfile movefile ov)
18221 ;; Check the different regular expressions
18222 (while (setq e (pop re-list))
18223 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18224 block (if block-type "\n\n" ""))
18225 (when (member m matchers)
18226 (goto-char (point-min))
18227 (while (re-search-forward re nil t)
18228 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18229 (or (not overlays)
18230 (not (eq (get-char-property (match-beginning n)
18231 'org-overlay-type)
18232 'org-latex-overlay))))
18233 (cond
18234 ((eq processing-type 'verbatim))
18235 ((eq processing-type 'mathjax)
18236 ;; Prepare for MathJax processing.
18237 (setq string (match-string n))
18238 (when (member m '("$" "$1"))
18239 (save-excursion
18240 (delete-region (match-beginning n) (match-end n))
18241 (goto-char (match-beginning n))
18242 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18243 ((or (eq processing-type 'dvipng)
18244 (eq processing-type 'imagemagick))
18245 ;; Process to an image.
18246 (setq txt (match-string n)
18247 beg (match-beginning n) end (match-end n)
18248 cnt (1+ cnt))
18249 (let ((face (face-at-point))
18250 (fg (plist-get opt :foreground))
18251 (bg (plist-get opt :background))
18252 ;; Ensure full list is printed.
18253 print-length print-level)
18254 (when forbuffer
18255 ;; Get the colors from the face at point.
18256 (goto-char beg)
18257 (when (eq fg 'auto)
18258 (setq fg (face-attribute face :foreground nil 'default)))
18259 (when (eq bg 'auto)
18260 (setq bg (face-attribute face :background nil 'default)))
18261 (setq optnew (copy-sequence opt))
18262 (plist-put optnew :foreground fg)
18263 (plist-put optnew :background bg))
18264 (setq hash (sha1 (prin1-to-string
18265 (list org-format-latex-header
18266 org-latex-default-packages-alist
18267 org-latex-packages-alist
18268 org-format-latex-options
18269 forbuffer txt fg bg)))
18270 linkfile (format "%s_%s.png" prefix hash)
18271 movefile (format "%s_%s.png" absprefix hash)))
18272 (setq link (concat block "[[file:" linkfile "]]" block))
18273 (if msg (message msg cnt))
18274 (goto-char beg)
18275 (unless checkdir ; Ensure the directory exists.
18276 (setq checkdir t)
18277 (or (file-directory-p todir) (make-directory todir t)))
18278 (unless (file-exists-p movefile)
18279 (org-create-formula-image
18280 txt movefile optnew forbuffer processing-type))
18281 (if overlays
18282 (progn
18283 (mapc (lambda (o)
18284 (if (eq (overlay-get o 'org-overlay-type)
18285 'org-latex-overlay)
18286 (delete-overlay o)))
18287 (overlays-in beg end))
18288 (setq ov (make-overlay beg end))
18289 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18290 (if (featurep 'xemacs)
18291 (progn
18292 (overlay-put ov 'invisible t)
18293 (overlay-put
18294 ov 'end-glyph
18295 (make-glyph (vector 'png :file movefile))))
18296 (overlay-put
18297 ov 'display
18298 (list 'image :type 'png :file movefile :ascent 'center)))
18299 (push ov org-latex-fragment-image-overlays)
18300 (goto-char end))
18301 (delete-region beg end)
18302 (insert (org-add-props link
18303 (list 'org-latex-src
18304 (replace-regexp-in-string
18305 "\"" "" txt)
18306 'org-latex-src-embed-type
18307 (if block-type 'paragraph 'character))))))
18308 ((eq processing-type 'mathml)
18309 ;; Process to MathML
18310 (unless (save-match-data (org-format-latex-mathml-available-p))
18311 (user-error "LaTeX to MathML converter not configured"))
18312 (setq txt (match-string n)
18313 beg (match-beginning n) end (match-end n)
18314 cnt (1+ cnt))
18315 (if msg (message msg cnt))
18316 (goto-char beg)
18317 (delete-region beg end)
18318 (insert (org-format-latex-as-mathml
18319 txt block-type prefix dir)))
18321 (error "Unknown conversion type %s for LaTeX fragments"
18322 processing-type)))))))))
18324 (defun org-create-math-formula (latex-frag &optional mathml-file)
18325 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18326 Use `org-latex-to-mathml-convert-command'. If the conversion is
18327 sucessful, return the portion between \"<math...> </math>\"
18328 elements otherwise return nil. When MATHML-FILE is specified,
18329 write the results in to that file. When invoked as an
18330 interactive command, prompt for LATEX-FRAG, with initial value
18331 set to the current active region and echo the results for user
18332 inspection."
18333 (interactive (list (let ((frag (when (org-region-active-p)
18334 (buffer-substring-no-properties
18335 (region-beginning) (region-end)))))
18336 (read-string "LaTeX Fragment: " frag nil frag))))
18337 (unless latex-frag (error "Invalid LaTeX fragment"))
18338 (let* ((tmp-in-file (file-relative-name
18339 (make-temp-name (expand-file-name "ltxmathml-in"))))
18340 (ignore (write-region latex-frag nil tmp-in-file))
18341 (tmp-out-file (file-relative-name
18342 (make-temp-name (expand-file-name "ltxmathml-out"))))
18343 (cmd (format-spec
18344 org-latex-to-mathml-convert-command
18345 `((?j . ,(shell-quote-argument
18346 (expand-file-name org-latex-to-mathml-jar-file)))
18347 (?I . ,(shell-quote-argument tmp-in-file))
18348 (?o . ,(shell-quote-argument tmp-out-file)))))
18349 mathml shell-command-output)
18350 (when (org-called-interactively-p 'any)
18351 (unless (org-format-latex-mathml-available-p)
18352 (user-error "LaTeX to MathML converter not configured")))
18353 (message "Running %s" cmd)
18354 (setq shell-command-output (shell-command-to-string cmd))
18355 (setq mathml
18356 (when (file-readable-p tmp-out-file)
18357 (with-current-buffer (find-file-noselect tmp-out-file t)
18358 (goto-char (point-min))
18359 (when (re-search-forward
18360 (concat
18361 (regexp-quote
18362 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18363 "\\(.\\|\n\\)*"
18364 (regexp-quote "</math>")) nil t)
18365 (prog1 (match-string 0) (kill-buffer))))))
18366 (cond
18367 (mathml
18368 (setq mathml
18369 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18370 (when mathml-file
18371 (write-region mathml nil mathml-file))
18372 (when (org-called-interactively-p 'any)
18373 (message mathml)))
18374 ((message "LaTeX to MathML conversion failed")
18375 (message shell-command-output)))
18376 (delete-file tmp-in-file)
18377 (when (file-exists-p tmp-out-file)
18378 (delete-file tmp-out-file))
18379 mathml))
18381 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18382 prefix &optional dir)
18383 "Use `org-create-math-formula' but check local cache first."
18384 (let* ((absprefix (expand-file-name prefix dir))
18385 (print-length nil) (print-level nil)
18386 (formula-id (concat
18387 "formula-"
18388 (sha1
18389 (prin1-to-string
18390 (list latex-frag
18391 org-latex-to-mathml-convert-command)))))
18392 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18393 (formula-cache-dir (file-name-directory formula-cache)))
18395 (unless (file-directory-p formula-cache-dir)
18396 (make-directory formula-cache-dir t))
18398 (unless (file-exists-p formula-cache)
18399 (org-create-math-formula latex-frag formula-cache))
18401 (if (file-exists-p formula-cache)
18402 ;; Successful conversion. Return the link to MathML file.
18403 (org-add-props
18404 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18405 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18406 'org-latex-src-embed-type (if latex-frag-type
18407 'paragraph 'character)))
18408 ;; Failed conversion. Return the LaTeX fragment verbatim
18409 latex-frag)))
18411 (defun org-create-formula-image (string tofile options buffer &optional type)
18412 "Create an image from LaTeX source using dvipng or convert.
18413 This function calls either `org-create-formula-image-with-dvipng'
18414 or `org-create-formula-image-with-imagemagick' depending on the
18415 value of `org-latex-create-formula-image-program' or on the value
18416 of the optional TYPE variable.
18418 Note: ultimately these two function should be combined as they
18419 share a good deal of logic."
18420 (org-check-external-command
18421 "latex" "needed to convert LaTeX fragments to images")
18422 (funcall
18423 (case (or type org-latex-create-formula-image-program)
18424 ('dvipng
18425 (org-check-external-command
18426 "dvipng" "needed to convert LaTeX fragments to images")
18427 #'org-create-formula-image-with-dvipng)
18428 ('imagemagick
18429 (org-check-external-command
18430 "convert" "you need to install imagemagick")
18431 #'org-create-formula-image-with-imagemagick)
18432 (t (error
18433 "Invalid value of `org-latex-create-formula-image-program'")))
18434 string tofile options buffer))
18436 (declare-function org-export--get-global-options "ox" (&optional backend))
18437 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18438 (defun org-create-formula--latex-header ()
18439 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18440 (org-latex-guess-inputenc
18441 (org-splice-latex-header
18442 org-format-latex-header
18443 org-latex-default-packages-alist
18444 org-latex-packages-alist t
18445 (plist-get
18446 (org-combine-plists
18447 (org-export--get-global-options 'latex)
18448 (org-export--get-inbuffer-options 'latex))
18449 :latex-header))))
18451 ;; This function borrows from Ganesh Swami's latex2png.el
18452 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18453 "This calls dvipng."
18454 (require 'ox-latex)
18455 (let* ((tmpdir (if (featurep 'xemacs)
18456 (temp-directory)
18457 temporary-file-directory))
18458 (texfilebase (make-temp-name
18459 (expand-file-name "orgtex" tmpdir)))
18460 (texfile (concat texfilebase ".tex"))
18461 (dvifile (concat texfilebase ".dvi"))
18462 (pngfile (concat texfilebase ".png"))
18463 (fnh (if (featurep 'xemacs)
18464 (font-height (face-font 'default))
18465 (face-attribute 'default :height nil)))
18466 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18467 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18468 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18469 "Black"))
18470 (bg (or (plist-get options (if buffer :background :html-background))
18471 "Transparent")))
18472 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18473 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18474 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18475 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18476 (let ((latex-header (org-create-formula--latex-header)))
18477 (with-temp-file texfile
18478 (insert latex-header)
18479 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18480 (let ((dir default-directory))
18481 (condition-case nil
18482 (progn
18483 (cd tmpdir)
18484 (call-process "latex" nil nil nil texfile))
18485 (error nil))
18486 (cd dir))
18487 (if (not (file-exists-p dvifile))
18488 (progn (message "Failed to create dvi file from %s" texfile) nil)
18489 (condition-case nil
18490 (if (featurep 'xemacs)
18491 (call-process "dvipng" nil nil nil
18492 "-fg" fg "-bg" bg
18493 "-T" "tight"
18494 "-o" pngfile
18495 dvifile)
18496 (call-process "dvipng" nil nil nil
18497 "-fg" fg "-bg" bg
18498 "-D" dpi
18499 ;;"-x" scale "-y" scale
18500 "-T" "tight"
18501 "-o" pngfile
18502 dvifile))
18503 (error nil))
18504 (if (not (file-exists-p pngfile))
18505 (if org-format-latex-signal-error
18506 (error "Failed to create png file from %s" texfile)
18507 (message "Failed to create png file from %s" texfile)
18508 nil)
18509 ;; Use the requested file name and clean up
18510 (copy-file pngfile tofile 'replace)
18511 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18512 (if (file-exists-p (concat texfilebase e))
18513 (delete-file (concat texfilebase e))))
18514 pngfile))))
18516 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18517 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18518 "This calls convert, which is included into imagemagick."
18519 (require 'ox-latex)
18520 (let* ((tmpdir (if (featurep 'xemacs)
18521 (temp-directory)
18522 temporary-file-directory))
18523 (texfilebase (make-temp-name
18524 (expand-file-name "orgtex" tmpdir)))
18525 (texfile (concat texfilebase ".tex"))
18526 (pdffile (concat texfilebase ".pdf"))
18527 (pngfile (concat texfilebase ".png"))
18528 (fnh (if (featurep 'xemacs)
18529 (font-height (face-font 'default))
18530 (face-attribute 'default :height nil)))
18531 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18532 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18533 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18534 "black"))
18535 (bg (or (plist-get options (if buffer :background :html-background))
18536 "white")))
18537 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18538 (setq fg (org-latex-color-format fg)))
18539 (if (eq bg 'default) (setq bg (org-latex-color :background))
18540 (setq bg (org-latex-color-format
18541 (if (string= bg "Transparent") "white" bg))))
18542 (let ((latex-header (org-create-formula--latex-header)))
18543 (with-temp-file texfile
18544 (insert latex-header)
18545 (insert "\n\\begin{document}\n"
18546 "\\definecolor{fg}{rgb}{" fg "}\n"
18547 "\\definecolor{bg}{rgb}{" bg "}\n"
18548 "\n\\pagecolor{bg}\n"
18549 "\n{\\color{fg}\n"
18550 string
18551 "\n}\n"
18552 "\n\\end{document}\n")))
18553 (org-latex-compile texfile t)
18554 (if (not (file-exists-p pdffile))
18555 (progn (message "Failed to create pdf file from %s" texfile) nil)
18556 (condition-case nil
18557 (if (featurep 'xemacs)
18558 (call-process "convert" nil nil nil
18559 "-density" "96"
18560 "-trim"
18561 "-antialias"
18562 pdffile
18563 "-quality" "100"
18564 ;; "-sharpen" "0x1.0"
18565 pngfile)
18566 (call-process "convert" nil nil nil
18567 "-density" dpi
18568 "-trim"
18569 "-antialias"
18570 pdffile
18571 "-quality" "100"
18572 ;; "-sharpen" "0x1.0"
18573 pngfile))
18574 (error nil))
18575 (if (not (file-exists-p pngfile))
18576 (if org-format-latex-signal-error
18577 (error "Failed to create png file from %s" texfile)
18578 (message "Failed to create png file from %s" texfile)
18579 nil)
18580 ;; Use the requested file name and clean up
18581 (copy-file pngfile tofile 'replace)
18582 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18583 (if (file-exists-p (concat texfilebase e))
18584 (delete-file (concat texfilebase e))))
18585 pngfile))))
18587 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18588 "Fill a LaTeX header template TPL.
18589 In the template, the following place holders will be recognized:
18591 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18592 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18593 [PACKAGES] \\usepackage statements for PKG
18594 [NO-PACKAGES] do not include PKG
18595 [EXTRA] the string EXTRA
18596 [NO-EXTRA] do not include EXTRA
18598 For backward compatibility, if both the positive and the negative place
18599 holder is missing, the positive one (without the \"NO-\") will be
18600 assumed to be present at the end of the template.
18601 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18602 EXTRA is a string.
18603 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18604 (let (rpl (end ""))
18605 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18606 (setq rpl (if (or (match-end 1) (not def-pkg))
18607 "" (org-latex-packages-to-string def-pkg snippets-p t))
18608 tpl (replace-match rpl t t tpl))
18609 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18611 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18612 (setq rpl (if (or (match-end 1) (not pkg))
18613 "" (org-latex-packages-to-string pkg snippets-p t))
18614 tpl (replace-match rpl t t tpl))
18615 (if pkg (setq end
18616 (concat end "\n"
18617 (org-latex-packages-to-string pkg snippets-p)))))
18619 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18620 (setq rpl (if (or (match-end 1) (not extra))
18621 "" (concat extra "\n"))
18622 tpl (replace-match rpl t t tpl))
18623 (if (and extra (string-match "\\S-" extra))
18624 (setq end (concat end "\n" extra))))
18626 (if (string-match "\\S-" end)
18627 (concat tpl "\n" end)
18628 tpl)))
18630 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18631 "Turn an alist of packages into a string with the \\usepackage macros."
18632 (setq pkg (mapconcat (lambda(p)
18633 (cond
18634 ((stringp p) p)
18635 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18636 (format "%% Package %s omitted" (cadr p)))
18637 ((equal "" (car p))
18638 (format "\\usepackage{%s}" (cadr p)))
18640 (format "\\usepackage[%s]{%s}"
18641 (car p) (cadr p)))))
18643 "\n"))
18644 (if newline (concat pkg "\n") pkg))
18646 (defun org-dvipng-color (attr)
18647 "Return a RGB color specification for dvipng."
18648 (apply 'format "rgb %s %s %s"
18649 (mapcar 'org-normalize-color
18650 (if (featurep 'xemacs)
18651 (color-rgb-components
18652 (face-property 'default
18653 (cond ((eq attr :foreground) 'foreground)
18654 ((eq attr :background) 'background))))
18655 (color-values (face-attribute 'default attr nil))))))
18657 (defun org-dvipng-color-format (color-name)
18658 "Convert COLOR-NAME to a RGB color value for dvipng."
18659 (apply 'format "rgb %s %s %s"
18660 (mapcar 'org-normalize-color
18661 (color-values color-name))))
18663 (defun org-latex-color (attr)
18664 "Return a RGB color for the LaTeX color package."
18665 (apply 'format "%s,%s,%s"
18666 (mapcar 'org-normalize-color
18667 (if (featurep 'xemacs)
18668 (color-rgb-components
18669 (face-property 'default
18670 (cond ((eq attr :foreground) 'foreground)
18671 ((eq attr :background) 'background))))
18672 (color-values (face-attribute 'default attr nil))))))
18674 (defun org-latex-color-format (color-name)
18675 "Convert COLOR-NAME to a RGB color value."
18676 (apply 'format "%s,%s,%s"
18677 (mapcar 'org-normalize-color
18678 (color-values color-name))))
18680 (defun org-normalize-color (value)
18681 "Return string to be used as color value for an RGB component."
18682 (format "%g" (/ value 65535.0)))
18686 ;; Image display
18688 (defvar org-inline-image-overlays nil)
18689 (make-variable-buffer-local 'org-inline-image-overlays)
18691 (defun org-toggle-inline-images (&optional include-linked)
18692 "Toggle the display of inline images.
18693 INCLUDE-LINKED is passed to `org-display-inline-images'."
18694 (interactive "P")
18695 (if org-inline-image-overlays
18696 (progn
18697 (org-remove-inline-images)
18698 (message "Inline image display turned off"))
18699 (org-display-inline-images include-linked)
18700 (if (and (org-called-interactively-p)
18701 org-inline-image-overlays)
18702 (message "%d images displayed inline"
18703 (length org-inline-image-overlays))
18704 (message "No images to display inline"))))
18706 (defun org-redisplay-inline-images ()
18707 "Refresh the display of inline images."
18708 (interactive)
18709 (if (not org-inline-image-overlays)
18710 (org-toggle-inline-images)
18711 (org-toggle-inline-images)
18712 (org-toggle-inline-images)))
18714 (defun org-display-inline-images (&optional include-linked refresh beg end)
18715 "Display inline images.
18716 Normally only links without a description part are inlined, because this
18717 is how it will work for export. When INCLUDE-LINKED is set, also links
18718 with a description part will be inlined. This can be nice for a quick
18719 look at those images, but it does not reflect what exported files will look
18720 like.
18721 When REFRESH is set, refresh existing images between BEG and END.
18722 This will create new image displays only if necessary.
18723 BEG and END default to the buffer boundaries."
18724 (interactive "P")
18725 (unless refresh
18726 (org-remove-inline-images)
18727 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18728 (save-excursion
18729 (save-restriction
18730 (widen)
18731 (setq beg (or beg (point-min)) end (or end (point-max)))
18732 (goto-char beg)
18733 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18734 (substring (org-image-file-name-regexp) 0 -2)
18735 "\\)\\]" (if include-linked "" "\\]")))
18736 (case-fold-search t)
18737 old file ov img type attrwidth width)
18738 (while (re-search-forward re end t)
18739 (setq old (get-char-property-and-overlay (match-beginning 1)
18740 'org-image-overlay)
18741 file (expand-file-name
18742 (concat (or (match-string 3) "") (match-string 4))))
18743 (when (image-type-available-p 'imagemagick)
18744 (setq attrwidth (if (or (listp org-image-actual-width)
18745 (null org-image-actual-width))
18746 (save-excursion
18747 (save-match-data
18748 (when (re-search-backward
18749 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18750 (save-excursion
18751 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18752 (string-to-number (match-string 1))))))
18753 width (cond ((eq org-image-actual-width t) nil)
18754 ((null org-image-actual-width) attrwidth)
18755 ((numberp org-image-actual-width)
18756 org-image-actual-width)
18757 ((listp org-image-actual-width)
18758 (or attrwidth (car org-image-actual-width))))
18759 type (if width 'imagemagick)))
18760 (when (file-exists-p file)
18761 (if (and (car-safe old) refresh)
18762 (image-refresh (overlay-get (cdr old) 'display))
18763 (setq img (save-match-data (create-image file type nil :width width)))
18764 (when img
18765 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18766 (overlay-put ov 'display img)
18767 (overlay-put ov 'face 'default)
18768 (overlay-put ov 'org-image-overlay t)
18769 (overlay-put ov 'modification-hooks
18770 (list 'org-display-inline-remove-overlay))
18771 (push ov org-inline-image-overlays)))))))))
18773 (define-obsolete-function-alias
18774 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18776 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18777 "Remove inline-display overlay if a corresponding region is modified."
18778 (let ((inhibit-modification-hooks t))
18779 (when (and ov after)
18780 (delete ov org-inline-image-overlays)
18781 (delete-overlay ov))))
18783 (defun org-remove-inline-images ()
18784 "Remove inline display of images."
18785 (interactive)
18786 (mapc 'delete-overlay org-inline-image-overlays)
18787 (setq org-inline-image-overlays nil))
18789 ;;;; Key bindings
18791 ;; Outline functions from `outline-mode-prefix-map'
18792 ;; that can be remapped in Org:
18793 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18794 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18795 (define-key org-mode-map [remap outline-forward-same-level]
18796 'org-forward-heading-same-level)
18797 (define-key org-mode-map [remap outline-backward-same-level]
18798 'org-backward-heading-same-level)
18799 (define-key org-mode-map [remap show-branches]
18800 'org-kill-note-or-show-branches)
18801 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18802 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18803 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18805 ;; Outline functions from `outline-mode-prefix-map' that can not
18806 ;; be remapped in Org:
18808 ;; - the column "key binding" shows whether the Outline function is still
18809 ;; available in Org mode on the same key that it has been bound to in
18810 ;; Outline mode:
18811 ;; - "overridden": key used for a different functionality in Org mode
18812 ;; - else: key still bound to the same Outline function in Org mode
18814 ;; | Outline function | key binding | Org replacement |
18815 ;; |------------------------------------+-------------+-----------------------|
18816 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18817 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18818 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18819 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18820 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18821 ;; | `show-entry' | overridden | no replacement |
18822 ;; | `show-children' | `C-c C-i' | visibility cycling |
18823 ;; | `show-branches' | `C-c C-k' | still same function |
18824 ;; | `show-subtree' | overridden | visibility cycling |
18825 ;; | `show-all' | overridden | no replacement |
18826 ;; | `hide-subtree' | overridden | visibility cycling |
18827 ;; | `hide-body' | overridden | no replacement |
18828 ;; | `hide-entry' | overridden | visibility cycling |
18829 ;; | `hide-leaves' | overridden | no replacement |
18830 ;; | `hide-sublevels' | overridden | no replacement |
18831 ;; | `hide-other' | overridden | no replacement |
18833 ;; Make `C-c C-x' a prefix key
18834 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18836 ;; TAB key with modifiers
18837 (org-defkey org-mode-map "\C-i" 'org-cycle)
18838 (org-defkey org-mode-map [(tab)] 'org-cycle)
18839 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18840 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18841 ;; The following line is necessary under Suse GNU/Linux
18842 (unless (featurep 'xemacs)
18843 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18844 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18845 (define-key org-mode-map [backtab] 'org-shifttab)
18847 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18848 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18849 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18851 ;; Cursor keys with modifiers
18852 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18853 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18854 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18855 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18857 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18858 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18859 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18860 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18862 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18863 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18864 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18865 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18867 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18868 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18869 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18870 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18872 ;; Babel keys
18873 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18874 (mapc (lambda (pair)
18875 (define-key org-babel-map (car pair) (cdr pair)))
18876 org-babel-key-bindings)
18878 ;;; Extra keys for tty access.
18879 ;; We only set them when really needed because otherwise the
18880 ;; menus don't show the simple keys
18882 (when (or org-use-extra-keys
18883 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18884 (not window-system))
18885 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18886 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18887 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18888 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18889 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18890 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18891 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18892 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18893 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18894 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18895 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18896 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18897 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18898 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18899 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18900 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18901 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18902 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18903 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18904 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18905 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18906 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18907 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18908 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18909 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18910 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18911 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18912 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18914 ;; All the other keys
18916 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18917 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18918 (if (boundp 'narrow-map)
18919 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18920 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18921 (if (boundp 'narrow-map)
18922 (org-defkey narrow-map "b" 'org-narrow-to-block)
18923 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18924 (if (boundp 'narrow-map)
18925 (org-defkey narrow-map "e" 'org-narrow-to-element)
18926 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18927 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18928 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18929 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18930 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18931 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18932 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18933 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18934 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18935 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18936 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18937 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18938 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18939 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18940 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18941 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18942 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18943 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18944 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18945 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18946 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18947 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18948 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18949 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18950 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18951 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18952 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18953 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18954 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18955 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18956 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18957 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18958 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18959 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18960 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18961 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18962 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18963 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18964 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18965 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18966 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18967 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18968 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18969 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18970 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18971 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18972 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18973 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18974 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18975 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18976 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18977 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18978 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18979 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18980 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18981 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18982 (org-defkey org-mode-map "\C-c^" 'org-sort)
18983 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18984 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18985 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18986 (org-defkey org-mode-map [remap open-line] 'org-open-line)
18987 (org-defkey org-mode-map "\C-m" 'org-return)
18988 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18989 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18990 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18991 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18992 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18993 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18994 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18995 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18996 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18997 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18998 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18999 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19000 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19001 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19002 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19003 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19004 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19005 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19006 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19007 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19008 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19009 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19010 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19012 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19013 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19014 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19016 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19017 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19018 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19019 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19020 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19021 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19022 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19023 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19024 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19025 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19026 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19027 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19028 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19029 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19030 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19031 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19032 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19033 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19034 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19035 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19036 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19037 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19038 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19040 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19041 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19042 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19043 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19044 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19046 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19048 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19050 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19051 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19053 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19056 (when (featurep 'xemacs)
19057 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19060 (defconst org-speed-commands-default
19062 ("Outline Navigation")
19063 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19064 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19065 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19066 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19067 ("F" . org-next-block)
19068 ("B" . org-previous-block)
19069 ("u" . (org-speed-move-safe 'outline-up-heading))
19070 ("j" . org-goto)
19071 ("g" . (org-refile t))
19072 ("Outline Visibility")
19073 ("c" . org-cycle)
19074 ("C" . org-shifttab)
19075 (" " . org-display-outline-path)
19076 ("s" . org-narrow-to-subtree)
19077 ("=" . org-columns)
19078 ("Outline Structure Editing")
19079 ("U" . org-shiftmetaup)
19080 ("D" . org-shiftmetadown)
19081 ("r" . org-metaright)
19082 ("l" . org-metaleft)
19083 ("R" . org-shiftmetaright)
19084 ("L" . org-shiftmetaleft)
19085 ("i" . (progn (forward-char 1) (call-interactively
19086 'org-insert-heading-respect-content)))
19087 ("^" . org-sort)
19088 ("w" . org-refile)
19089 ("a" . org-archive-subtree-default-with-confirmation)
19090 ("@" . org-mark-subtree)
19091 ("#" . org-toggle-comment)
19092 ("Clock Commands")
19093 ("I" . org-clock-in)
19094 ("O" . org-clock-out)
19095 ("Meta Data Editing")
19096 ("t" . org-todo)
19097 ("," . (org-priority))
19098 ("0" . (org-priority ?\ ))
19099 ("1" . (org-priority ?A))
19100 ("2" . (org-priority ?B))
19101 ("3" . (org-priority ?C))
19102 (":" . org-set-tags-command)
19103 ("e" . org-set-effort)
19104 ("E" . org-inc-effort)
19105 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19106 (org-entry-put (point) "APPT_WARNTIME" m)))
19107 ("Agenda Views etc")
19108 ("v" . org-agenda)
19109 ("/" . org-sparse-tree)
19110 ("Misc")
19111 ("o" . org-open-at-point)
19112 ("?" . org-speed-command-help)
19113 ("<" . (org-agenda-set-restriction-lock 'subtree))
19114 (">" . (org-agenda-remove-restriction-lock))
19116 "The default speed commands.")
19118 (defun org-print-speed-command (e)
19119 (if (> (length (car e)) 1)
19120 (progn
19121 (princ "\n")
19122 (princ (car e))
19123 (princ "\n")
19124 (princ (make-string (length (car e)) ?-))
19125 (princ "\n"))
19126 (princ (car e))
19127 (princ " ")
19128 (if (symbolp (cdr e))
19129 (princ (symbol-name (cdr e)))
19130 (prin1 (cdr e)))
19131 (princ "\n")))
19133 (defun org-speed-command-help ()
19134 "Show the available speed commands."
19135 (interactive)
19136 (if (not org-use-speed-commands)
19137 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19138 (with-output-to-temp-buffer "*Help*"
19139 (princ "User-defined Speed commands\n===========================\n")
19140 (mapc 'org-print-speed-command org-speed-commands-user)
19141 (princ "\n")
19142 (princ "Built-in Speed commands\n=======================\n")
19143 (mapc 'org-print-speed-command org-speed-commands-default))
19144 (with-current-buffer "*Help*"
19145 (setq truncate-lines t))))
19147 (defun org-speed-move-safe (cmd)
19148 "Execute CMD, but make sure that the cursor always ends up in a headline.
19149 If not, return to the original position and throw an error."
19150 (interactive)
19151 (let ((pos (point)))
19152 (call-interactively cmd)
19153 (unless (and (bolp) (org-at-heading-p))
19154 (goto-char pos)
19155 (error "Boundary reached while executing %s" cmd))))
19157 (defvar org-self-insert-command-undo-counter 0)
19159 (defvar org-table-auto-blank-field) ; defined in org-table.el
19160 (defvar org-speed-command nil)
19162 (define-obsolete-function-alias
19163 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19165 (defun org-speed-command-activate (keys)
19166 "Hook for activating single-letter speed commands.
19167 `org-speed-commands-default' specifies a minimal command set.
19168 Use `org-speed-commands-user' for further customization."
19169 (when (or (and (bolp) (looking-at org-outline-regexp))
19170 (and (functionp org-use-speed-commands)
19171 (funcall org-use-speed-commands)))
19172 (cdr (assoc keys (append org-speed-commands-user
19173 org-speed-commands-default)))))
19175 (define-obsolete-function-alias
19176 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19178 (defun org-babel-speed-command-activate (keys)
19179 "Hook for activating single-letter code block commands."
19180 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19181 (cdr (assoc keys org-babel-key-bindings))))
19183 (defcustom org-speed-command-hook
19184 '(org-speed-command-default-hook org-babel-speed-command-hook)
19185 "Hook for activating speed commands at strategic locations.
19186 Hook functions are called in sequence until a valid handler is
19187 found.
19189 Each hook takes a single argument, a user-pressed command key
19190 which is also a `self-insert-command' from the global map.
19192 Within the hook, examine the cursor position and the command key
19193 and return nil or a valid handler as appropriate. Handler could
19194 be one of an interactive command, a function, or a form.
19196 Set `org-use-speed-commands' to non-nil value to enable this
19197 hook. The default setting is `org-speed-command-activate'."
19198 :group 'org-structure
19199 :version "24.1"
19200 :type 'hook)
19202 (defun org-self-insert-command (N)
19203 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19204 If the cursor is in a table looking at whitespace, the whitespace is
19205 overwritten, and the table is not marked as requiring realignment."
19206 (interactive "p")
19207 (org-check-before-invisible-edit 'insert)
19208 (cond
19209 ((and org-use-speed-commands
19210 (setq org-speed-command
19211 (run-hook-with-args-until-success
19212 'org-speed-command-hook (this-command-keys))))
19213 (cond
19214 ((commandp org-speed-command)
19215 (setq this-command org-speed-command)
19216 (call-interactively org-speed-command))
19217 ((functionp org-speed-command)
19218 (funcall org-speed-command))
19219 ((and org-speed-command (listp org-speed-command))
19220 (eval org-speed-command))
19221 (t (let (org-use-speed-commands)
19222 (call-interactively 'org-self-insert-command)))))
19223 ((and
19224 (org-table-p)
19225 (progn
19226 ;; check if we blank the field, and if that triggers align
19227 (and (featurep 'org-table) org-table-auto-blank-field
19228 (member last-command
19229 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19230 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19231 ;; got extra space, this field does not determine column width
19232 (let (org-table-may-need-update) (org-table-blank-field))
19233 ;; no extra space, this field may determine column width
19234 (org-table-blank-field)))
19236 (eq N 1)
19237 (looking-at "[^|\n]* |"))
19238 (let (org-table-may-need-update)
19239 (goto-char (1- (match-end 0)))
19240 (backward-delete-char 1)
19241 (goto-char (match-beginning 0))
19242 (self-insert-command N)))
19244 (setq org-table-may-need-update t)
19245 (self-insert-command N)
19246 (org-fix-tags-on-the-fly)
19247 (if org-self-insert-cluster-for-undo
19248 (if (not (eq last-command 'org-self-insert-command))
19249 (setq org-self-insert-command-undo-counter 1)
19250 (if (>= org-self-insert-command-undo-counter 20)
19251 (setq org-self-insert-command-undo-counter 1)
19252 (and (> org-self-insert-command-undo-counter 0)
19253 buffer-undo-list (listp buffer-undo-list)
19254 (not (cadr buffer-undo-list)) ; remove nil entry
19255 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19256 (setq org-self-insert-command-undo-counter
19257 (1+ org-self-insert-command-undo-counter))))))))
19259 (defun org-check-before-invisible-edit (kind)
19260 "Check is editing if kind KIND would be dangerous with invisible text around.
19261 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19262 ;; First, try to get out of here as quickly as possible, to reduce overhead
19263 (if (and org-catch-invisible-edits
19264 (or (not (boundp 'visible-mode)) (not visible-mode))
19265 (or (get-char-property (point) 'invisible)
19266 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19267 ;; OK, we need to take a closer look
19268 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19269 (invisible-before-point (if (bobp) nil (get-char-property
19270 (1- (point)) 'invisible)))
19271 (border-and-ok-direction
19273 ;; Check if we are acting predictably before invisible text
19274 (and invisible-at-point (not invisible-before-point)
19275 (memq kind '(insert delete-backward)))
19276 ;; Check if we are acting predictably after invisible text
19277 ;; This works not well, and I have turned it off. It seems
19278 ;; better to always show and stop after invisible text.
19279 ;; (and (not invisible-at-point) invisible-before-point
19280 ;; (memq kind '(insert delete)))
19282 (when (or (memq invisible-at-point '(outline org-hide-block t))
19283 (memq invisible-before-point '(outline org-hide-block t)))
19284 (if (eq org-catch-invisible-edits 'error)
19285 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19286 (if (and org-custom-properties-overlays
19287 (y-or-n-p "Display invisible properties in this buffer? "))
19288 (org-toggle-custom-properties-visibility)
19289 ;; Make the area visible
19290 (save-excursion
19291 (if invisible-before-point
19292 (goto-char (previous-single-char-property-change
19293 (point) 'invisible)))
19294 (org-cycle))
19295 (cond
19296 ((eq org-catch-invisible-edits 'show)
19297 ;; That's it, we do the edit after showing
19298 (message
19299 "Unfolding invisible region around point before editing")
19300 (sit-for 1))
19301 ((and (eq org-catch-invisible-edits 'smart)
19302 border-and-ok-direction)
19303 (message "Unfolding invisible region around point before editing"))
19305 ;; Don't do the edit, make the user repeat it in full visibility
19306 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19308 (defun org-fix-tags-on-the-fly ()
19309 (when (and (equal (char-after (point-at-bol)) ?*)
19310 (org-at-heading-p))
19311 (org-align-tags-here org-tags-column)))
19313 (defun org-delete-backward-char (N)
19314 "Like `delete-backward-char', insert whitespace at field end in tables.
19315 When deleting backwards, in tables this function will insert whitespace in
19316 front of the next \"|\" separator, to keep the table aligned. The table will
19317 still be marked for re-alignment if the field did fill the entire column,
19318 because, in this case the deletion might narrow the column."
19319 (interactive "p")
19320 (save-match-data
19321 (org-check-before-invisible-edit 'delete-backward)
19322 (if (and (org-table-p)
19323 (eq N 1)
19324 (string-match "|" (buffer-substring (point-at-bol) (point)))
19325 (looking-at ".*?|"))
19326 (let ((pos (point))
19327 (noalign (looking-at "[^|\n\r]* |"))
19328 (c org-table-may-need-update))
19329 (backward-delete-char N)
19330 (if (not overwrite-mode)
19331 (progn
19332 (skip-chars-forward "^|")
19333 (insert " ")
19334 (goto-char (1- pos))))
19335 ;; noalign: if there were two spaces at the end, this field
19336 ;; does not determine the width of the column.
19337 (if noalign (setq org-table-may-need-update c)))
19338 (backward-delete-char N)
19339 (org-fix-tags-on-the-fly))))
19341 (defun org-delete-char (N)
19342 "Like `delete-char', but insert whitespace at field end in tables.
19343 When deleting characters, in tables this function will insert whitespace in
19344 front of the next \"|\" separator, to keep the table aligned. The table will
19345 still be marked for re-alignment if the field did fill the entire column,
19346 because, in this case the deletion might narrow the column."
19347 (interactive "p")
19348 (save-match-data
19349 (org-check-before-invisible-edit 'delete)
19350 (if (and (org-table-p)
19351 (not (bolp))
19352 (not (= (char-after) ?|))
19353 (eq N 1))
19354 (if (looking-at ".*?|")
19355 (let ((pos (point))
19356 (noalign (looking-at "[^|\n\r]* |"))
19357 (c org-table-may-need-update))
19358 (replace-match
19359 (concat (substring (match-string 0) 1 -1) " |") nil t)
19360 (goto-char pos)
19361 ;; noalign: if there were two spaces at the end, this field
19362 ;; does not determine the width of the column.
19363 (if noalign (setq org-table-may-need-update c)))
19364 (delete-char N))
19365 (delete-char N)
19366 (org-fix-tags-on-the-fly))))
19368 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19369 (put 'org-self-insert-command 'delete-selection t)
19370 (put 'orgtbl-self-insert-command 'delete-selection t)
19371 (put 'org-delete-char 'delete-selection 'supersede)
19372 (put 'org-delete-backward-char 'delete-selection 'supersede)
19373 (put 'org-yank 'delete-selection 'yank)
19375 ;; Make `flyspell-mode' delay after some commands
19376 (put 'org-self-insert-command 'flyspell-delayed t)
19377 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19378 (put 'org-delete-char 'flyspell-delayed t)
19379 (put 'org-delete-backward-char 'flyspell-delayed t)
19381 ;; Make pabbrev-mode expand after org-mode commands
19382 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19383 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19385 ;; How to do this: Measure non-white length of current string
19386 ;; If equal to column width, we should realign.
19388 (defun org-remap (map &rest commands)
19389 "In MAP, remap the functions given in COMMANDS.
19390 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19391 (let (new old)
19392 (while commands
19393 (setq old (pop commands) new (pop commands))
19394 (if (fboundp 'command-remapping)
19395 (org-defkey map (vector 'remap old) new)
19396 (substitute-key-definition old new map global-map)))))
19398 (defun org-transpose-words ()
19399 "Transpose words for Org.
19400 This uses the `org-mode-transpose-word-syntax-table' syntax
19401 table, which interprets characters in `org-emphasis-alist' as
19402 word constituants."
19403 (interactive)
19404 (with-syntax-table org-mode-transpose-word-syntax-table
19405 (call-interactively 'transpose-words)))
19406 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19408 (when (eq org-enable-table-editor 'optimized)
19409 ;; If the user wants maximum table support, we need to hijack
19410 ;; some standard editing functions
19411 (org-remap org-mode-map
19412 'self-insert-command 'org-self-insert-command
19413 'delete-char 'org-delete-char
19414 'delete-backward-char 'org-delete-backward-char)
19415 (org-defkey org-mode-map "|" 'org-force-self-insert))
19417 (defvar org-ctrl-c-ctrl-c-hook nil
19418 "Hook for functions attaching themselves to `C-c C-c'.
19420 This can be used to add additional functionality to the C-c C-c
19421 key which executes context-dependent commands. This hook is run
19422 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19423 run after the last test.
19425 Each function will be called with no arguments. The function
19426 must check if the context is appropriate for it to act. If yes,
19427 it should do its thing and then return a non-nil value. If the
19428 context is wrong, just do nothing and return nil.")
19430 (defvar org-ctrl-c-ctrl-c-final-hook nil
19431 "Hook for functions attaching themselves to `C-c C-c'.
19433 This can be used to add additional functionality to the C-c C-c
19434 key which executes context-dependent commands. This hook is run
19435 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19436 before the first test.
19438 Each function will be called with no arguments. The function
19439 must check if the context is appropriate for it to act. If yes,
19440 it should do its thing and then return a non-nil value. If the
19441 context is wrong, just do nothing and return nil.")
19443 (defvar org-tab-first-hook nil
19444 "Hook for functions to attach themselves to TAB.
19445 See `org-ctrl-c-ctrl-c-hook' for more information.
19446 This hook runs as the first action when TAB is pressed, even before
19447 `org-cycle' messes around with the `outline-regexp' to cater for
19448 inline tasks and plain list item folding.
19449 If any function in this hook returns t, any other actions that
19450 would have been caused by TAB (such as table field motion or visibility
19451 cycling) will not occur.")
19453 (defvar org-tab-after-check-for-table-hook nil
19454 "Hook for functions to attach themselves to TAB.
19455 See `org-ctrl-c-ctrl-c-hook' for more information.
19456 This hook runs after it has been established that the cursor is not in a
19457 table, but before checking if the cursor is in a headline or if global cycling
19458 should be done.
19459 If any function in this hook returns t, not other actions like visibility
19460 cycling will be done.")
19462 (defvar org-tab-after-check-for-cycling-hook nil
19463 "Hook for functions to attach themselves to TAB.
19464 See `org-ctrl-c-ctrl-c-hook' for more information.
19465 This hook runs after it has been established that not table field motion and
19466 not visibility should be done because of current context. This is probably
19467 the place where a package like yasnippets can hook in.")
19469 (defvar org-tab-before-tab-emulation-hook nil
19470 "Hook for functions to attach themselves to TAB.
19471 See `org-ctrl-c-ctrl-c-hook' for more information.
19472 This hook runs after every other options for TAB have been exhausted, but
19473 before indentation and \t insertion takes place.")
19475 (defvar org-metaleft-hook nil
19476 "Hook for functions attaching themselves to `M-left'.
19477 See `org-ctrl-c-ctrl-c-hook' for more information.")
19478 (defvar org-metaright-hook nil
19479 "Hook for functions attaching themselves to `M-right'.
19480 See `org-ctrl-c-ctrl-c-hook' for more information.")
19481 (defvar org-metaup-hook nil
19482 "Hook for functions attaching themselves to `M-up'.
19483 See `org-ctrl-c-ctrl-c-hook' for more information.")
19484 (defvar org-metadown-hook nil
19485 "Hook for functions attaching themselves to `M-down'.
19486 See `org-ctrl-c-ctrl-c-hook' for more information.")
19487 (defvar org-shiftmetaleft-hook nil
19488 "Hook for functions attaching themselves to `M-S-left'.
19489 See `org-ctrl-c-ctrl-c-hook' for more information.")
19490 (defvar org-shiftmetaright-hook nil
19491 "Hook for functions attaching themselves to `M-S-right'.
19492 See `org-ctrl-c-ctrl-c-hook' for more information.")
19493 (defvar org-shiftmetaup-hook nil
19494 "Hook for functions attaching themselves to `M-S-up'.
19495 See `org-ctrl-c-ctrl-c-hook' for more information.")
19496 (defvar org-shiftmetadown-hook nil
19497 "Hook for functions attaching themselves to `M-S-down'.
19498 See `org-ctrl-c-ctrl-c-hook' for more information.")
19499 (defvar org-metareturn-hook nil
19500 "Hook for functions attaching themselves to `M-RET'.
19501 See `org-ctrl-c-ctrl-c-hook' for more information.")
19502 (defvar org-shiftup-hook nil
19503 "Hook for functions attaching themselves to `S-up'.
19504 See `org-ctrl-c-ctrl-c-hook' for more information.")
19505 (defvar org-shiftup-final-hook nil
19506 "Hook for functions attaching themselves to `S-up'.
19507 This one runs after all other options except shift-select have been excluded.
19508 See `org-ctrl-c-ctrl-c-hook' for more information.")
19509 (defvar org-shiftdown-hook nil
19510 "Hook for functions attaching themselves to `S-down'.
19511 See `org-ctrl-c-ctrl-c-hook' for more information.")
19512 (defvar org-shiftdown-final-hook nil
19513 "Hook for functions attaching themselves to `S-down'.
19514 This one runs after all other options except shift-select have been excluded.
19515 See `org-ctrl-c-ctrl-c-hook' for more information.")
19516 (defvar org-shiftleft-hook nil
19517 "Hook for functions attaching themselves to `S-left'.
19518 See `org-ctrl-c-ctrl-c-hook' for more information.")
19519 (defvar org-shiftleft-final-hook nil
19520 "Hook for functions attaching themselves to `S-left'.
19521 This one runs after all other options except shift-select have been excluded.
19522 See `org-ctrl-c-ctrl-c-hook' for more information.")
19523 (defvar org-shiftright-hook nil
19524 "Hook for functions attaching themselves to `S-right'.
19525 See `org-ctrl-c-ctrl-c-hook' for more information.")
19526 (defvar org-shiftright-final-hook nil
19527 "Hook for functions attaching themselves to `S-right'.
19528 This one runs after all other options except shift-select have been excluded.
19529 See `org-ctrl-c-ctrl-c-hook' for more information.")
19531 (defun org-modifier-cursor-error ()
19532 "Throw an error, a modified cursor command was applied in wrong context."
19533 (user-error "This command is active in special context like tables, headlines or items"))
19535 (defun org-shiftselect-error ()
19536 "Throw an error because Shift-Cursor command was applied in wrong context."
19537 (if (and (boundp 'shift-select-mode) shift-select-mode)
19538 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19539 (user-error "This command works only in special context like headlines or timestamps")))
19541 (defun org-call-for-shift-select (cmd)
19542 (let ((this-command-keys-shift-translated t))
19543 (call-interactively cmd)))
19545 (defun org-shifttab (&optional arg)
19546 "Global visibility cycling or move to previous table field.
19547 Call `org-table-previous-field' within a table.
19548 When ARG is nil, cycle globally through visibility states.
19549 When ARG is a numeric prefix, show contents of this level."
19550 (interactive "P")
19551 (cond
19552 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19553 ((integerp arg)
19554 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19555 (message "Content view to level: %d" arg)
19556 (org-content (prefix-numeric-value arg2))
19557 (org-cycle-show-empty-lines t)
19558 (setq org-cycle-global-status 'overview)))
19559 (t (call-interactively 'org-global-cycle))))
19561 (defun org-shiftmetaleft ()
19562 "Promote subtree or delete table column.
19563 Calls `org-promote-subtree', `org-outdent-item-tree', or
19564 `org-table-delete-column', depending on context. See the
19565 individual commands for more information."
19566 (interactive)
19567 (cond
19568 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19569 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19570 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19571 ((if (not (org-region-active-p)) (org-at-item-p)
19572 (save-excursion (goto-char (region-beginning))
19573 (org-at-item-p)))
19574 (call-interactively 'org-outdent-item-tree))
19575 (t (org-modifier-cursor-error))))
19577 (defun org-shiftmetaright ()
19578 "Demote subtree or insert table column.
19579 Calls `org-demote-subtree', `org-indent-item-tree', or
19580 `org-table-insert-column', depending on context. See the
19581 individual commands for more information."
19582 (interactive)
19583 (cond
19584 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19585 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19586 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19587 ((if (not (org-region-active-p)) (org-at-item-p)
19588 (save-excursion (goto-char (region-beginning))
19589 (org-at-item-p)))
19590 (call-interactively 'org-indent-item-tree))
19591 (t (org-modifier-cursor-error))))
19593 (defun org-shiftmetaup (&optional arg)
19594 "Move subtree up or kill table row.
19595 Calls `org-move-subtree-up' or `org-table-kill-row' or
19596 `org-move-item-up' or `org-timestamp-up', depending on context.
19597 See the individual commands for more information."
19598 (interactive "P")
19599 (cond
19600 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19601 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19602 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19603 ((org-at-item-p) (call-interactively 'org-move-item-up))
19604 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19605 (call-interactively 'org-timestamp-up)))
19606 (t (call-interactively 'org-drag-line-backward))))
19608 (defun org-shiftmetadown (&optional arg)
19609 "Move subtree down or insert table row.
19610 Calls `org-move-subtree-down' or `org-table-insert-row' or
19611 `org-move-item-down' or `org-timestamp-up', depending on context.
19612 See the individual commands for more information."
19613 (interactive "P")
19614 (cond
19615 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19616 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19617 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19618 ((org-at-item-p) (call-interactively 'org-move-item-down))
19619 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19620 (call-interactively 'org-timestamp-down)))
19621 (t (call-interactively 'org-drag-line-forward))))
19623 (defsubst org-hidden-tree-error ()
19624 (user-error
19625 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19627 (defun org-metaleft (&optional arg)
19628 "Promote heading or move table column to left.
19629 Calls `org-do-promote' or `org-table-move-column', depending on context.
19630 With no specific context, calls the Emacs default `backward-word'.
19631 See the individual commands for more information."
19632 (interactive "P")
19633 (cond
19634 ((run-hook-with-args-until-success 'org-metaleft-hook))
19635 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19636 ((org-with-limited-levels
19637 (or (org-at-heading-p)
19638 (and (org-region-active-p)
19639 (save-excursion
19640 (goto-char (region-beginning))
19641 (org-at-heading-p)))))
19642 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19643 (call-interactively 'org-do-promote))
19644 ;; At an inline task.
19645 ((org-at-heading-p)
19646 (call-interactively 'org-inlinetask-promote))
19647 ((or (org-at-item-p)
19648 (and (org-region-active-p)
19649 (save-excursion
19650 (goto-char (region-beginning))
19651 (org-at-item-p))))
19652 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19653 (call-interactively 'org-outdent-item))
19654 (t (call-interactively 'backward-word))))
19656 (defun org-metaright (&optional arg)
19657 "Demote a subtree, a list item or move table column to right.
19658 In front of a drawer or a block keyword, indent it correctly.
19659 With no specific context, calls the Emacs default `forward-word'.
19660 See the individual commands for more information."
19661 (interactive "P")
19662 (cond
19663 ((run-hook-with-args-until-success 'org-metaright-hook))
19664 ((org-at-table-p) (call-interactively 'org-table-move-column))
19665 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19666 ((org-at-block-p) (call-interactively 'org-indent-block))
19667 ((org-with-limited-levels
19668 (or (org-at-heading-p)
19669 (and (org-region-active-p)
19670 (save-excursion
19671 (goto-char (region-beginning))
19672 (org-at-heading-p)))))
19673 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19674 (call-interactively 'org-do-demote))
19675 ;; At an inline task.
19676 ((org-at-heading-p)
19677 (call-interactively 'org-inlinetask-demote))
19678 ((or (org-at-item-p)
19679 (and (org-region-active-p)
19680 (save-excursion
19681 (goto-char (region-beginning))
19682 (org-at-item-p))))
19683 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19684 (call-interactively 'org-indent-item))
19685 (t (call-interactively 'forward-word))))
19687 (defun org-check-for-hidden (what)
19688 "Check if there are hidden headlines/items in the current visual line.
19689 WHAT can be either `headlines' or `items'. If the current line is
19690 an outline or item heading and it has a folded subtree below it,
19691 this function returns t, nil otherwise."
19692 (let ((re (cond
19693 ((eq what 'headlines) org-outline-regexp-bol)
19694 ((eq what 'items) (org-item-beginning-re))
19695 (t (error "This should not happen"))))
19696 beg end)
19697 (save-excursion
19698 (catch 'exit
19699 (unless (org-region-active-p)
19700 (setq beg (point-at-bol))
19701 (beginning-of-line 2)
19702 (while (and (not (eobp)) ;; this is like `next-line'
19703 (get-char-property (1- (point)) 'invisible))
19704 (beginning-of-line 2))
19705 (setq end (point))
19706 (goto-char beg)
19707 (goto-char (point-at-eol))
19708 (setq end (max end (point)))
19709 (while (re-search-forward re end t)
19710 (if (get-char-property (match-beginning 0) 'invisible)
19711 (throw 'exit t))))
19712 nil))))
19714 (defun org-metaup (&optional arg)
19715 "Move subtree up or move table row up.
19716 Calls `org-move-subtree-up' or `org-table-move-row' or
19717 `org-move-item-up', depending on context. See the individual commands
19718 for more information."
19719 (interactive "P")
19720 (cond
19721 ((run-hook-with-args-until-success 'org-metaup-hook))
19722 ((org-region-active-p)
19723 (let* ((a (min (region-beginning) (region-end)))
19724 (b (1- (max (region-beginning) (region-end))))
19725 (c (save-excursion (goto-char a)
19726 (move-beginning-of-line 0)))
19727 (d (save-excursion (goto-char a)
19728 (move-end-of-line 0) (point))))
19729 (transpose-regions a b c d)
19730 (goto-char c)))
19731 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19732 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19733 ((org-at-item-p) (call-interactively 'org-move-item-up))
19734 (t (org-drag-element-backward))))
19736 (defun org-metadown (&optional arg)
19737 "Move subtree down or move table row down.
19738 Calls `org-move-subtree-down' or `org-table-move-row' or
19739 `org-move-item-down', depending on context. See the individual
19740 commands for more information."
19741 (interactive "P")
19742 (cond
19743 ((run-hook-with-args-until-success 'org-metadown-hook))
19744 ((org-region-active-p)
19745 (let* ((a (min (region-beginning) (region-end)))
19746 (b (max (region-beginning) (region-end)))
19747 (c (save-excursion (goto-char b)
19748 (move-beginning-of-line 1)))
19749 (d (save-excursion (goto-char b)
19750 (move-end-of-line 1) (1+ (point)))))
19751 (transpose-regions a b c d)
19752 (goto-char d)))
19753 ((org-at-table-p) (call-interactively 'org-table-move-row))
19754 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19755 ((org-at-item-p) (call-interactively 'org-move-item-down))
19756 (t (org-drag-element-forward))))
19758 (defun org-shiftup (&optional arg)
19759 "Increase item in timestamp or increase priority of current headline.
19760 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19761 depending on context. See the individual commands for more information."
19762 (interactive "P")
19763 (cond
19764 ((run-hook-with-args-until-success 'org-shiftup-hook))
19765 ((and org-support-shift-select (org-region-active-p))
19766 (org-call-for-shift-select 'previous-line))
19767 ((org-at-timestamp-p t)
19768 (call-interactively (if org-edit-timestamp-down-means-later
19769 'org-timestamp-down 'org-timestamp-up)))
19770 ((and (not (eq org-support-shift-select 'always))
19771 org-enable-priority-commands
19772 (org-at-heading-p))
19773 (call-interactively 'org-priority-up))
19774 ((and (not org-support-shift-select) (org-at-item-p))
19775 (call-interactively 'org-previous-item))
19776 ((org-clocktable-try-shift 'up arg))
19777 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19778 (org-support-shift-select
19779 (org-call-for-shift-select 'previous-line))
19780 (t (org-shiftselect-error))))
19782 (defun org-shiftdown (&optional arg)
19783 "Decrease item in timestamp or decrease priority of current headline.
19784 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19785 depending on context. See the individual commands for more information."
19786 (interactive "P")
19787 (cond
19788 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19789 ((and org-support-shift-select (org-region-active-p))
19790 (org-call-for-shift-select 'next-line))
19791 ((org-at-timestamp-p t)
19792 (call-interactively (if org-edit-timestamp-down-means-later
19793 'org-timestamp-up 'org-timestamp-down)))
19794 ((and (not (eq org-support-shift-select 'always))
19795 org-enable-priority-commands
19796 (org-at-heading-p))
19797 (call-interactively 'org-priority-down))
19798 ((and (not org-support-shift-select) (org-at-item-p))
19799 (call-interactively 'org-next-item))
19800 ((org-clocktable-try-shift 'down arg))
19801 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19802 (org-support-shift-select
19803 (org-call-for-shift-select 'next-line))
19804 (t (org-shiftselect-error))))
19806 (defun org-shiftright (&optional arg)
19807 "Cycle the thing at point or in the current line, depending on context.
19808 Depending on context, this does one of the following:
19810 - switch a timestamp at point one day into the future
19811 - on a headline, switch to the next TODO keyword.
19812 - on an item, switch entire list to the next bullet type
19813 - on a property line, switch to the next allowed value
19814 - on a clocktable definition line, move time block into the future"
19815 (interactive "P")
19816 (cond
19817 ((run-hook-with-args-until-success 'org-shiftright-hook))
19818 ((and org-support-shift-select (org-region-active-p))
19819 (org-call-for-shift-select 'forward-char))
19820 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19821 ((and (not (eq org-support-shift-select 'always))
19822 (org-at-heading-p))
19823 (let ((org-inhibit-logging
19824 (not org-treat-S-cursor-todo-selection-as-state-change))
19825 (org-inhibit-blocking
19826 (not org-treat-S-cursor-todo-selection-as-state-change)))
19827 (org-call-with-arg 'org-todo 'right)))
19828 ((or (and org-support-shift-select
19829 (not (eq org-support-shift-select 'always))
19830 (org-at-item-bullet-p))
19831 (and (not org-support-shift-select) (org-at-item-p)))
19832 (org-call-with-arg 'org-cycle-list-bullet nil))
19833 ((and (not (eq org-support-shift-select 'always))
19834 (org-at-property-p))
19835 (call-interactively 'org-property-next-allowed-value))
19836 ((org-clocktable-try-shift 'right arg))
19837 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19838 (org-support-shift-select
19839 (org-call-for-shift-select 'forward-char))
19840 (t (org-shiftselect-error))))
19842 (defun org-shiftleft (&optional arg)
19843 "Cycle the thing at point or in the current line, depending on context.
19844 Depending on context, this does one of the following:
19846 - switch a timestamp at point one day into the past
19847 - on a headline, switch to the previous TODO keyword.
19848 - on an item, switch entire list to the previous bullet type
19849 - on a property line, switch to the previous allowed value
19850 - on a clocktable definition line, move time block into the past"
19851 (interactive "P")
19852 (cond
19853 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19854 ((and org-support-shift-select (org-region-active-p))
19855 (org-call-for-shift-select 'backward-char))
19856 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19857 ((and (not (eq org-support-shift-select 'always))
19858 (org-at-heading-p))
19859 (let ((org-inhibit-logging
19860 (not org-treat-S-cursor-todo-selection-as-state-change))
19861 (org-inhibit-blocking
19862 (not org-treat-S-cursor-todo-selection-as-state-change)))
19863 (org-call-with-arg 'org-todo 'left)))
19864 ((or (and org-support-shift-select
19865 (not (eq org-support-shift-select 'always))
19866 (org-at-item-bullet-p))
19867 (and (not org-support-shift-select) (org-at-item-p)))
19868 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19869 ((and (not (eq org-support-shift-select 'always))
19870 (org-at-property-p))
19871 (call-interactively 'org-property-previous-allowed-value))
19872 ((org-clocktable-try-shift 'left arg))
19873 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19874 (org-support-shift-select
19875 (org-call-for-shift-select 'backward-char))
19876 (t (org-shiftselect-error))))
19878 (defun org-shiftcontrolright ()
19879 "Switch to next TODO set."
19880 (interactive)
19881 (cond
19882 ((and org-support-shift-select (org-region-active-p))
19883 (org-call-for-shift-select 'forward-word))
19884 ((and (not (eq org-support-shift-select 'always))
19885 (org-at-heading-p))
19886 (org-call-with-arg 'org-todo 'nextset))
19887 (org-support-shift-select
19888 (org-call-for-shift-select 'forward-word))
19889 (t (org-shiftselect-error))))
19891 (defun org-shiftcontrolleft ()
19892 "Switch to previous TODO set."
19893 (interactive)
19894 (cond
19895 ((and org-support-shift-select (org-region-active-p))
19896 (org-call-for-shift-select 'backward-word))
19897 ((and (not (eq org-support-shift-select 'always))
19898 (org-at-heading-p))
19899 (org-call-with-arg 'org-todo 'previousset))
19900 (org-support-shift-select
19901 (org-call-for-shift-select 'backward-word))
19902 (t (org-shiftselect-error))))
19904 (defun org-shiftcontrolup (&optional n)
19905 "Change timestamps synchronously up in CLOCK log lines.
19906 Optional argument N tells to change by that many units."
19907 (interactive "P")
19908 (cond ((and (not org-support-shift-select)
19909 (org-at-clock-log-p)
19910 (org-at-timestamp-p t))
19911 (org-clock-timestamps-up n))
19912 (t (org-shiftselect-error))))
19914 (defun org-shiftcontroldown (&optional n)
19915 "Change timestamps synchronously down in CLOCK log lines.
19916 Optional argument N tells to change by that many units."
19917 (interactive "P")
19918 (cond ((and (not org-support-shift-select)
19919 (org-at-clock-log-p)
19920 (org-at-timestamp-p t))
19921 (org-clock-timestamps-down n))
19922 (t (org-shiftselect-error))))
19924 (defun org-ctrl-c-ret ()
19925 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19926 (interactive)
19927 (cond
19928 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19929 (t (call-interactively 'org-insert-heading))))
19931 (defun org-find-visible ()
19932 (let ((s (point)))
19933 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19934 (get-char-property s 'invisible)))
19936 (defun org-find-invisible ()
19937 (let ((s (point)))
19938 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19939 (not (get-char-property s 'invisible))))
19942 (defun org-copy-visible (beg end)
19943 "Copy the visible parts of the region."
19944 (interactive "r")
19945 (let (snippets s)
19946 (save-excursion
19947 (save-restriction
19948 (narrow-to-region beg end)
19949 (setq s (goto-char (point-min)))
19950 (while (not (= (point) (point-max)))
19951 (goto-char (org-find-invisible))
19952 (push (buffer-substring s (point)) snippets)
19953 (setq s (goto-char (org-find-visible))))))
19954 (kill-new (apply 'concat (nreverse snippets)))))
19956 (defun org-copy-special ()
19957 "Copy region in table or copy current subtree.
19958 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19959 See the individual commands for more information."
19960 (interactive)
19961 (call-interactively
19962 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19964 (defun org-cut-special ()
19965 "Cut region in table or cut current subtree.
19966 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19967 See the individual commands for more information."
19968 (interactive)
19969 (call-interactively
19970 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19972 (defun org-paste-special (arg)
19973 "Paste rectangular region into table, or past subtree relative to level.
19974 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19975 See the individual commands for more information."
19976 (interactive "P")
19977 (if (org-at-table-p)
19978 (org-table-paste-rectangle)
19979 (org-paste-subtree arg)))
19981 (defsubst org-in-fixed-width-region-p ()
19982 "Is point in a fixed-width region?"
19983 (save-match-data
19984 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19986 (defun org-edit-special (&optional arg)
19987 "Call a special editor for the element at point.
19988 When at a table, call the formula editor with `org-table-edit-formulas'.
19989 When in a source code block, call `org-edit-src-code'.
19990 When in a fixed-width region, call `org-edit-fixed-width-region'.
19991 When at an #+INCLUDE keyword, visit the included file.
19992 On a link, call `ffap' to visit the link at point.
19993 Otherwise, return a user error."
19994 (interactive "P")
19995 (let ((element (org-element-at-point)))
19996 (assert (not buffer-read-only) nil
19997 "Buffer is read-only: %s" (buffer-name))
19998 (case (org-element-type element)
19999 (src-block
20000 (if (not arg) (org-edit-src-code)
20001 (let* ((info (org-babel-get-src-block-info))
20002 (lang (nth 0 info))
20003 (params (nth 2 info))
20004 (session (cdr (assq :session params))))
20005 (if (not session) (org-edit-src-code)
20006 ;; At a src-block with a session and function called with
20007 ;; an ARG: switch to the buffer related to the inferior
20008 ;; process.
20009 (switch-to-buffer
20010 (funcall (intern (concat "org-babel-prep-session:" lang))
20011 session params))))))
20012 (keyword
20013 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20014 (find-file
20015 (org-remove-double-quotes
20016 (car (org-split-string (org-element-property :value element)))))
20017 (user-error "No special environment to edit here")))
20018 (table
20019 (if (eq (org-element-property :type element) 'table.el)
20020 (org-edit-src-code)
20021 (call-interactively 'org-table-edit-formulas)))
20022 ;; Only Org tables contain `table-row' type elements.
20023 (table-row (call-interactively 'org-table-edit-formulas))
20024 ((example-block export-block) (org-edit-src-code))
20025 (fixed-width (org-edit-fixed-width-region))
20026 (otherwise
20027 ;; No notable element at point. Though, we may be at a link,
20028 ;; which is an object. Thus, scan deeper.
20029 (if (eq (org-element-type (org-element-context element)) 'link)
20030 (call-interactively 'ffap)
20031 (user-error "No special environment to edit here"))))))
20033 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20034 (defun org-ctrl-c-ctrl-c (&optional arg)
20035 "Set tags in headline, or update according to changed information at point.
20037 This command does many different things, depending on context:
20039 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20040 this is what we do.
20042 - If the cursor is on a statistics cookie, update it.
20044 - If the cursor is in a headline, prompt for tags and insert them
20045 into the current line, aligned to `org-tags-column'. When called
20046 with prefix arg, realign all tags in the current buffer.
20048 - If the cursor is in one of the special #+KEYWORD lines, this
20049 triggers scanning the buffer for these lines and updating the
20050 information.
20052 - If the cursor is inside a table, realign the table. This command
20053 works even if the automatic table editor has been turned off.
20055 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20056 the entire table.
20058 - If the cursor is at a footnote reference or definition, jump to
20059 the corresponding definition or references, respectively.
20061 - If the cursor is a the beginning of a dynamic block, update it.
20063 - If the current buffer is a capture buffer, close note and file it.
20065 - If the cursor is on a <<<target>>>, update radio targets and
20066 corresponding links in this buffer.
20068 - If the cursor is on a numbered item in a plain list, renumber the
20069 ordered list.
20071 - If the cursor is on a checkbox, toggle it.
20073 - If the cursor is on a code block, evaluate it. The variable
20074 `org-confirm-babel-evaluate' can be used to control prompting
20075 before code block evaluation, by default every code block
20076 evaluation requires confirmation. Code block evaluation can be
20077 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20078 (interactive "P")
20079 (cond
20080 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20081 org-occur-highlights
20082 org-latex-fragment-image-overlays)
20083 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20084 (org-remove-occur-highlights)
20085 (org-remove-latex-fragment-image-overlays)
20086 (message "Temporary highlights/overlays removed from current buffer"))
20087 ((and (local-variable-p 'org-finish-function (current-buffer))
20088 (fboundp org-finish-function))
20089 (funcall org-finish-function))
20090 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20092 (let* ((context (org-element-context)) (type (org-element-type context)))
20093 ;; Test if point is within a blank line.
20094 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20095 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20096 (user-error "C-c C-c can do nothing useful at this location"))
20097 ;; For convenience: at the first line of a paragraph on the
20098 ;; same line as an item, apply function on that item instead.
20099 (when (eq type 'paragraph)
20100 (let ((parent (org-element-property :parent context)))
20101 (when (and (eq (org-element-type parent) 'item)
20102 (= (point-at-bol) (org-element-property :begin parent)))
20103 (setq context parent type 'item))))
20104 ;; Act according to type of element or object at point.
20105 (case type
20106 (clock (org-clock-update-time-maybe))
20107 (dynamic-block
20108 (save-excursion
20109 (goto-char (org-element-property :post-affiliated context))
20110 (org-update-dblock)))
20111 (footnote-definition
20112 (goto-char (org-element-property :post-affiliated context))
20113 (call-interactively 'org-footnote-action))
20114 (footnote-reference (call-interactively 'org-footnote-action))
20115 ((headline inlinetask)
20116 (save-excursion (goto-char (org-element-property :begin context))
20117 (call-interactively 'org-set-tags)))
20118 (item
20119 ;; At an item: a double C-u set checkbox to "[-]"
20120 ;; unconditionally, whereas a single one will toggle its
20121 ;; presence. Without an universal argument, if the item
20122 ;; has a checkbox, toggle it. Otherwise repair the list.
20123 (let* ((box (org-element-property :checkbox context))
20124 (struct (org-element-property :structure context))
20125 (old-struct (copy-tree struct))
20126 (parents (org-list-parents-alist struct))
20127 (prevs (org-list-prevs-alist struct))
20128 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20129 (org-list-set-checkbox
20130 (org-element-property :begin context) struct
20131 (cond ((equal arg '(16)) "[-]")
20132 ((and (not box) (equal arg '(4))) "[ ]")
20133 ((or (not box) (equal arg '(4))) nil)
20134 ((eq box 'on) "[ ]")
20135 (t "[X]")))
20136 ;; Mimic `org-list-write-struct' but with grabbing
20137 ;; a return value from `org-list-struct-fix-box'.
20138 (org-list-struct-fix-ind struct parents 2)
20139 (org-list-struct-fix-item-end struct)
20140 (org-list-struct-fix-bul struct prevs)
20141 (org-list-struct-fix-ind struct parents)
20142 (let ((block-item
20143 (org-list-struct-fix-box struct parents prevs orderedp)))
20144 (if (and box (equal struct old-struct))
20145 (if (equal arg '(16))
20146 (message "Checkboxes already reset")
20147 (user-error "Cannot toggle this checkbox: %s"
20148 (if (eq box 'on)
20149 "all subitems checked"
20150 "unchecked subitems")))
20151 (org-list-struct-apply-struct struct old-struct)
20152 (org-update-checkbox-count-maybe))
20153 (when block-item
20154 (message "Checkboxes were removed due to empty box at line %d"
20155 (org-current-line block-item))))))
20156 (keyword
20157 (let ((org-inhibit-startup-visibility-stuff t)
20158 (org-startup-align-all-tables nil))
20159 (when (boundp 'org-table-coordinate-overlays)
20160 (mapc 'delete-overlay org-table-coordinate-overlays)
20161 (setq org-table-coordinate-overlays nil))
20162 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20163 (message "Local setup has been refreshed"))
20164 (plain-list
20165 ;; At a plain list, with a double C-u argument, set
20166 ;; checkboxes of each item to "[-]", whereas a single one
20167 ;; will toggle their presence according to the state of the
20168 ;; first item in the list. Without an argument, repair the
20169 ;; list.
20170 (let* ((begin (org-element-property :contents-begin context))
20171 (beginm (move-marker (make-marker) begin))
20172 (struct (org-element-property :structure context))
20173 (old-struct (copy-tree struct))
20174 (first-box (save-excursion
20175 (goto-char begin)
20176 (looking-at org-list-full-item-re)
20177 (match-string-no-properties 3)))
20178 (new-box (cond ((equal arg '(16)) "[-]")
20179 ((equal arg '(4)) (unless first-box "[ ]"))
20180 ((equal first-box "[X]") "[ ]")
20181 (t "[X]"))))
20182 (cond
20183 (arg
20184 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20185 (org-list-get-all-items
20186 begin struct (org-list-prevs-alist struct))))
20187 ((and first-box (eq (point) begin))
20188 ;; For convenience, when point is at bol on the first
20189 ;; item of the list and no argument is provided, simply
20190 ;; toggle checkbox of that item, if any.
20191 (org-list-set-checkbox begin struct new-box)))
20192 (org-list-write-struct
20193 struct (org-list-parents-alist struct) old-struct)
20194 (org-update-checkbox-count-maybe)
20195 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20196 ((property-drawer node-property)
20197 (call-interactively 'org-property-action))
20198 ((radio-target target)
20199 (call-interactively 'org-update-radio-target-regexp))
20200 (statistics-cookie
20201 (call-interactively 'org-update-statistics-cookies))
20202 ((table table-cell table-row)
20203 ;; At a table, recalculate every field and align it. Also
20204 ;; send the table if necessary. If the table has
20205 ;; a `table.el' type, just give up. At a table row or
20206 ;; cell, maybe recalculate line but always align table.
20207 (if (eq (org-element-property :type context) 'table.el)
20208 (message "Use C-c ' to edit table.el tables")
20209 (let ((org-enable-table-editor t))
20210 (if (or (eq type 'table)
20211 ;; Check if point is at a TBLFM line.
20212 (and (eq type 'table-row)
20213 (= (point) (org-element-property :end context))))
20214 (save-excursion
20215 (if (org-at-TBLFM-p) (org-calc-current-TBLFM)
20216 (goto-char (org-element-property :contents-begin context))
20217 (org-call-with-arg 'org-table-recalculate (or arg t))
20218 (orgtbl-send-table 'maybe)))
20219 (org-table-maybe-eval-formula)
20220 (cond (arg (call-interactively 'org-table-recalculate))
20221 ((org-table-maybe-recalculate-line))
20222 (t (org-table-align)))))))
20223 (timestamp (org-timestamp-change 0 'day))
20224 (otherwise
20225 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20226 (user-error
20227 "C-c C-c can do nothing useful at this location")))))))))
20229 (defun org-mode-restart ()
20230 "Restart Org-mode, to scan again for special lines.
20231 Also updates the keyword regular expressions."
20232 (interactive)
20233 (org-mode)
20234 (message "Org-mode restarted"))
20236 (defun org-kill-note-or-show-branches ()
20237 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20238 (interactive)
20239 (if (not org-finish-function)
20240 (progn
20241 (hide-subtree)
20242 (call-interactively 'show-branches))
20243 (let ((org-note-abort t))
20244 (funcall org-finish-function))))
20246 (defun org-open-line (n)
20247 "Insert a new row in tables, call `open-line' elsewhere."
20248 (interactive "*p")
20249 (if (org-at-table-p)
20250 (org-table-insert-row)
20251 (open-line n)))
20253 (defun org-return (&optional indent)
20254 "Goto next table row or insert a newline.
20255 Calls `org-table-next-row' or `newline', depending on context.
20256 See the individual commands for more information."
20257 (interactive)
20258 (let (org-ts-what)
20259 (cond
20260 ((or (bobp) (org-in-src-block-p))
20261 (if indent (newline-and-indent) (newline)))
20262 ((org-at-table-p)
20263 (org-table-justify-field-maybe)
20264 (call-interactively 'org-table-next-row))
20265 ;; when `newline-and-indent' is called within a list, make sure
20266 ;; text moved stays inside the item.
20267 ((and (org-in-item-p) indent)
20268 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20269 (progn
20270 (save-match-data (newline))
20271 (org-indent-line-to (length (match-string 0))))
20272 (let ((ind (org-get-indentation)))
20273 (newline)
20274 (if (org-looking-back org-list-end-re)
20275 (org-indent-line)
20276 (org-indent-line-to ind)))))
20277 ((and org-return-follows-link
20278 (org-at-timestamp-p t)
20279 (not (eq org-ts-what 'after)))
20280 (org-follow-timestamp-link))
20281 ((and org-return-follows-link
20282 (let ((tprop (get-text-property (point) 'face)))
20283 (or (eq tprop 'org-link)
20284 (and (listp tprop) (memq 'org-link tprop)))))
20285 (call-interactively 'org-open-at-point))
20286 ((and (org-at-heading-p)
20287 (looking-at
20288 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20289 (org-show-entry)
20290 (end-of-line 1)
20291 (newline))
20292 (t (if indent (newline-and-indent) (newline))))))
20294 (defun org-return-indent ()
20295 "Goto next table row or insert a newline and indent.
20296 Calls `org-table-next-row' or `newline-and-indent', depending on
20297 context. See the individual commands for more information."
20298 (interactive)
20299 (org-return t))
20301 (defun org-ctrl-c-star ()
20302 "Compute table, or change heading status of lines.
20303 Calls `org-table-recalculate' or `org-toggle-heading',
20304 depending on context."
20305 (interactive)
20306 (cond
20307 ((org-at-table-p)
20308 (call-interactively 'org-table-recalculate))
20310 ;; Convert all lines in region to list items
20311 (call-interactively 'org-toggle-heading))))
20313 (defun org-ctrl-c-minus ()
20314 "Insert separator line in table or modify bullet status of line.
20315 Also turns a plain line or a region of lines into list items.
20316 Calls `org-table-insert-hline', `org-toggle-item', or
20317 `org-cycle-list-bullet', depending on context."
20318 (interactive)
20319 (cond
20320 ((org-at-table-p)
20321 (call-interactively 'org-table-insert-hline))
20322 ((org-region-active-p)
20323 (call-interactively 'org-toggle-item))
20324 ((org-in-item-p)
20325 (call-interactively 'org-cycle-list-bullet))
20327 (call-interactively 'org-toggle-item))))
20329 (defun org-toggle-item (arg)
20330 "Convert headings or normal lines to items, items to normal lines.
20331 If there is no active region, only the current line is considered.
20333 If the first non blank line in the region is a headline, convert
20334 all headlines to items, shifting text accordingly.
20336 If it is an item, convert all items to normal lines.
20338 If it is normal text, change region into a list of items.
20339 With a prefix argument ARG, change the region in a single item."
20340 (interactive "P")
20341 (let ((shift-text
20342 (function
20343 ;; Shift text in current section to IND, from point to END.
20344 ;; The function leaves point to END line.
20345 (lambda (ind end)
20346 (let ((min-i 1000) (end (copy-marker end)))
20347 ;; First determine the minimum indentation (MIN-I) of
20348 ;; the text.
20349 (save-excursion
20350 (catch 'exit
20351 (while (< (point) end)
20352 (let ((i (org-get-indentation)))
20353 (cond
20354 ;; Skip blank lines and inline tasks.
20355 ((looking-at "^[ \t]*$"))
20356 ((looking-at org-outline-regexp-bol))
20357 ;; We can't find less than 0 indentation.
20358 ((zerop i) (throw 'exit (setq min-i 0)))
20359 ((< i min-i) (setq min-i i))))
20360 (forward-line))))
20361 ;; Then indent each line so that a line indented to
20362 ;; MIN-I becomes indented to IND. Ignore blank lines
20363 ;; and inline tasks in the process.
20364 (let ((delta (- ind min-i)))
20365 (while (< (point) end)
20366 (unless (or (looking-at "^[ \t]*$")
20367 (looking-at org-outline-regexp-bol))
20368 (org-indent-line-to (+ (org-get-indentation) delta)))
20369 (forward-line)))))))
20370 (skip-blanks
20371 (function
20372 ;; Return beginning of first non-blank line, starting from
20373 ;; line at POS.
20374 (lambda (pos)
20375 (save-excursion
20376 (goto-char pos)
20377 (skip-chars-forward " \r\t\n")
20378 (point-at-bol)))))
20379 beg end)
20380 ;; Determine boundaries of changes.
20381 (if (org-region-active-p)
20382 (setq beg (funcall skip-blanks (region-beginning))
20383 end (copy-marker (region-end)))
20384 (setq beg (funcall skip-blanks (point-at-bol))
20385 end (copy-marker (point-at-eol))))
20386 ;; Depending on the starting line, choose an action on the text
20387 ;; between BEG and END.
20388 (org-with-limited-levels
20389 (save-excursion
20390 (goto-char beg)
20391 (cond
20392 ;; Case 1. Start at an item: de-itemize. Note that it only
20393 ;; happens when a region is active: `org-ctrl-c-minus'
20394 ;; would call `org-cycle-list-bullet' otherwise.
20395 ((org-at-item-p)
20396 (while (< (point) end)
20397 (when (org-at-item-p)
20398 (skip-chars-forward " \t")
20399 (delete-region (point) (match-end 0)))
20400 (forward-line)))
20401 ;; Case 2. Start at an heading: convert to items.
20402 ((org-at-heading-p)
20403 (let* ((bul (org-list-bullet-string "-"))
20404 (bul-len (length bul))
20405 ;; Indentation of the first heading. It should be
20406 ;; relative to the indentation of its parent, if any.
20407 (start-ind (save-excursion
20408 (cond
20409 ((not org-adapt-indentation) 0)
20410 ((not (outline-previous-heading)) 0)
20411 (t (length (match-string 0))))))
20412 ;; Level of first heading. Further headings will be
20413 ;; compared to it to determine hierarchy in the list.
20414 (ref-level (org-reduced-level (org-outline-level))))
20415 (while (< (point) end)
20416 (let* ((level (org-reduced-level (org-outline-level)))
20417 (delta (max 0 (- level ref-level))))
20418 ;; If current headline is less indented than the first
20419 ;; one, set it as reference, in order to preserve
20420 ;; subtrees.
20421 (when (< level ref-level) (setq ref-level level))
20422 (replace-match bul t t)
20423 (org-indent-line-to (+ start-ind (* delta bul-len)))
20424 ;; Ensure all text down to END (or SECTION-END) belongs
20425 ;; to the newly created item.
20426 (let ((section-end (save-excursion
20427 (or (outline-next-heading) (point)))))
20428 (forward-line)
20429 (funcall shift-text
20430 (+ start-ind (* (1+ delta) bul-len))
20431 (min end section-end)))))))
20432 ;; Case 3. Normal line with ARG: make the first line of region
20433 ;; an item, and shift indentation of others lines to
20434 ;; set them as item's body.
20435 (arg (let* ((bul (org-list-bullet-string "-"))
20436 (bul-len (length bul))
20437 (ref-ind (org-get-indentation)))
20438 (skip-chars-forward " \t")
20439 (insert bul)
20440 (forward-line)
20441 (while (< (point) end)
20442 ;; Ensure that lines less indented than first one
20443 ;; still get included in item body.
20444 (funcall shift-text
20445 (+ ref-ind bul-len)
20446 (min end (save-excursion (or (outline-next-heading)
20447 (point)))))
20448 (forward-line))))
20449 ;; Case 4. Normal line without ARG: turn each non-item line
20450 ;; into an item.
20452 (while (< (point) end)
20453 (unless (or (org-at-heading-p) (org-at-item-p))
20454 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20455 (replace-match
20456 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20457 (forward-line))))))))
20459 (defun org-toggle-heading (&optional nstars)
20460 "Convert headings to normal text, or items or text to headings.
20461 If there is no active region, only convert the current line.
20463 With a \\[universal-argument] prefix, convert the whole list at
20464 point into heading.
20466 In a region:
20468 - If the first non blank line is a headline, remove the stars
20469 from all headlines in the region.
20471 - If it is a normal line, turn each and every normal line (i.e.,
20472 not an heading or an item) in the region into headings. If you
20473 want to convert only the first line of this region, use one
20474 universal prefix argument.
20476 - If it is a plain list item, turn all plain list items into headings.
20478 When converting a line into a heading, the number of stars is chosen
20479 such that the lines become children of the current entry. However,
20480 when a numeric prefix argument is given, its value determines the
20481 number of stars to add."
20482 (interactive "P")
20483 (let ((skip-blanks
20484 (function
20485 ;; Return beginning of first non-blank line, starting from
20486 ;; line at POS.
20487 (lambda (pos)
20488 (save-excursion
20489 (goto-char pos)
20490 (while (org-at-comment-p) (forward-line))
20491 (skip-chars-forward " \r\t\n")
20492 (point-at-bol)))))
20493 beg end toggled)
20494 ;; Determine boundaries of changes. If a universal prefix has
20495 ;; been given, put the list in a region. If region ends at a bol,
20496 ;; do not consider the last line to be in the region.
20498 (when (and current-prefix-arg (org-at-item-p))
20499 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20500 (org-mark-element))
20502 (if (org-region-active-p)
20503 (setq beg (funcall skip-blanks (region-beginning))
20504 end (copy-marker (save-excursion
20505 (goto-char (region-end))
20506 (if (bolp) (point) (point-at-eol)))))
20507 (setq beg (funcall skip-blanks (point-at-bol))
20508 end (copy-marker (point-at-eol))))
20509 ;; Ensure inline tasks don't count as headings.
20510 (org-with-limited-levels
20511 (save-excursion
20512 (goto-char beg)
20513 (cond
20514 ;; Case 1. Started at an heading: de-star headings.
20515 ((org-at-heading-p)
20516 (while (< (point) end)
20517 (when (org-at-heading-p t)
20518 (looking-at org-outline-regexp) (replace-match "")
20519 (setq toggled t))
20520 (forward-line)))
20521 ;; Case 2. Started at an item: change items into headlines.
20522 ;; One star will be added by `org-list-to-subtree'.
20523 ((org-at-item-p)
20524 (let* ((stars (make-string
20525 ;; subtract the star that will be added again by
20526 ;; `org-list-to-subtree'
20527 (if (numberp nstars) (1- nstars)
20528 (or (org-current-level) 0))
20529 ?*))
20530 (add-stars
20531 (cond (nstars "") ; stars from prefix only
20532 ((equal stars "") "") ; before first heading
20533 (org-odd-levels-only "*") ; inside heading, odd
20534 (t "")))) ; inside heading, oddeven
20535 (while (< (point) end)
20536 (when (org-at-item-p)
20537 ;; Pay attention to cases when region ends before list.
20538 (let* ((struct (org-list-struct))
20539 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20540 (save-restriction
20541 (narrow-to-region (point) list-end)
20542 (insert
20543 (org-list-to-subtree
20544 (org-list-parse-list t)
20545 '(:istart (concat stars add-stars (funcall get-stars depth))
20546 :icount (concat stars add-stars (funcall get-stars depth)))))))
20547 (setq toggled t))
20548 (forward-line))))
20549 ;; Case 3. Started at normal text: make every line an heading,
20550 ;; skipping headlines and items.
20551 (t (let* ((stars
20552 (make-string
20553 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20554 (add-stars
20555 (cond (nstars "") ; stars from prefix only
20556 ((equal stars "") "*") ; before first heading
20557 (org-odd-levels-only "**") ; inside heading, odd
20558 (t "*"))) ; inside heading, oddeven
20559 (rpl (concat stars add-stars " "))
20560 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20561 (while (< (point) (if (equal nstars '(4)) lend end))
20562 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20563 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20564 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20565 (forward-line)))))))
20566 (unless toggled (message "Cannot toggle heading from here"))))
20568 (defun org-meta-return (&optional arg)
20569 "Insert a new heading or wrap a region in a table.
20570 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20571 See the individual commands for more information."
20572 (interactive "P")
20573 (cond
20574 ((run-hook-with-args-until-success 'org-metareturn-hook))
20575 ((or (org-at-drawer-p) (org-at-property-p))
20576 (newline-and-indent))
20577 ((org-at-table-p)
20578 (call-interactively 'org-table-wrap-region))
20579 (t (call-interactively 'org-insert-heading))))
20581 ;;; Menu entries
20583 (defsubst org-in-subtree-not-table-p ()
20584 "Are we in a subtree and not in a table?"
20585 (and (not (org-before-first-heading-p))
20586 (not (org-at-table-p))))
20588 ;; Define the Org-mode menus
20589 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20590 '("Tbl"
20591 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20592 ["Next Field" org-cycle (org-at-table-p)]
20593 ["Previous Field" org-shifttab (org-at-table-p)]
20594 ["Next Row" org-return (org-at-table-p)]
20595 "--"
20596 ["Blank Field" org-table-blank-field (org-at-table-p)]
20597 ["Edit Field" org-table-edit-field (org-at-table-p)]
20598 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20599 "--"
20600 ("Column"
20601 ["Move Column Left" org-metaleft (org-at-table-p)]
20602 ["Move Column Right" org-metaright (org-at-table-p)]
20603 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20604 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20605 ("Row"
20606 ["Move Row Up" org-metaup (org-at-table-p)]
20607 ["Move Row Down" org-metadown (org-at-table-p)]
20608 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20609 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20610 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20611 "--"
20612 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20613 ("Rectangle"
20614 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20615 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20616 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20617 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20618 "--"
20619 ("Calculate"
20620 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20621 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20622 ["Edit Formulas" org-edit-special (org-at-table-p)]
20623 "--"
20624 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20625 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20626 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20627 "--"
20628 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20629 "--"
20630 ["Sum Column/Rectangle" org-table-sum
20631 (or (org-at-table-p) (org-region-active-p))]
20632 ["Which Column?" org-table-current-column (org-at-table-p)])
20633 ["Debug Formulas"
20634 org-table-toggle-formula-debugger
20635 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20636 ["Show Col/Row Numbers"
20637 org-table-toggle-coordinate-overlays
20638 :style toggle
20639 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20640 "--"
20641 ["Create" org-table-create (and (not (org-at-table-p))
20642 org-enable-table-editor)]
20643 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20644 ["Import from File" org-table-import (not (org-at-table-p))]
20645 ["Export to File" org-table-export (org-at-table-p)]
20646 "--"
20647 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20649 (easy-menu-define org-org-menu org-mode-map "Org menu"
20650 '("Org"
20651 ("Show/Hide"
20652 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20653 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20654 ["Sparse Tree..." org-sparse-tree t]
20655 ["Reveal Context" org-reveal t]
20656 ["Show All" show-all t]
20657 "--"
20658 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20659 "--"
20660 ["New Heading" org-insert-heading t]
20661 ("Navigate Headings"
20662 ["Up" outline-up-heading t]
20663 ["Next" outline-next-visible-heading t]
20664 ["Previous" outline-previous-visible-heading t]
20665 ["Next Same Level" outline-forward-same-level t]
20666 ["Previous Same Level" outline-backward-same-level t]
20667 "--"
20668 ["Jump" org-goto t])
20669 ("Edit Structure"
20670 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20671 "--"
20672 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20673 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20674 "--"
20675 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20676 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20677 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20678 "--"
20679 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20680 "--"
20681 ["Copy visible text" org-copy-visible t]
20682 "--"
20683 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20684 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20685 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20686 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20687 "--"
20688 ["Sort Region/Children" org-sort t]
20689 "--"
20690 ["Convert to odd levels" org-convert-to-odd-levels t]
20691 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20692 ("Editing"
20693 ["Emphasis..." org-emphasize t]
20694 ["Edit Source Example" org-edit-special t]
20695 "--"
20696 ["Footnote new/jump" org-footnote-action t]
20697 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20698 ("Archive"
20699 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20700 "--"
20701 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20702 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20703 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20705 "--"
20706 ("Hyperlinks"
20707 ["Store Link (Global)" org-store-link t]
20708 ["Find existing link to here" org-occur-link-in-agenda-files t]
20709 ["Insert Link" org-insert-link t]
20710 ["Follow Link" org-open-at-point t]
20711 "--"
20712 ["Next link" org-next-link t]
20713 ["Previous link" org-previous-link t]
20714 "--"
20715 ["Descriptive Links"
20716 org-toggle-link-display
20717 :style radio
20718 :selected org-descriptive-links
20720 ["Literal Links"
20721 org-toggle-link-display
20722 :style radio
20723 :selected (not org-descriptive-links)])
20724 "--"
20725 ("TODO Lists"
20726 ["TODO/DONE/-" org-todo t]
20727 ("Select keyword"
20728 ["Next keyword" org-shiftright (org-at-heading-p)]
20729 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20730 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20731 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20732 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20733 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20734 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20735 "--"
20736 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20737 :selected org-enforce-todo-dependencies :style toggle :active t]
20738 "Settings for tree at point"
20739 ["Do Children sequentially" org-toggle-ordered-property :style radio
20740 :selected (org-entry-get nil "ORDERED")
20741 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20742 ["Do Children parallel" org-toggle-ordered-property :style radio
20743 :selected (not (org-entry-get nil "ORDERED"))
20744 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20745 "--"
20746 ["Set Priority" org-priority t]
20747 ["Priority Up" org-shiftup t]
20748 ["Priority Down" org-shiftdown t]
20749 "--"
20750 ["Get news from all feeds" org-feed-update-all t]
20751 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20752 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20753 ("TAGS and Properties"
20754 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20755 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20756 "--"
20757 ["Set property" org-set-property (not (org-before-first-heading-p))]
20758 ["Column view of properties" org-columns t]
20759 ["Insert Column View DBlock" org-insert-columns-dblock t])
20760 ("Dates and Scheduling"
20761 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20762 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20763 ("Change Date"
20764 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20765 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20766 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20767 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20768 ["Compute Time Range" org-evaluate-time-range t]
20769 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20770 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20771 "--"
20772 ["Custom time format" org-toggle-time-stamp-overlays
20773 :style radio :selected org-display-custom-times]
20774 "--"
20775 ["Goto Calendar" org-goto-calendar t]
20776 ["Date from Calendar" org-date-from-calendar t]
20777 "--"
20778 ["Start/Restart Timer" org-timer-start t]
20779 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20780 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20781 ["Insert Timer String" org-timer t]
20782 ["Insert Timer Item" org-timer-item t])
20783 ("Logging work"
20784 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20785 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20786 ["Clock out" org-clock-out t]
20787 ["Clock cancel" org-clock-cancel t]
20788 "--"
20789 ["Mark as default task" org-clock-mark-default-task t]
20790 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20791 ["Goto running clock" org-clock-goto t]
20792 "--"
20793 ["Display times" org-clock-display t]
20794 ["Create clock table" org-clock-report t]
20795 "--"
20796 ["Record DONE time"
20797 (progn (setq org-log-done (not org-log-done))
20798 (message "Switching to %s will %s record a timestamp"
20799 (car org-done-keywords)
20800 (if org-log-done "automatically" "not")))
20801 :style toggle :selected org-log-done])
20802 "--"
20803 ["Agenda Command..." org-agenda t]
20804 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20805 ("File List for Agenda")
20806 ("Special views current file"
20807 ["TODO Tree" org-show-todo-tree t]
20808 ["Check Deadlines" org-check-deadlines t]
20809 ["Timeline" org-timeline t]
20810 ["Tags/Property tree" org-match-sparse-tree t])
20811 "--"
20812 ["Export/Publish..." org-export-dispatch t]
20813 ("LaTeX"
20814 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20815 :selected org-cdlatex-mode]
20816 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20817 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20818 ["Modify math symbol" org-cdlatex-math-modify
20819 (org-inside-LaTeX-fragment-p)]
20820 ["Insert citation" org-reftex-citation t]
20821 "--"
20822 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20823 "--"
20824 ("MobileOrg"
20825 ["Push Files and Views" org-mobile-push t]
20826 ["Get Captured and Flagged" org-mobile-pull t]
20827 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20828 "--"
20829 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20830 "--"
20831 ("Documentation"
20832 ["Show Version" org-version t]
20833 ["Info Documentation" org-info t])
20834 ("Customize"
20835 ["Browse Org Group" org-customize t]
20836 "--"
20837 ["Expand This Menu" org-create-customize-menu
20838 (fboundp 'customize-menu-create)])
20839 ["Send bug report" org-submit-bug-report t]
20840 "--"
20841 ("Refresh/Reload"
20842 ["Refresh setup current buffer" org-mode-restart t]
20843 ["Reload Org (after update)" org-reload t]
20844 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20847 (defun org-info (&optional node)
20848 "Read documentation for Org-mode in the info system.
20849 With optional NODE, go directly to that node."
20850 (interactive)
20851 (info (format "(org)%s" (or node ""))))
20853 ;;;###autoload
20854 (defun org-submit-bug-report ()
20855 "Submit a bug report on Org-mode via mail.
20857 Don't hesitate to report any problems or inaccurate documentation.
20859 If you don't have setup sending mail from (X)Emacs, please copy the
20860 output buffer into your mail program, as it gives us important
20861 information about your Org-mode version and configuration."
20862 (interactive)
20863 (require 'reporter)
20864 (org-load-modules-maybe)
20865 (org-require-autoloaded-modules)
20866 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20867 (reporter-submit-bug-report
20868 "emacs-orgmode@gnu.org"
20869 (org-version nil 'full)
20870 (let (list)
20871 (save-window-excursion
20872 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20873 (delete-other-windows)
20874 (erase-buffer)
20875 (insert "You are about to submit a bug report to the Org-mode mailing list.
20877 We would like to add your full Org-mode and Outline configuration to the
20878 bug report. This greatly simplifies the work of the maintainer and
20879 other experts on the mailing list.
20881 HOWEVER, some variables you have customized may contain private
20882 information. The names of customers, colleagues, or friends, might
20883 appear in the form of file names, tags, todo states, or search strings.
20884 If you answer yes to the prompt, you might want to check and remove
20885 such private information before sending the email.")
20886 (add-text-properties (point-min) (point-max) '(face org-warning))
20887 (when (yes-or-no-p "Include your Org-mode configuration ")
20888 (mapatoms
20889 (lambda (v)
20890 (and (boundp v)
20891 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20892 (or (and (symbol-value v)
20893 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20894 (and
20895 (get v 'custom-type) (get v 'standard-value)
20896 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20897 (push v list)))))
20898 (kill-buffer (get-buffer "*Warn about privacy*"))
20899 list))
20900 nil nil
20901 "Remember to cover the basics, that is, what you expected to happen and
20902 what in fact did happen. You don't know how to make a good report? See
20904 http://orgmode.org/manual/Feedback.html#Feedback
20906 Your bug report will be posted to the Org-mode mailing list.
20907 ------------------------------------------------------------------------")
20908 (save-excursion
20909 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20910 (replace-match "\\1Bug: \\3 [\\2]")))))
20913 (defun org-install-agenda-files-menu ()
20914 (let ((bl (buffer-list)))
20915 (save-excursion
20916 (while bl
20917 (set-buffer (pop bl))
20918 (if (derived-mode-p 'org-mode) (setq bl nil)))
20919 (when (derived-mode-p 'org-mode)
20920 (easy-menu-change
20921 '("Org") "File List for Agenda"
20922 (append
20923 (list
20924 ["Edit File List" (org-edit-agenda-file-list) t]
20925 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20926 ["Remove Current File from List" org-remove-file t]
20927 ["Cycle through agenda files" org-cycle-agenda-files t]
20928 ["Occur in all agenda files" org-occur-in-agenda-files t]
20929 "--")
20930 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20932 ;;;; Documentation
20934 (defun org-require-autoloaded-modules ()
20935 (interactive)
20936 (mapc 'require
20937 '(org-agenda org-archive org-attach org-clock org-colview org-id
20938 org-remember org-table org-timer)))
20940 ;;;###autoload
20941 (defun org-reload (&optional uncompiled)
20942 "Reload all org lisp files.
20943 With prefix arg UNCOMPILED, load the uncompiled versions."
20944 (interactive "P")
20945 (require 'loadhist)
20946 (let* ((org-dir (org-find-library-dir "org"))
20947 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20948 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20949 (remove-re (mapconcat 'identity
20950 (mapcar (lambda (f) (concat "^" f "$"))
20951 (list (if (featurep 'xemacs)
20952 "org-colview"
20953 "org-colview-xemacs")
20954 "org" "org-loaddefs" "org-version"))
20955 "\\|"))
20956 (feats (delete-dups
20957 (mapcar 'file-name-sans-extension
20958 (mapcar 'file-name-nondirectory
20959 (delq nil
20960 (mapcar 'feature-file
20961 features))))))
20962 (lfeat (append
20963 (sort
20964 (setq feats
20965 (delq nil (mapcar
20966 (lambda (f)
20967 (if (and (string-match feature-re f)
20968 (not (string-match remove-re f)))
20969 f nil))
20970 feats)))
20971 'string-lessp)
20972 (list "org-version" "org")))
20973 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20974 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20975 load-uncore load-misses)
20976 (setq load-misses
20977 (delq 't
20978 (mapcar (lambda (f)
20979 (or (org-load-noerror-mustsuffix (concat org-dir f))
20980 (and (string= org-dir contrib-dir)
20981 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20982 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20983 (add-to-list 'load-uncore f 'append)
20986 lfeat)))
20987 (if load-uncore
20988 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20989 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20990 (if load-misses
20991 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20992 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20993 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20995 ;;;###autoload
20996 (defun org-customize ()
20997 "Call the customize function with org as argument."
20998 (interactive)
20999 (org-load-modules-maybe)
21000 (org-require-autoloaded-modules)
21001 (customize-browse 'org))
21003 (defun org-create-customize-menu ()
21004 "Create a full customization menu for Org-mode, insert it into the menu."
21005 (interactive)
21006 (org-load-modules-maybe)
21007 (org-require-autoloaded-modules)
21008 (if (fboundp 'customize-menu-create)
21009 (progn
21010 (easy-menu-change
21011 '("Org") "Customize"
21012 `(["Browse Org group" org-customize t]
21013 "--"
21014 ,(customize-menu-create 'org)
21015 ["Set" Custom-set t]
21016 ["Save" Custom-save t]
21017 ["Reset to Current" Custom-reset-current t]
21018 ["Reset to Saved" Custom-reset-saved t]
21019 ["Reset to Standard Settings" Custom-reset-standard t]))
21020 (message "\"Org\"-menu now contains full customization menu"))
21021 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21023 ;;;; Miscellaneous stuff
21025 ;;; Generally useful functions
21027 (defun org-get-at-bol (property)
21028 "Get text property PROPERTY at beginning of line."
21029 (get-text-property (point-at-bol) property))
21031 (defun org-find-text-property-in-string (prop s)
21032 "Return the first non-nil value of property PROP in string S."
21033 (or (get-text-property 0 prop s)
21034 (get-text-property (or (next-single-property-change 0 prop s) 0)
21035 prop s)))
21037 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21038 "Display the given MESSAGE as a warning."
21039 (if (fboundp 'display-warning)
21040 (display-warning 'org message
21041 (if (featurep 'xemacs) 'warning :warning))
21042 (let ((buf (get-buffer-create "*Org warnings*")))
21043 (with-current-buffer buf
21044 (goto-char (point-max))
21045 (insert "Warning (Org): " message)
21046 (unless (bolp)
21047 (newline)))
21048 (display-buffer buf)
21049 (sit-for 0))))
21051 (defun org-eval (form)
21052 "Eval FORM and return result."
21053 (condition-case error
21054 (eval form)
21055 (error (format "%%![Error: %s]" error))))
21057 (defun org-in-clocktable-p ()
21058 "Check if the cursor is in a clocktable."
21059 (let ((pos (point)) start)
21060 (save-excursion
21061 (end-of-line 1)
21062 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21063 (setq start (match-beginning 0))
21064 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21065 (>= (match-end 0) pos)
21066 start))))
21068 (defun org-in-commented-line ()
21069 "Is point in a line starting with `#'?"
21070 (equal (char-after (point-at-bol)) ?#))
21072 (defun org-in-indented-comment-line ()
21073 "Is point in a line starting with `#' after some white space?"
21074 (save-excursion
21075 (save-match-data
21076 (goto-char (point-at-bol))
21077 (looking-at "[ \t]*#"))))
21079 (defun org-in-verbatim-emphasis ()
21080 (save-match-data
21081 (and (org-in-regexp org-emph-re 2)
21082 (>= (point) (match-beginning 3))
21083 (<= (point) (match-end 4))
21084 (member (match-string 3) '("=" "~")))))
21086 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21087 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21088 (if (and marker (marker-buffer marker)
21089 (buffer-live-p (marker-buffer marker)))
21090 (progn
21091 (org-pop-to-buffer-same-window (marker-buffer marker))
21092 (if (or (> marker (point-max)) (< marker (point-min)))
21093 (widen))
21094 (goto-char marker)
21095 (org-show-context 'org-goto))
21096 (if bookmark
21097 (bookmark-jump bookmark)
21098 (error "Cannot find location"))))
21100 (defun org-quote-csv-field (s)
21101 "Quote field for inclusion in CSV material."
21102 (if (string-match "[\",]" s)
21103 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21106 (defun org-force-self-insert (N)
21107 "Needed to enforce self-insert under remapping."
21108 (interactive "p")
21109 (self-insert-command N))
21111 (defun org-string-width (s)
21112 "Compute width of string, ignoring invisible characters.
21113 This ignores character with invisibility property `org-link', and also
21114 characters with property `org-cwidth', because these will become invisible
21115 upon the next fontification round."
21116 (let (b l)
21117 (when (or (eq t buffer-invisibility-spec)
21118 (assq 'org-link buffer-invisibility-spec))
21119 (while (setq b (text-property-any 0 (length s)
21120 'invisible 'org-link s))
21121 (setq s (concat (substring s 0 b)
21122 (substring s (or (next-single-property-change
21123 b 'invisible s) (length s)))))))
21124 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21125 (setq s (concat (substring s 0 b)
21126 (substring s (or (next-single-property-change
21127 b 'org-cwidth s) (length s))))))
21128 (setq l (string-width s) b -1)
21129 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21130 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21133 (defun org-shorten-string (s maxlength)
21134 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21135 If the string is shorter or has length MAXLENGTH, just return the
21136 original string. If it is longer, the functions finds a space in the
21137 string, breaks this string off at that locations and adds three dots
21138 as ellipsis. Including the ellipsis, the string will not be longer
21139 than MAXLENGTH. If finding a good breaking point in the string does
21140 not work, the string is just chopped off in the middle of a word
21141 if necessary."
21142 (if (<= (length s) maxlength)
21144 (let* ((n (max (- maxlength 4) 1))
21145 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21146 (if (string-match re s)
21147 (concat (match-string 1 s) "...")
21148 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21150 (defun org-get-indentation (&optional line)
21151 "Get the indentation of the current line, interpreting tabs.
21152 When LINE is given, assume it represents a line and compute its indentation."
21153 (if line
21154 (if (string-match "^ *" (org-remove-tabs line))
21155 (match-end 0))
21156 (save-excursion
21157 (beginning-of-line 1)
21158 (skip-chars-forward " \t")
21159 (current-column))))
21161 (defun org-get-string-indentation (s)
21162 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21163 (let ((n -1) (i 0) (w tab-width) c)
21164 (catch 'exit
21165 (while (< (setq n (1+ n)) (length s))
21166 (setq c (aref s n))
21167 (cond ((= c ?\ ) (setq i (1+ i)))
21168 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21169 (t (throw 'exit t)))))
21172 (defun org-remove-tabs (s &optional width)
21173 "Replace tabulators in S with spaces.
21174 Assumes that s is a single line, starting in column 0."
21175 (setq width (or width tab-width))
21176 (while (string-match "\t" s)
21177 (setq s (replace-match
21178 (make-string
21179 (- (* width (/ (+ (match-beginning 0) width) width))
21180 (match-beginning 0)) ?\ )
21181 t t s)))
21184 (defun org-fix-indentation (line ind)
21185 "Fix indentation in LINE.
21186 IND is a cons cell with target and minimum indentation.
21187 If the current indentation in LINE is smaller than the minimum,
21188 leave it alone. If it is larger than ind, set it to the target."
21189 (let* ((l (org-remove-tabs line))
21190 (i (org-get-indentation l))
21191 (i1 (car ind)) (i2 (cdr ind)))
21192 (if (>= i i2) (setq l (substring line i2)))
21193 (if (> i1 0)
21194 (concat (make-string i1 ?\ ) l)
21195 l)))
21197 (defun org-remove-indentation (code &optional n)
21198 "Remove the maximum common indentation from the lines in CODE.
21199 N may optionally be the number of spaces to remove."
21200 (with-temp-buffer
21201 (insert code)
21202 (org-do-remove-indentation n)
21203 (buffer-string)))
21205 (defun org-do-remove-indentation (&optional n)
21206 "Remove the maximum common indentation from the buffer."
21207 (untabify (point-min) (point-max))
21208 (let ((min 10000) re)
21209 (if n
21210 (setq min n)
21211 (goto-char (point-min))
21212 (while (re-search-forward "^ *[^ \n]" nil t)
21213 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21214 (unless (or (= min 0) (= min 10000))
21215 (setq re (format "^ \\{%d\\}" min))
21216 (goto-char (point-min))
21217 (while (re-search-forward re nil t)
21218 (replace-match "")
21219 (end-of-line 1))
21220 min)))
21222 (defun org-fill-template (template alist)
21223 "Find each %key of ALIST in TEMPLATE and replace it."
21224 (let ((case-fold-search nil)
21225 entry key value)
21226 (setq alist (sort (copy-sequence alist)
21227 (lambda (a b) (< (length (car a)) (length (car b))))))
21228 (while (setq entry (pop alist))
21229 (setq template
21230 (replace-regexp-in-string
21231 (concat "%" (regexp-quote (car entry)))
21232 (or (cdr entry) "") template t t)))
21233 template))
21235 (defun org-base-buffer (buffer)
21236 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21237 (if (not buffer)
21238 buffer
21239 (or (buffer-base-buffer buffer)
21240 buffer)))
21242 (defun org-trim (s)
21243 "Remove whitespace at beginning and end of string."
21244 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21245 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21248 (defun org-wrap (string &optional width lines)
21249 "Wrap string to either a number of lines, or a width in characters.
21250 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21251 that costs. If there is a word longer than WIDTH, the text is actually
21252 wrapped to the length of that word.
21253 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21254 many lines, whatever width that takes.
21255 The return value is a list of lines, without newlines at the end."
21256 (let* ((words (org-split-string string "[ \t\n]+"))
21257 (maxword (apply 'max (mapcar 'org-string-width words)))
21258 w ll)
21259 (cond (width
21260 (org-do-wrap words (max maxword width)))
21261 (lines
21262 (setq w maxword)
21263 (setq ll (org-do-wrap words maxword))
21264 (if (<= (length ll) lines)
21266 (setq ll words)
21267 (while (> (length ll) lines)
21268 (setq w (1+ w))
21269 (setq ll (org-do-wrap words w)))
21270 ll))
21271 (t (error "Cannot wrap this")))))
21273 (defun org-do-wrap (words width)
21274 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21275 (let (lines line)
21276 (while words
21277 (setq line (pop words))
21278 (while (and words (< (+ (length line) (length (car words))) width))
21279 (setq line (concat line " " (pop words))))
21280 (setq lines (push line lines)))
21281 (nreverse lines)))
21283 (defun org-split-string (string &optional separators)
21284 "Splits STRING into substrings at SEPARATORS.
21285 No empty strings are returned if there are matches at the beginning
21286 and end of string."
21287 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21288 (start 0)
21289 notfirst
21290 (list nil))
21291 (while (and (string-match rexp string
21292 (if (and notfirst
21293 (= start (match-beginning 0))
21294 (< start (length string)))
21295 (1+ start) start))
21296 (< (match-beginning 0) (length string)))
21297 (setq notfirst t)
21298 (or (eq (match-beginning 0) 0)
21299 (and (eq (match-beginning 0) (match-end 0))
21300 (eq (match-beginning 0) start))
21301 (setq list
21302 (cons (substring string start (match-beginning 0))
21303 list)))
21304 (setq start (match-end 0)))
21305 (or (eq start (length string))
21306 (setq list
21307 (cons (substring string start)
21308 list)))
21309 (nreverse list)))
21311 (defun org-quote-vert (s)
21312 "Replace \"|\" with \"\\vert\"."
21313 (while (string-match "|" s)
21314 (setq s (replace-match "\\vert" t t s)))
21317 (defun org-uuidgen-p (s)
21318 "Is S an ID created by UUIDGEN?"
21319 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21321 (defun org-in-src-block-p (&optional inside)
21322 "Whether point is in a code source block.
21323 When INSIDE is non-nil, don't consider we are within a src block
21324 when point is at #+BEGIN_SRC or #+END_SRC."
21325 (let ((case-fold-search t) ov)
21326 (or (and (setq ov (overlays-at (point)))
21327 (memq 'org-block-background
21328 (overlay-properties (car ov))))
21329 (and (not inside)
21330 (save-match-data
21331 (save-excursion
21332 (beginning-of-line)
21333 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21335 (defun org-context ()
21336 "Return a list of contexts of the current cursor position.
21337 If several contexts apply, all are returned.
21338 Each context entry is a list with a symbol naming the context, and
21339 two positions indicating start and end of the context. Possible
21340 contexts are:
21342 :headline anywhere in a headline
21343 :headline-stars on the leading stars in a headline
21344 :todo-keyword on a TODO keyword (including DONE) in a headline
21345 :tags on the TAGS in a headline
21346 :priority on the priority cookie in a headline
21347 :item on the first line of a plain list item
21348 :item-bullet on the bullet/number of a plain list item
21349 :checkbox on the checkbox in a plain list item
21350 :table in an org-mode table
21351 :table-special on a special filed in a table
21352 :table-table in a table.el table
21353 :clocktable in a clocktable
21354 :src-block in a source block
21355 :link on a hyperlink
21356 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21357 :target on a <<target>>
21358 :radio-target on a <<<radio-target>>>
21359 :latex-fragment on a LaTeX fragment
21360 :latex-preview on a LaTeX fragment with overlaid preview image
21362 This function expects the position to be visible because it uses font-lock
21363 faces as a help to recognize the following contexts: :table-special, :link,
21364 and :keyword."
21365 (let* ((f (get-text-property (point) 'face))
21366 (faces (if (listp f) f (list f)))
21367 (case-fold-search t)
21368 (p (point)) clist o)
21369 ;; First the large context
21370 (cond
21371 ((org-at-heading-p t)
21372 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21373 (when (progn
21374 (beginning-of-line 1)
21375 (looking-at org-todo-line-tags-regexp))
21376 (push (org-point-in-group p 1 :headline-stars) clist)
21377 (push (org-point-in-group p 2 :todo-keyword) clist)
21378 (push (org-point-in-group p 4 :tags) clist))
21379 (goto-char p)
21380 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21381 (if (looking-at "\\[#[A-Z0-9]\\]")
21382 (push (org-point-in-group p 0 :priority) clist)))
21384 ((org-at-item-p)
21385 (push (org-point-in-group p 2 :item-bullet) clist)
21386 (push (list :item (point-at-bol)
21387 (save-excursion (org-end-of-item) (point)))
21388 clist)
21389 (and (org-at-item-checkbox-p)
21390 (push (org-point-in-group p 0 :checkbox) clist)))
21392 ((org-at-table-p)
21393 (push (list :table (org-table-begin) (org-table-end)) clist)
21394 (if (memq 'org-formula faces)
21395 (push (list :table-special
21396 (previous-single-property-change p 'face)
21397 (next-single-property-change p 'face)) clist)))
21398 ((org-at-table-p 'any)
21399 (push (list :table-table) clist)))
21400 (goto-char p)
21402 (let ((case-fold-search t))
21403 ;; New the "medium" contexts: clocktables, source blocks
21404 (cond ((org-in-clocktable-p)
21405 (push (list :clocktable
21406 (and (or (looking-at "#\\+BEGIN: clocktable")
21407 (search-backward "#+BEGIN: clocktable" nil t))
21408 (match-beginning 0))
21409 (and (re-search-forward "#\\+END:?" nil t)
21410 (match-end 0))) clist))
21411 ((org-in-src-block-p)
21412 (push (list :src-block
21413 (and (or (looking-at "#\\+BEGIN_SRC")
21414 (search-backward "#+BEGIN_SRC" nil t))
21415 (match-beginning 0))
21416 (and (search-forward "#+END_SRC" nil t)
21417 (match-beginning 0))) clist))))
21418 (goto-char p)
21420 ;; Now the small context
21421 (cond
21422 ((org-at-timestamp-p)
21423 (push (org-point-in-group p 0 :timestamp) clist))
21424 ((memq 'org-link faces)
21425 (push (list :link
21426 (previous-single-property-change p 'face)
21427 (next-single-property-change p 'face)) clist))
21428 ((memq 'org-special-keyword faces)
21429 (push (list :keyword
21430 (previous-single-property-change p 'face)
21431 (next-single-property-change p 'face)) clist))
21432 ((org-at-target-p)
21433 (push (org-point-in-group p 0 :target) clist)
21434 (goto-char (1- (match-beginning 0)))
21435 (if (looking-at org-radio-target-regexp)
21436 (push (org-point-in-group p 0 :radio-target) clist))
21437 (goto-char p))
21438 ((setq o (car (delq nil
21439 (mapcar
21440 (lambda (x)
21441 (if (memq x org-latex-fragment-image-overlays) x))
21442 (overlays-at (point))))))
21443 (push (list :latex-fragment
21444 (overlay-start o) (overlay-end o)) clist)
21445 (push (list :latex-preview
21446 (overlay-start o) (overlay-end o)) clist))
21447 ((org-inside-LaTeX-fragment-p)
21448 ;; FIXME: positions wrong.
21449 (push (list :latex-fragment (point) (point)) clist)))
21451 (setq clist (nreverse (delq nil clist)))
21452 clist))
21454 ;; FIXME: Compare with at-regexp-p Do we need both?
21455 (defun org-in-regexp (re &optional nlines visually)
21456 "Check if point is inside a match of regexp.
21457 Normally only the current line is checked, but you can include NLINES extra
21458 lines both before and after point into the search.
21459 If VISUALLY is set, require that the cursor is not after the match but
21460 really on, so that the block visually is on the match."
21461 (catch 'exit
21462 (let ((pos (point))
21463 (eol (point-at-eol (+ 1 (or nlines 0))))
21464 (inc (if visually 1 0)))
21465 (save-excursion
21466 (beginning-of-line (- 1 (or nlines 0)))
21467 (while (re-search-forward re eol t)
21468 (if (and (<= (match-beginning 0) pos)
21469 (>= (+ inc (match-end 0)) pos))
21470 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21472 (defun org-at-regexp-p (regexp)
21473 "Is point inside a match of REGEXP in the current line?"
21474 (catch 'exit
21475 (save-excursion
21476 (let ((pos (point)) (end (point-at-eol)))
21477 (beginning-of-line 1)
21478 (while (re-search-forward regexp end t)
21479 (if (and (<= (match-beginning 0) pos)
21480 (>= (match-end 0) pos))
21481 (throw 'exit t)))
21482 nil))))
21484 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21485 "Non-nil when point is between matches of START-RE and END-RE.
21487 Also return a non-nil value when point is on one of the matches.
21489 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21490 buffer positions. Default values are the positions of headlines
21491 surrounding the point.
21493 The functions returns a cons cell whose car (resp. cdr) is the
21494 position before START-RE (resp. after END-RE)."
21495 (save-match-data
21496 (let ((pos (point))
21497 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21498 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21499 beg end)
21500 (save-excursion
21501 ;; Point is on a block when on START-RE or if START-RE can be
21502 ;; found before it...
21503 (and (or (org-at-regexp-p start-re)
21504 (re-search-backward start-re limit-up t))
21505 (setq beg (match-beginning 0))
21506 ;; ... and END-RE after it...
21507 (goto-char (match-end 0))
21508 (re-search-forward end-re limit-down t)
21509 (> (setq end (match-end 0)) pos)
21510 ;; ... without another START-RE in-between.
21511 (goto-char (match-beginning 0))
21512 (not (re-search-backward start-re (1+ beg) t))
21513 ;; Return value.
21514 (cons beg end))))))
21516 (defun org-in-block-p (names)
21517 "Non-nil when point belongs to a block whose name belongs to NAMES.
21519 NAMES is a list of strings containing names of blocks.
21521 Return first block name matched, or nil. Beware that in case of
21522 nested blocks, the returned name may not belong to the closest
21523 block from point."
21524 (save-match-data
21525 (catch 'exit
21526 (let ((case-fold-search t)
21527 (lim-up (save-excursion (outline-previous-heading)))
21528 (lim-down (save-excursion (outline-next-heading))))
21529 (mapc (lambda (name)
21530 (let ((n (regexp-quote name)))
21531 (when (org-between-regexps-p
21532 (concat "^[ \t]*#\\+begin_" n)
21533 (concat "^[ \t]*#\\+end_" n)
21534 lim-up lim-down)
21535 (throw 'exit n))))
21536 names))
21537 nil)))
21539 (defun org-occur-in-agenda-files (regexp &optional nlines)
21540 "Call `multi-occur' with buffers for all agenda files."
21541 (interactive "sOrg-files matching: \np")
21542 (let* ((files (org-agenda-files))
21543 (tnames (mapcar 'file-truename files))
21544 (extra org-agenda-text-search-extra-files)
21546 (when (eq (car extra) 'agenda-archives)
21547 (setq extra (cdr extra))
21548 (setq files (org-add-archive-files files)))
21549 (while (setq f (pop extra))
21550 (unless (member (file-truename f) tnames)
21551 (add-to-list 'files f 'append)
21552 (add-to-list 'tnames (file-truename f) 'append)))
21553 (multi-occur
21554 (mapcar (lambda (x)
21555 (with-current-buffer
21556 (or (get-file-buffer x) (find-file-noselect x))
21557 (widen)
21558 (current-buffer)))
21559 files)
21560 regexp)))
21562 (if (boundp 'occur-mode-find-occurrence-hook)
21563 ;; Emacs 23
21564 (add-hook 'occur-mode-find-occurrence-hook
21565 (lambda ()
21566 (when (derived-mode-p 'org-mode)
21567 (org-reveal))))
21568 ;; Emacs 22
21569 (defadvice occur-mode-goto-occurrence
21570 (after org-occur-reveal activate)
21571 (and (derived-mode-p 'org-mode) (org-reveal)))
21572 (defadvice occur-mode-goto-occurrence-other-window
21573 (after org-occur-reveal activate)
21574 (and (derived-mode-p 'org-mode) (org-reveal)))
21575 (defadvice occur-mode-display-occurrence
21576 (after org-occur-reveal activate)
21577 (when (derived-mode-p 'org-mode)
21578 (let ((pos (occur-mode-find-occurrence)))
21579 (with-current-buffer (marker-buffer pos)
21580 (save-excursion
21581 (goto-char pos)
21582 (org-reveal)))))))
21584 (defun org-occur-link-in-agenda-files ()
21585 "Create a link and search for it in the agendas.
21586 The link is not stored in `org-stored-links', it is just created
21587 for the search purpose."
21588 (interactive)
21589 (let ((link (condition-case nil
21590 (org-store-link nil)
21591 (error "Unable to create a link to here"))))
21592 (org-occur-in-agenda-files (regexp-quote link))))
21594 (defun org-reverse-string (string)
21595 "Return the reverse of STRING."
21596 (apply 'string (reverse (string-to-list string))))
21598 (defsubst org-uniquify (list)
21599 "Non-destructively remove duplicate elements from LIST."
21600 (let ((res (copy-sequence list))) (delete-dups res)))
21602 (defun org-uniquify-alist (alist)
21603 "Merge elements of ALIST with the same key.
21605 For example, in this alist:
21607 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21608 => '((a 1 3) (b 2))
21610 merge (a 1) and (a 3) into (a 1 3).
21612 The function returns the new ALIST."
21613 (let (rtn)
21614 (mapc
21615 (lambda (e)
21616 (let (n)
21617 (if (not (assoc (car e) rtn))
21618 (push e rtn)
21619 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21620 (setq rtn (assq-delete-all (car e) rtn))
21621 (push n rtn))))
21622 alist)
21623 rtn))
21625 (defun org-delete-all (elts list)
21626 "Remove all elements in ELTS from LIST."
21627 (while elts
21628 (setq list (delete (pop elts) list)))
21629 list)
21631 (defun org-count (cl-item cl-seq)
21632 "Count the number of occurrences of ITEM in SEQ.
21633 Taken from `count' in cl-seq.el with all keyword arguments removed."
21634 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21635 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21636 (while (< cl-start cl-end)
21637 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21638 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21639 (setq cl-start (1+ cl-start)))
21640 cl-count))
21642 (defun org-remove-if (predicate seq)
21643 "Remove everything from SEQ that fulfills PREDICATE."
21644 (let (res e)
21645 (while seq
21646 (setq e (pop seq))
21647 (if (not (funcall predicate e)) (push e res)))
21648 (nreverse res)))
21650 (defun org-remove-if-not (predicate seq)
21651 "Remove everything from SEQ that does not fulfill PREDICATE."
21652 (let (res e)
21653 (while seq
21654 (setq e (pop seq))
21655 (if (funcall predicate e) (push e res)))
21656 (nreverse res)))
21658 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21659 "Reduce two-argument FUNCTION across SEQ.
21660 Taken from `reduce' in cl-seq.el with all keyword arguments but
21661 \":initial-value\" removed."
21662 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21663 (cadr (memq :initial-value cl-keys)))
21664 (cl-seq (pop cl-seq))
21665 (t (funcall cl-func)))))
21666 (while cl-seq
21667 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21668 cl-accum))
21670 (defun org-back-over-empty-lines ()
21671 "Move backwards over whitespace, to the beginning of the first empty line.
21672 Returns the number of empty lines passed."
21673 (let ((pos (point)))
21674 (if (cdr (assoc 'heading org-blank-before-new-entry))
21675 (skip-chars-backward " \t\n\r")
21676 (unless (eobp)
21677 (forward-line -1)))
21678 (beginning-of-line 2)
21679 (goto-char (min (point) pos))
21680 (count-lines (point) pos)))
21682 (defun org-skip-whitespace ()
21683 (skip-chars-forward " \t\n\r"))
21685 (defun org-point-in-group (point group &optional context)
21686 "Check if POINT is in match-group GROUP.
21687 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21688 match. If the match group does not exist or point is not inside it,
21689 return nil."
21690 (and (match-beginning group)
21691 (>= point (match-beginning group))
21692 (<= point (match-end group))
21693 (if context
21694 (list context (match-beginning group) (match-end group))
21695 t)))
21697 (defun org-switch-to-buffer-other-window (&rest args)
21698 "Switch to buffer in a second window on the current frame.
21699 In particular, do not allow pop-up frames.
21700 Returns the newly created buffer."
21701 (org-no-popups
21702 (apply 'switch-to-buffer-other-window args)))
21704 (defun org-combine-plists (&rest plists)
21705 "Create a single property list from all plists in PLISTS.
21706 The process starts by copying the first list, and then setting properties
21707 from the other lists. Settings in the last list are the most significant
21708 ones and overrule settings in the other lists."
21709 (let ((rtn (copy-sequence (pop plists)))
21710 p v ls)
21711 (while plists
21712 (setq ls (pop plists))
21713 (while ls
21714 (setq p (pop ls) v (pop ls))
21715 (setq rtn (plist-put rtn p v))))
21716 rtn))
21718 (defun org-replace-escapes (string table)
21719 "Replace %-escapes in STRING with values in TABLE.
21720 TABLE is an association list with keys like \"%a\" and string values.
21721 The sequences in STRING may contain normal field width and padding information,
21722 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21723 so values can contain further %-escapes if they are define later in TABLE."
21724 (let ((tbl (copy-alist table))
21725 (case-fold-search nil)
21726 (pchg 0)
21727 e re rpl)
21728 (while (setq e (pop tbl))
21729 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21730 (when (and (cdr e) (string-match re (cdr e)))
21731 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21732 (safe "SREF"))
21733 (add-text-properties 0 3 (list 'sref sref) safe)
21734 (setcdr e (replace-match safe t t (cdr e)))))
21735 (while (string-match re string)
21736 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21737 (cdr e)))
21738 (setq string (replace-match rpl t t string))))
21739 (while (setq pchg (next-property-change pchg string))
21740 (let ((sref (get-text-property pchg 'sref string)))
21741 (when (and sref (string-match "SREF" string pchg))
21742 (setq string (replace-match sref t t string)))))
21743 string))
21745 (defun org-sublist (list start end)
21746 "Return a section of LIST, from START to END.
21747 Counting starts at 1."
21748 (let (rtn (c start))
21749 (setq list (nthcdr (1- start) list))
21750 (while (and list (<= c end))
21751 (push (pop list) rtn)
21752 (setq c (1+ c)))
21753 (nreverse rtn)))
21755 (defun org-find-base-buffer-visiting (file)
21756 "Like `find-buffer-visiting' but always return the base buffer and
21757 not an indirect buffer."
21758 (let ((buf (or (get-file-buffer file)
21759 (find-buffer-visiting file))))
21760 (if buf
21761 (or (buffer-base-buffer buf) buf)
21762 nil)))
21764 (defun org-image-file-name-regexp (&optional extensions)
21765 "Return regexp matching the file names of images.
21766 If EXTENSIONS is given, only match these."
21767 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21768 (image-file-name-regexp)
21769 (let ((image-file-name-extensions
21770 (or extensions
21771 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21772 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21773 (concat "\\."
21774 (regexp-opt (nconc (mapcar 'upcase
21775 image-file-name-extensions)
21776 image-file-name-extensions)
21778 "\\'"))))
21780 (defun org-file-image-p (file &optional extensions)
21781 "Return non-nil if FILE is an image."
21782 (save-match-data
21783 (string-match (org-image-file-name-regexp extensions) file)))
21785 (defun org-get-cursor-date (&optional with-time)
21786 "Return the date at cursor in as a time.
21787 This works in the calendar and in the agenda, anywhere else it just
21788 returns the current time.
21789 If WITH-TIME is non-nil, returns the time of the event at point (in
21790 the agenda) or the current time of the day."
21791 (let (date day defd tp tm hod mod)
21792 (when with-time
21793 (setq tp (get-text-property (point) 'time))
21794 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21795 (setq hod (string-to-number (match-string 1 tp))
21796 mod (string-to-number (match-string 2 tp))))
21797 (or tp (setq hod (nth 2 (decode-time (current-time)))
21798 mod (nth 1 (decode-time (current-time))))))
21799 (cond
21800 ((eq major-mode 'calendar-mode)
21801 (setq date (calendar-cursor-to-date)
21802 defd (encode-time 0 (or mod 0) (or hod 0)
21803 (nth 1 date) (nth 0 date) (nth 2 date))))
21804 ((eq major-mode 'org-agenda-mode)
21805 (setq day (get-text-property (point) 'day))
21806 (if day
21807 (setq date (calendar-gregorian-from-absolute day)
21808 defd (encode-time 0 (or mod 0) (or hod 0)
21809 (nth 1 date) (nth 0 date) (nth 2 date))))))
21810 (or defd (current-time))))
21812 (defun org-mark-subtree (&optional up)
21813 "Mark the current subtree.
21814 This puts point at the start of the current subtree, and mark at
21815 the end. If a numeric prefix UP is given, move up into the
21816 hierarchy of headlines by UP levels before marking the subtree."
21817 (interactive "P")
21818 (org-with-limited-levels
21819 (cond ((org-at-heading-p) (beginning-of-line))
21820 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21821 (t (outline-previous-visible-heading 1))))
21822 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21823 (if (org-called-interactively-p 'any)
21824 (call-interactively 'org-mark-element)
21825 (org-mark-element)))
21828 ;;; Indentation
21830 (defun org-indent-line ()
21831 "Indent line depending on context."
21832 (interactive)
21833 (let* ((pos (point))
21834 (itemp (org-at-item-p))
21835 (case-fold-search t)
21836 (org-drawer-regexp (or org-drawer-regexp "\000"))
21837 (inline-task-p (and (featurep 'org-inlinetask)
21838 (org-inlinetask-in-task-p)))
21839 (inline-re (and inline-task-p
21840 (org-inlinetask-outline-regexp)))
21841 column)
21842 (if (and orgstruct-is-++ (eq pos (point)))
21843 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21844 (indent-according-to-mode))
21845 (beginning-of-line 1)
21846 (cond
21847 ;; Headings
21848 ((looking-at org-outline-regexp) (setq column 0))
21849 ;; Footnote definition
21850 ((looking-at org-footnote-definition-re) (setq column 0))
21851 ;; Literal examples
21852 ((looking-at "[ \t]*:\\( \\|$\\)")
21853 (setq column (org-get-indentation))) ; do nothing
21854 ;; Lists
21855 ((ignore-errors (goto-char (org-in-item-p)))
21856 (setq column (if itemp
21857 (org-get-indentation)
21858 (org-list-item-body-column (point))))
21859 (goto-char pos))
21860 ;; Drawers
21861 ((and (looking-at "[ \t]*:END:")
21862 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21863 (save-excursion
21864 (goto-char (1- (match-beginning 1)))
21865 (setq column (current-column))))
21866 ;; Special blocks
21867 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21868 (save-excursion
21869 (re-search-backward
21870 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21871 (setq column (org-get-indentation (match-string 0))))
21872 ((and (not (looking-at "[ \t]*#\\+begin_"))
21873 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21874 (save-excursion
21875 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21876 (setq column
21877 (cond ((equal (downcase (match-string 1)) "src")
21878 ;; src blocks: let `org-edit-src-exit' handle them
21879 (org-get-indentation))
21880 ((equal (downcase (match-string 1)) "example")
21881 (max (org-get-indentation)
21882 (org-get-indentation (match-string 0))))
21884 (org-get-indentation (match-string 0))))))
21885 ;; This line has nothing special, look at the previous relevant
21886 ;; line to compute indentation
21888 (beginning-of-line 0)
21889 (while (and (not (bobp))
21890 (not (looking-at org-table-line-regexp))
21891 (not (looking-at org-drawer-regexp))
21892 ;; When point started in an inline task, do not move
21893 ;; above task starting line.
21894 (not (and inline-task-p (looking-at inline-re)))
21895 ;; Skip drawers, blocks, empty lines, verbatim,
21896 ;; comments, tables, footnotes definitions, lists,
21897 ;; inline tasks.
21898 (or (and (looking-at "[ \t]*:END:")
21899 (re-search-backward org-drawer-regexp nil t))
21900 (and (looking-at "[ \t]*#\\+end_")
21901 (re-search-backward "[ \t]*#\\+begin_"nil t))
21902 (looking-at "[ \t]*[\n:#|]")
21903 (looking-at org-footnote-definition-re)
21904 (and (not inline-task-p)
21905 (featurep 'org-inlinetask)
21906 (org-inlinetask-in-task-p)
21907 (or (org-inlinetask-goto-beginning) t))))
21908 (beginning-of-line 0))
21909 (cond
21910 ;; There was a list item above.
21911 ((save-excursion
21912 (and (ignore-errors (goto-char (org-in-item-p)))
21913 (goto-char
21914 (org-list-get-top-point (org-list-struct)))))
21915 (looking-at org-list-full-item-re)
21916 (setq column (length (match-string 0))))
21917 ;; There was an heading above.
21918 ((looking-at "\\*+[ \t]+")
21919 (if (not org-adapt-indentation)
21920 (setq column 0)
21921 (goto-char (match-end 0))
21922 (setq column (current-column))))
21923 ;; A drawer had started and is unfinished
21924 ((looking-at org-drawer-regexp)
21925 (goto-char (1- (match-beginning 1)))
21926 (setq column (current-column)))
21927 ;; Else, nothing noticeable found: get indentation and go on.
21928 (t (setq column (org-get-indentation))))))
21929 ;; Now apply indentation and move cursor accordingly
21930 (goto-char pos)
21931 (if (<= (current-column) (current-indentation))
21932 (org-indent-line-to column)
21933 (save-excursion (org-indent-line-to column)))
21934 ;; Special polishing for properties, see `org-property-format'
21935 (setq column (current-column))
21936 (beginning-of-line 1)
21937 (if (looking-at
21938 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21939 (replace-match (concat (match-string 1)
21940 (format org-property-format
21941 (match-string 2) (match-string 3)))
21942 t t))
21943 (org-move-to-column column))))
21945 (defun org-indent-drawer ()
21946 "Indent the drawer at point."
21947 (interactive)
21948 (let ((p (point))
21949 (e (and (save-excursion (re-search-forward ":END:" nil t))
21950 (match-end 0)))
21951 (folded
21952 (save-excursion
21953 (end-of-line)
21954 (when (overlays-at (point))
21955 (member 'invisible (overlay-properties
21956 (car (overlays-at (point)))))))))
21957 (when folded (org-cycle))
21958 (indent-for-tab-command)
21959 (while (and (move-beginning-of-line 2) (< (point) e))
21960 (indent-for-tab-command))
21961 (goto-char p)
21962 (when folded (org-cycle)))
21963 (message "Drawer at point indented"))
21965 (defun org-indent-block ()
21966 "Indent the block at point."
21967 (interactive)
21968 (let ((p (point))
21969 (case-fold-search t)
21970 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21971 (match-end 0)))
21972 (folded
21973 (save-excursion
21974 (end-of-line)
21975 (when (overlays-at (point))
21976 (member 'invisible (overlay-properties
21977 (car (overlays-at (point)))))))))
21978 (when folded (org-cycle))
21979 (indent-for-tab-command)
21980 (while (and (move-beginning-of-line 2) (< (point) e))
21981 (indent-for-tab-command))
21982 (goto-char p)
21983 (when folded (org-cycle)))
21984 (message "Block at point indented"))
21986 (defun org-indent-region (start end)
21987 "Indent region."
21988 (interactive "r")
21989 (save-excursion
21990 (let ((line-end (org-current-line end)))
21991 (goto-char start)
21992 (while (< (org-current-line) line-end)
21993 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21994 (t (call-interactively 'org-indent-line)))
21995 (move-beginning-of-line 2)))))
21998 ;;; Filling
22000 ;; We use our own fill-paragraph and auto-fill functions.
22002 ;; `org-fill-paragraph' relies on adaptive filling and context
22003 ;; checking. Appropriate `fill-prefix' is computed with
22004 ;; `org-adaptive-fill-function'.
22006 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22007 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22008 ;; `org-adaptive-fill-function' value. Internally,
22009 ;; `org-comment-line-break-function' breaks the line.
22011 ;; `org-setup-filling' installs filling and auto-filling related
22012 ;; variables during `org-mode' initialization.
22014 (defun org-setup-filling ()
22015 (interactive)
22016 ;; Prevent auto-fill from inserting unwanted new items.
22017 (when (boundp 'fill-nobreak-predicate)
22018 (org-set-local
22019 'fill-nobreak-predicate
22020 (org-uniquify
22021 (append fill-nobreak-predicate
22022 '(org-fill-paragraph-separate-nobreak-p
22023 org-fill-line-break-nobreak-p
22024 org-fill-paragraph-with-timestamp-nobreak-p)))))
22025 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22026 (org-set-local 'auto-fill-inhibit-regexp nil)
22027 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22028 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22029 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22031 (defvar org-element-paragraph-separate) ; org-element.el
22032 (defun org-fill-paragraph-separate-nobreak-p ()
22033 "Non-nil when a line break at point would insert a new item."
22034 (looking-at (substring org-element-paragraph-separate 1)))
22036 (defun org-fill-line-break-nobreak-p ()
22037 "Non-nil when a line break at point would create an Org line break."
22038 (save-excursion
22039 (skip-chars-backward "[ \t]")
22040 (skip-chars-backward "\\\\")
22041 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22043 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22044 "Non-nil when a line break at point would insert a new item."
22045 (and (org-at-timestamp-p t)
22046 (not (looking-at org-ts-regexp-both))))
22048 (declare-function message-in-body-p "message" ())
22049 (defvar orgtbl-line-start-regexp) ; From org-table.el
22050 (defun org-adaptive-fill-function ()
22051 "Compute a fill prefix for the current line.
22052 Return fill prefix, as a string, or nil if current line isn't
22053 meant to be filled."
22054 (let (prefix)
22055 (catch 'exit
22056 (when (derived-mode-p 'message-mode)
22057 (save-excursion
22058 (beginning-of-line)
22059 (cond ((or (not (message-in-body-p))
22060 (looking-at orgtbl-line-start-regexp))
22061 (throw 'exit nil))
22062 ((looking-at message-cite-prefix-regexp)
22063 (throw 'exit (match-string-no-properties 0)))
22064 ((looking-at org-outline-regexp)
22065 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22066 (org-with-wide-buffer
22067 (let* ((p (line-beginning-position))
22068 (element (save-excursion
22069 (beginning-of-line)
22070 (or (ignore-errors (org-element-at-point))
22071 (user-error "An element cannot be parsed line %d"
22072 (line-number-at-pos (point))))))
22073 (type (org-element-type element))
22074 (post-affiliated (org-element-property :post-affiliated element)))
22075 (unless (and post-affiliated (< p post-affiliated))
22076 (case type
22077 (comment (looking-at "[ \t]*# ?") (match-string 0))
22078 (footnote-definition "")
22079 ((item plain-list)
22080 (make-string (org-list-item-body-column
22081 (or post-affiliated
22082 (org-element-property :begin element)))
22083 ? ))
22084 (paragraph
22085 ;; Fill prefix is usually the same as the current line,
22086 ;; except if the paragraph is at the beginning of an item.
22087 (let ((parent (org-element-property :parent element)))
22088 (cond ((eq (org-element-type parent) 'item)
22089 (make-string (org-list-item-body-column
22090 (org-element-property :begin parent))
22091 ? ))
22092 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22093 (match-string 0))
22094 (t ""))))
22095 (comment-block
22096 ;; Only fill contents if P is within block boundaries.
22097 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22098 (forward-line)
22099 (point)))
22100 (cend (save-excursion
22101 (goto-char (org-element-property :end element))
22102 (skip-chars-backward " \r\t\n")
22103 (line-beginning-position))))
22104 (when (and (>= p cbeg) (< p cend))
22105 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22106 (match-string 0)
22107 "")))))))))))
22109 (declare-function message-goto-body "message" ())
22110 (defvar message-cite-prefix-regexp) ; From message.el
22111 (defun org-fill-paragraph (&optional justify)
22112 "Fill element at point, when applicable.
22114 This function only applies to comment blocks, comments, example
22115 blocks and paragraphs. Also, as a special case, re-align table
22116 when point is at one.
22118 If JUSTIFY is non-nil (interactively, with prefix argument),
22119 justify as well. If `sentence-end-double-space' is non-nil, then
22120 period followed by one space does not end a sentence, so don't
22121 break a line there. The variable `fill-column' controls the
22122 width for filling.
22124 For convenience, when point is at a plain list, an item or
22125 a footnote definition, try to fill the first paragraph within."
22126 (interactive)
22127 (if (and (derived-mode-p 'message-mode)
22128 (or (not (message-in-body-p))
22129 (save-excursion (move-beginning-of-line 1)
22130 (looking-at message-cite-prefix-regexp))))
22131 ;; First ensure filling is correct in message-mode.
22132 (let ((fill-paragraph-function
22133 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22134 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22135 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22136 (paragraph-separate
22137 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22138 (fill-paragraph nil))
22139 (with-syntax-table org-mode-transpose-word-syntax-table
22140 ;; Move to end of line in order to get the first paragraph
22141 ;; within a plain list or a footnote definition.
22142 (let ((element (save-excursion
22143 (end-of-line)
22144 (or (ignore-errors (org-element-at-point))
22145 (user-error "An element cannot be parsed line %d"
22146 (line-number-at-pos (point)))))))
22147 ;; First check if point is in a blank line at the beginning of
22148 ;; the buffer. In that case, ignore filling.
22149 (case (org-element-type element)
22150 ;; Use major mode filling function is src blocks.
22151 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22152 ;; Align Org tables, leave table.el tables as-is.
22153 (table-row (org-table-align) t)
22154 (table
22155 (when (eq (org-element-property :type element) 'org)
22156 (org-table-align))
22158 (paragraph
22159 ;; Paragraphs may contain `line-break' type objects.
22160 (let ((beg (max (point-min)
22161 (org-element-property :contents-begin element)))
22162 (end (min (point-max)
22163 (org-element-property :contents-end element))))
22164 ;; Do nothing if point is at an affiliated keyword.
22165 (if (< (line-end-position) beg) t
22166 (when (derived-mode-p 'message-mode)
22167 ;; In `message-mode', do not fill following citation
22168 ;; in current paragraph nor text before message body.
22169 (let ((body-start (save-excursion (message-goto-body))))
22170 (when body-start (setq beg (max body-start beg))))
22171 (when (save-excursion
22172 (re-search-forward
22173 (concat "^" message-cite-prefix-regexp) end t))
22174 (setq end (match-beginning 0))))
22175 ;; Fill paragraph, taking line breaks into account.
22176 ;; For that, slice the paragraph using line breaks as
22177 ;; separators, and fill the parts in reverse order to
22178 ;; avoid messing with markers.
22179 (save-excursion
22180 (goto-char end)
22181 (mapc
22182 (lambda (pos)
22183 (fill-region-as-paragraph pos (point) justify)
22184 (goto-char pos))
22185 ;; Find the list of ending positions for line breaks
22186 ;; in the current paragraph. Add paragraph
22187 ;; beginning to include first slice.
22188 (nreverse
22189 (cons beg
22190 (org-element-map
22191 (org-element--parse-objects
22192 beg end nil (org-element-restriction 'paragraph))
22193 'line-break
22194 (lambda (lb) (org-element-property :end lb)))))))
22195 t)))
22196 ;; Contents of `comment-block' type elements should be
22197 ;; filled as plain text, but only if point is within block
22198 ;; markers.
22199 (comment-block
22200 (let* ((case-fold-search t)
22201 (beg (save-excursion
22202 (goto-char (org-element-property :begin element))
22203 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22204 (forward-line)
22205 (point)))
22206 (end (save-excursion
22207 (goto-char (org-element-property :end element))
22208 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22209 (line-beginning-position))))
22210 (when (and (>= (point) beg) (< (point) end))
22211 (fill-region-as-paragraph
22212 (save-excursion
22213 (end-of-line)
22214 (re-search-backward "^[ \t]*$" beg 'move)
22215 (line-beginning-position))
22216 (save-excursion
22217 (beginning-of-line)
22218 (re-search-forward "^[ \t]*$" end 'move)
22219 (line-beginning-position))
22220 justify)))
22222 ;; Fill comments.
22223 (comment (fill-comment-paragraph justify))
22224 ;; Ignore every other element.
22225 (otherwise t))))))
22227 (defun org-auto-fill-function ()
22228 "Auto-fill function."
22229 ;; Check if auto-filling is meaningful.
22230 (let ((fc (current-fill-column)))
22231 (when (and fc (> (current-column) fc))
22232 (let* ((fill-prefix (org-adaptive-fill-function))
22233 ;; Enforce empty fill prefix, if required. Otherwise, it
22234 ;; will be computed again.
22235 (adaptive-fill-mode (not (equal fill-prefix ""))))
22236 (when fill-prefix (do-auto-fill))))))
22238 (defun org-comment-line-break-function (&optional soft)
22239 "Break line at point and indent, continuing comment if within one.
22240 The inserted newline is marked hard if variable
22241 `use-hard-newlines' is true, unless optional argument SOFT is
22242 non-nil."
22243 (if soft (insert-and-inherit ?\n) (newline 1))
22244 (save-excursion (forward-char -1) (delete-horizontal-space))
22245 (delete-horizontal-space)
22246 (indent-to-left-margin)
22247 (insert-before-markers-and-inherit fill-prefix))
22250 ;;; Comments
22252 ;; Org comments syntax is quite complex. It requires the entire line
22253 ;; to be just a comment. Also, even with the right syntax at the
22254 ;; beginning of line, some some elements (i.e. verse-block or
22255 ;; example-block) don't accept comments. Usual Emacs comment commands
22256 ;; cannot cope with those requirements. Therefore, Org replaces them.
22258 ;; Org still relies on `comment-dwim', but cannot trust
22259 ;; `comment-only-p'. So, `comment-region-function' and
22260 ;; `uncomment-region-function' both point
22261 ;; to`org-comment-or-uncomment-region'. Eventually,
22262 ;; `org-insert-comment' takes care of insertion of comments at the
22263 ;; beginning of line.
22265 ;; `org-setup-comments-handling' install comments related variables
22266 ;; during `org-mode' initialization.
22268 (defun org-setup-comments-handling ()
22269 (interactive)
22270 (org-set-local 'comment-use-syntax nil)
22271 (org-set-local 'comment-start "# ")
22272 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22273 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22274 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22275 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22277 (defun org-insert-comment ()
22278 "Insert an empty comment above current line.
22279 If the line is empty, insert comment at its beginning."
22280 (beginning-of-line)
22281 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22282 (org-indent-line)
22283 (insert "# "))
22285 (defvar comment-empty-lines) ; From newcomment.el.
22286 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22287 "Comment or uncomment each non-blank line in the region.
22288 Uncomment each non-blank line between BEG and END if it only
22289 contains commented lines. Otherwise, comment them."
22290 (save-restriction
22291 ;; Restrict region
22292 (narrow-to-region (save-excursion (goto-char beg)
22293 (skip-chars-forward " \r\t\n" end)
22294 (line-beginning-position))
22295 (save-excursion (goto-char end)
22296 (skip-chars-backward " \r\t\n" beg)
22297 (line-end-position)))
22298 (let ((uncommentp
22299 ;; UNCOMMENTP is non-nil when every non blank line between
22300 ;; BEG and END is a comment.
22301 (save-excursion
22302 (goto-char (point-min))
22303 (while (and (not (eobp))
22304 (let ((element (org-element-at-point)))
22305 (and (eq (org-element-type element) 'comment)
22306 (goto-char (min (point-max)
22307 (org-element-property
22308 :end element)))))))
22309 (eobp))))
22310 (if uncommentp
22311 ;; Only blank lines and comments in region: uncomment it.
22312 (save-excursion
22313 (goto-char (point-min))
22314 (while (not (eobp))
22315 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22316 (replace-match "" nil nil nil 1))
22317 (forward-line)))
22318 ;; Comment each line in region.
22319 (let ((min-indent (point-max)))
22320 ;; First find the minimum indentation across all lines.
22321 (save-excursion
22322 (goto-char (point-min))
22323 (while (and (not (eobp)) (not (zerop min-indent)))
22324 (unless (looking-at "[ \t]*$")
22325 (setq min-indent (min min-indent (current-indentation))))
22326 (forward-line)))
22327 ;; Then loop over all lines.
22328 (save-excursion
22329 (goto-char (point-min))
22330 (while (not (eobp))
22331 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22332 ;; Don't get fooled by invisible text (e.g. link path)
22333 ;; when moving to column MIN-INDENT.
22334 (let ((buffer-invisibility-spec nil))
22335 (org-move-to-column min-indent t))
22336 (insert comment-start))
22337 (forward-line))))))))
22340 ;;; Planning
22342 ;; This section contains tools to operate on timestamp objects, as
22343 ;; returned by, e.g. `org-element-context'.
22345 (defun org-timestamp-has-time-p (timestamp)
22346 "Non-nil when TIMESTAMP has a time specified."
22347 (org-element-property :hour-start timestamp))
22349 (defun org-timestamp-format (timestamp format &optional end utc)
22350 "Format a TIMESTAMP element into a string.
22352 FORMAT is a format specifier to be passed to
22353 `format-time-string'.
22355 When optional argument END is non-nil, use end of date-range or
22356 time-range, if possible.
22358 When optional argument UTC is non-nil, time will be expressed as
22359 Universal Time."
22360 (format-time-string
22361 format
22362 (apply 'encode-time
22363 (cons 0
22364 (mapcar
22365 (lambda (prop) (or (org-element-property prop timestamp) 0))
22366 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22367 '(:minute-start :hour-start :day-start :month-start
22368 :year-start)))))
22369 utc))
22371 (defun org-timestamp-split-range (timestamp &optional end)
22372 "Extract a timestamp object from a date or time range.
22374 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22375 the end of the range. Otherwise, extract its start.
22377 Return a new timestamp object sharing the same parent as
22378 TIMESTAMP."
22379 (let ((type (org-element-property :type timestamp)))
22380 (if (memq type '(active inactive diary)) timestamp
22381 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22382 ;; Set new type.
22383 (org-element-put-property
22384 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22385 ;; Copy start properties over end properties if END is
22386 ;; non-nil. Otherwise, copy end properties over `start' ones.
22387 (let ((p-alist '((:minute-start . :minute-end)
22388 (:hour-start . :hour-end)
22389 (:day-start . :day-end)
22390 (:month-start . :month-end)
22391 (:year-start . :year-end))))
22392 (dolist (p-cell p-alist)
22393 (org-element-put-property
22394 split-ts
22395 (funcall (if end 'car 'cdr) p-cell)
22396 (org-element-property
22397 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22398 ;; Eventually refresh `:raw-value'.
22399 (org-element-put-property split-ts :raw-value nil)
22400 (org-element-put-property
22401 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22403 (defun org-timestamp-translate (timestamp &optional boundary)
22404 "Apply `org-translate-time' on a TIMESTAMP object.
22405 When optional argument BOUNDARY is non-nil, it is either the
22406 symbol `start' or `end'. In this case, only translate the
22407 starting or ending part of TIMESTAMP if it is a date or time
22408 range. Otherwise, translate both parts."
22409 (if (and (not boundary)
22410 (memq (org-element-property :type timestamp)
22411 '(active-range inactive-range)))
22412 (concat
22413 (org-translate-time
22414 (org-element-property :raw-value
22415 (org-timestamp-split-range timestamp)))
22416 "--"
22417 (org-translate-time
22418 (org-element-property :raw-value
22419 (org-timestamp-split-range timestamp t))))
22420 (org-translate-time
22421 (org-element-property
22422 :raw-value
22423 (if (not boundary) timestamp
22424 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22428 ;;; Other stuff.
22430 (defun org-toggle-fixed-width-section (arg)
22431 "Toggle the fixed-width export.
22432 If there is no active region, the QUOTE keyword at the current headline is
22433 inserted or removed. When present, it causes the text between this headline
22434 and the next to be exported as fixed-width text, and unmodified.
22435 If there is an active region, this command adds or removes a colon as the
22436 first character of this line. If the first character of a line is a colon,
22437 this line is also exported in fixed-width font."
22438 (interactive "P")
22439 (let* ((cc 0)
22440 (regionp (org-region-active-p))
22441 (beg (if regionp (region-beginning) (point)))
22442 (end (if regionp (region-end)))
22443 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22444 (case-fold-search nil)
22445 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22446 off)
22447 (if regionp
22448 (save-excursion
22449 (goto-char beg)
22450 (setq cc (current-column))
22451 (beginning-of-line 1)
22452 (setq off (looking-at re))
22453 (while (> nlines 0)
22454 (setq nlines (1- nlines))
22455 (beginning-of-line 1)
22456 (cond
22457 (arg
22458 (org-move-to-column cc t)
22459 (insert ": \n")
22460 (forward-line -1))
22461 ((and off (looking-at re))
22462 (replace-match "" t t nil 1))
22463 ((not off) (org-move-to-column cc t) (insert ": ")))
22464 (forward-line 1)))
22465 (save-excursion
22466 (org-back-to-heading)
22467 (cond
22468 ((looking-at (format org-heading-keyword-regexp-format
22469 org-quote-string))
22470 (goto-char (match-end 1))
22471 (looking-at (concat " +" org-quote-string))
22472 (replace-match "" t t)
22473 (when (eolp) (insert " ")))
22474 ((looking-at org-outline-regexp)
22475 (goto-char (match-end 0))
22476 (insert org-quote-string " ")))))))
22478 (defun org-reftex-citation ()
22479 "Use reftex-citation to insert a citation into the buffer.
22480 This looks for a line like
22482 #+BIBLIOGRAPHY: foo plain option:-d
22484 and derives from it that foo.bib is the bibliography file relevant
22485 for this document. It then installs the necessary environment for RefTeX
22486 to work in this buffer and calls `reftex-citation' to insert a citation
22487 into the buffer.
22489 Export of such citations to both LaTeX and HTML is handled by the contributed
22490 package org-exp-bibtex by Taru Karttunen."
22491 (interactive)
22492 (let ((reftex-docstruct-symbol 'rds)
22493 (reftex-cite-format "\\cite{%l}")
22494 rds bib)
22495 (save-excursion
22496 (save-restriction
22497 (widen)
22498 (let ((case-fold-search t)
22499 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22500 (if (not (save-excursion
22501 (or (re-search-forward re nil t)
22502 (re-search-backward re nil t))))
22503 (error "No bibliography defined in file")
22504 (setq bib (concat (match-string 1) ".bib")
22505 rds (list (list 'bib bib)))))))
22506 (call-interactively 'reftex-citation)))
22508 ;;;; Functions extending outline functionality
22510 (defun org-beginning-of-line (&optional arg)
22511 "Go to the beginning of the current line. If that is invisible, continue
22512 to a visible line beginning. This makes the function of C-a more intuitive.
22513 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22514 first attempt, and only move to after the tags when the cursor is already
22515 beyond the end of the headline."
22516 (interactive "P")
22517 (let ((pos (point))
22518 (special (if (consp org-special-ctrl-a/e)
22519 (car org-special-ctrl-a/e)
22520 org-special-ctrl-a/e))
22521 refpos)
22522 (if (org-bound-and-true-p visual-line-mode)
22523 (beginning-of-visual-line 1)
22524 (beginning-of-line 1))
22525 (if (and arg (fboundp 'move-beginning-of-line))
22526 (call-interactively 'move-beginning-of-line)
22527 (if (bobp)
22529 (backward-char 1)
22530 (if (org-truely-invisible-p)
22531 (while (and (not (bobp)) (org-truely-invisible-p))
22532 (backward-char 1)
22533 (beginning-of-line 1))
22534 (forward-char 1))))
22535 (when special
22536 (cond
22537 ((and (looking-at org-complex-heading-regexp)
22538 (= (char-after (match-end 1)) ?\ ))
22539 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22540 (point-at-eol)))
22541 (goto-char
22542 (if (eq special t)
22543 (cond ((> pos refpos) refpos)
22544 ((= pos (point)) refpos)
22545 (t (point)))
22546 (cond ((> pos (point)) (point))
22547 ((not (eq last-command this-command)) (point))
22548 (t refpos)))))
22549 ((org-at-item-p)
22550 ;; Being at an item and not looking at an the item means point
22551 ;; was previously moved to beginning of a visual line, which
22552 ;; doesn't contain the item. Therefore, do nothing special,
22553 ;; just stay here.
22554 (when (looking-at org-list-full-item-re)
22555 ;; Set special position at first white space character after
22556 ;; bullet, and check-box, if any.
22557 (let ((after-bullet
22558 (let ((box (match-end 3)))
22559 (if (not box) (match-end 1)
22560 (let ((after (char-after box)))
22561 (if (and after (= after ? )) (1+ box) box))))))
22562 ;; Special case: Move point to special position when
22563 ;; currently after it or at beginning of line.
22564 (if (eq special t)
22565 (when (or (> pos after-bullet) (= (point) pos))
22566 (goto-char after-bullet))
22567 ;; Reversed case: Move point to special position when
22568 ;; point was already at beginning of line and command is
22569 ;; repeated.
22570 (when (and (= (point) pos) (eq last-command this-command))
22571 (goto-char after-bullet))))))))
22572 (org-no-warnings
22573 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22575 (defun org-end-of-line (&optional arg)
22576 "Go to the end of the line.
22577 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22578 tags on the first attempt, and only move to after the tags when
22579 the cursor is already beyond the end of the headline."
22580 (interactive "P")
22581 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22582 org-special-ctrl-a/e))
22583 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22584 'end-of-visual-line)
22585 ((fboundp 'move-end-of-line) 'move-end-of-line)
22586 (t 'end-of-line))))
22587 (if (or (not special) arg) (call-interactively move-fun)
22588 (let* ((element (save-excursion (beginning-of-line)
22589 (org-element-at-point)))
22590 (type (org-element-type element)))
22591 (cond
22592 ((memq type '(headline inlinetask))
22593 (let ((pos (point)))
22594 (beginning-of-line 1)
22595 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22596 (if (eq special t)
22597 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22598 (goto-char (match-beginning 1))
22599 (goto-char (match-end 0)))
22600 (if (or (< pos (match-end 0))
22601 (not (eq this-command last-command)))
22602 (goto-char (match-end 0))
22603 (goto-char (match-beginning 1))))
22604 (call-interactively move-fun))))
22605 ((org-element-property :hiddenp element)
22606 ;; If element is hidden, `move-end-of-line' would put point
22607 ;; after it. Use `end-of-line' to stay on current line.
22608 (call-interactively 'end-of-line))
22609 (t (call-interactively move-fun)))))
22610 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22612 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22613 (define-key org-mode-map "\C-e" 'org-end-of-line)
22615 (defun org-backward-sentence (&optional arg)
22616 "Go to beginning of sentence, or beginning of table field.
22617 This will call `backward-sentence' or `org-table-beginning-of-field',
22618 depending on context."
22619 (interactive "P")
22620 (cond
22621 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22622 (t (call-interactively 'backward-sentence))))
22624 (defun org-forward-sentence (&optional arg)
22625 "Go to end of sentence, or end of table field.
22626 This will call `forward-sentence' or `org-table-end-of-field',
22627 depending on context."
22628 (interactive "P")
22629 (cond
22630 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22631 (t (call-interactively 'forward-sentence))))
22633 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22634 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22636 (defun org-kill-line (&optional arg)
22637 "Kill line, to tags or end of line."
22638 (interactive "P")
22639 (cond
22640 ((or (not org-special-ctrl-k)
22641 (bolp)
22642 (not (org-at-heading-p)))
22643 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22644 org-ctrl-k-protect-subtree)
22645 (if (or (eq org-ctrl-k-protect-subtree 'error)
22646 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22647 (user-error "C-k aborted as it would kill a hidden subtree")))
22648 (call-interactively
22649 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22650 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22651 (kill-region (point) (match-beginning 1))
22652 (org-set-tags nil t))
22653 (t (kill-region (point) (point-at-eol)))))
22655 (define-key org-mode-map "\C-k" 'org-kill-line)
22657 (defun org-yank (&optional arg)
22658 "Yank. If the kill is a subtree, treat it specially.
22659 This command will look at the current kill and check if is a single
22660 subtree, or a series of subtrees[1]. If it passes the test, and if the
22661 cursor is at the beginning of a line or after the stars of a currently
22662 empty headline, then the yank is handled specially. How exactly depends
22663 on the value of the following variables, both set by default.
22665 org-yank-folded-subtrees
22666 When set, the subtree(s) will be folded after insertion, but only
22667 if doing so would now swallow text after the yanked text.
22669 org-yank-adjusted-subtrees
22670 When set, the subtree will be promoted or demoted in order to
22671 fit into the local outline tree structure, which means that the level
22672 will be adjusted so that it becomes the smaller one of the two
22673 *visible* surrounding headings.
22675 Any prefix to this command will cause `yank' to be called directly with
22676 no special treatment. In particular, a simple \\[universal-argument] prefix \
22677 will just
22678 plainly yank the text as it is.
22680 \[1] The test checks if the first non-white line is a heading
22681 and if there are no other headings with fewer stars."
22682 (interactive "P")
22683 (org-yank-generic 'yank arg))
22685 (defun org-yank-generic (command arg)
22686 "Perform some yank-like command.
22688 This function implements the behavior described in the `org-yank'
22689 documentation. However, it has been generalized to work for any
22690 interactive command with similar behavior."
22692 ;; pretend to be command COMMAND
22693 (setq this-command command)
22695 (if arg
22696 (call-interactively command)
22698 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22699 (and (org-kill-is-subtree-p)
22700 (or (bolp)
22701 (and (looking-at "[ \t]*$")
22702 (string-match
22703 "\\`\\*+\\'"
22704 (buffer-substring (point-at-bol) (point)))))))
22705 swallowp)
22706 (cond
22707 ((and subtreep org-yank-folded-subtrees)
22708 (let ((beg (point))
22709 end)
22710 (if (and subtreep org-yank-adjusted-subtrees)
22711 (org-paste-subtree nil nil 'for-yank)
22712 (call-interactively command))
22714 (setq end (point))
22715 (goto-char beg)
22716 (when (and (bolp) subtreep
22717 (not (setq swallowp
22718 (org-yank-folding-would-swallow-text beg end))))
22719 (org-with-limited-levels
22720 (or (looking-at org-outline-regexp)
22721 (re-search-forward org-outline-regexp-bol end t))
22722 (while (and (< (point) end) (looking-at org-outline-regexp))
22723 (hide-subtree)
22724 (org-cycle-show-empty-lines 'folded)
22725 (condition-case nil
22726 (outline-forward-same-level 1)
22727 (error (goto-char end))))))
22728 (when swallowp
22729 (message
22730 "Inserted text not folded because that would swallow text"))
22732 (goto-char end)
22733 (skip-chars-forward " \t\n\r")
22734 (beginning-of-line 1)
22735 (push-mark beg 'nomsg)))
22736 ((and subtreep org-yank-adjusted-subtrees)
22737 (let ((beg (point-at-bol)))
22738 (org-paste-subtree nil nil 'for-yank)
22739 (push-mark beg 'nomsg)))
22741 (call-interactively command))))))
22743 (defun org-yank-folding-would-swallow-text (beg end)
22744 "Would hide-subtree at BEG swallow any text after END?"
22745 (let (level)
22746 (org-with-limited-levels
22747 (save-excursion
22748 (goto-char beg)
22749 (when (or (looking-at org-outline-regexp)
22750 (re-search-forward org-outline-regexp-bol end t))
22751 (setq level (org-outline-level)))
22752 (goto-char end)
22753 (skip-chars-forward " \t\r\n\v\f")
22754 (if (or (eobp)
22755 (and (bolp) (looking-at org-outline-regexp)
22756 (<= (org-outline-level) level)))
22757 nil ; Nothing would be swallowed
22758 t))))) ; something would swallow
22760 (define-key org-mode-map "\C-y" 'org-yank)
22762 (defun org-truely-invisible-p ()
22763 "Check if point is at a character currently not visible.
22764 This version does not only check the character property, but also
22765 `visible-mode'."
22766 ;; Early versions of noutline don't have `outline-invisible-p'.
22767 (if (org-bound-and-true-p visible-mode)
22769 (outline-invisible-p)))
22771 (defun org-invisible-p2 ()
22772 "Check if point is at a character currently not visible."
22773 (save-excursion
22774 (if (and (eolp) (not (bobp))) (backward-char 1))
22775 ;; Early versions of noutline don't have `outline-invisible-p'.
22776 (outline-invisible-p)))
22778 (defun org-back-to-heading (&optional invisible-ok)
22779 "Call `outline-back-to-heading', but provide a better error message."
22780 (condition-case nil
22781 (outline-back-to-heading invisible-ok)
22782 (error (error "Before first headline at position %d in buffer %s"
22783 (point) (current-buffer)))))
22785 (defun org-before-first-heading-p ()
22786 "Before first heading?"
22787 (save-excursion
22788 (end-of-line)
22789 (null (re-search-backward org-outline-regexp-bol nil t))))
22791 (defun org-at-heading-p (&optional ignored)
22792 (outline-on-heading-p t))
22793 ;; Compatibility alias with Org versions < 7.8.03
22794 (defalias 'org-on-heading-p 'org-at-heading-p)
22796 (defun org-at-comment-p nil
22797 "Is cursor in a line starting with a # character?"
22798 (save-excursion
22799 (beginning-of-line)
22800 (looking-at "^#")))
22802 (defun org-at-drawer-p nil
22803 "Is cursor at a drawer keyword?"
22804 (save-excursion
22805 (move-beginning-of-line 1)
22806 (looking-at org-drawer-regexp)))
22808 (defun org-at-block-p nil
22809 "Is cursor at a block keyword?"
22810 (save-excursion
22811 (move-beginning-of-line 1)
22812 (looking-at org-block-regexp)))
22814 (defun org-point-at-end-of-empty-headline ()
22815 "If point is at the end of an empty headline, return t, else nil.
22816 If the heading only contains a TODO keyword, it is still still considered
22817 empty."
22818 (and (looking-at "[ \t]*$")
22819 (when org-todo-line-regexp
22820 (save-excursion
22821 (beginning-of-line 1)
22822 (let ((case-fold-search nil))
22823 (looking-at org-todo-line-regexp)
22824 (string= (match-string 3) ""))))))
22826 (defun org-at-heading-or-item-p ()
22827 (or (org-at-heading-p) (org-at-item-p)))
22829 (defun org-at-target-p ()
22830 (or (org-in-regexp org-radio-target-regexp)
22831 (org-in-regexp org-target-regexp)))
22832 ;; Compatibility alias with Org versions < 7.8.03
22833 (defalias 'org-on-target-p 'org-at-target-p)
22835 (defun org-up-heading-all (arg)
22836 "Move to the heading line of which the present line is a subheading.
22837 This function considers both visible and invisible heading lines.
22838 With argument, move up ARG levels."
22839 (if (fboundp 'outline-up-heading-all)
22840 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22841 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22843 (defun org-up-heading-safe ()
22844 "Move to the heading line of which the present line is a subheading.
22845 This version will not throw an error. It will return the level of the
22846 headline found, or nil if no higher level is found.
22848 Also, this function will be a lot faster than `outline-up-heading',
22849 because it relies on stars being the outline starters. This can really
22850 make a significant difference in outlines with very many siblings."
22851 (let (start-level re)
22852 (org-back-to-heading t)
22853 (setq start-level (funcall outline-level))
22854 (if (equal start-level 1)
22856 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22857 (if (re-search-backward re nil t)
22858 (funcall outline-level)))))
22860 (defun org-first-sibling-p ()
22861 "Is this heading the first child of its parents?"
22862 (interactive)
22863 (let ((re org-outline-regexp-bol)
22864 level l)
22865 (unless (org-at-heading-p t)
22866 (user-error "Not at a heading"))
22867 (setq level (funcall outline-level))
22868 (save-excursion
22869 (if (not (re-search-backward re nil t))
22871 (setq l (funcall outline-level))
22872 (< l level)))))
22874 (defun org-goto-sibling (&optional previous)
22875 "Goto the next sibling, even if it is invisible.
22876 When PREVIOUS is set, go to the previous sibling instead. Returns t
22877 when a sibling was found. When none is found, return nil and don't
22878 move point."
22879 (let ((fun (if previous 're-search-backward 're-search-forward))
22880 (pos (point))
22881 (re org-outline-regexp-bol)
22882 level l)
22883 (when (condition-case nil (org-back-to-heading t) (error nil))
22884 (setq level (funcall outline-level))
22885 (catch 'exit
22886 (or previous (forward-char 1))
22887 (while (funcall fun re nil t)
22888 (setq l (funcall outline-level))
22889 (when (< l level) (goto-char pos) (throw 'exit nil))
22890 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22891 (goto-char pos)
22892 nil))))
22894 (defun org-show-siblings ()
22895 "Show all siblings of the current headline."
22896 (save-excursion
22897 (while (org-goto-sibling) (org-flag-heading nil)))
22898 (save-excursion
22899 (while (org-goto-sibling 'previous)
22900 (org-flag-heading nil))))
22902 (defun org-goto-first-child ()
22903 "Goto the first child, even if it is invisible.
22904 Return t when a child was found. Otherwise don't move point and
22905 return nil."
22906 (let (level (pos (point)) (re org-outline-regexp-bol))
22907 (when (condition-case nil (org-back-to-heading t) (error nil))
22908 (setq level (outline-level))
22909 (forward-char 1)
22910 (if (and (re-search-forward re nil t) (> (outline-level) level))
22911 (progn (goto-char (match-beginning 0)) t)
22912 (goto-char pos) nil))))
22914 (defun org-show-hidden-entry ()
22915 "Show an entry where even the heading is hidden."
22916 (save-excursion
22917 (org-show-entry)))
22919 (defun org-flag-heading (flag &optional entry)
22920 "Flag the current heading. FLAG non-nil means make invisible.
22921 When ENTRY is non-nil, show the entire entry."
22922 (save-excursion
22923 (org-back-to-heading t)
22924 ;; Check if we should show the entire entry
22925 (if entry
22926 (progn
22927 (org-show-entry)
22928 (save-excursion
22929 (and (outline-next-heading)
22930 (org-flag-heading nil))))
22931 (outline-flag-region (max (point-min) (1- (point)))
22932 (save-excursion (outline-end-of-heading) (point))
22933 flag))))
22935 (defun org-get-next-sibling ()
22936 "Move to next heading of the same level, and return point.
22937 If there is no such heading, return nil.
22938 This is like outline-next-sibling, but invisible headings are ok."
22939 (let ((level (funcall outline-level)))
22940 (outline-next-heading)
22941 (while (and (not (eobp)) (> (funcall outline-level) level))
22942 (outline-next-heading))
22943 (if (or (eobp) (< (funcall outline-level) level))
22945 (point))))
22947 (defun org-get-last-sibling ()
22948 "Move to previous heading of the same level, and return point.
22949 If there is no such heading, return nil."
22950 (let ((opoint (point))
22951 (level (funcall outline-level)))
22952 (outline-previous-heading)
22953 (when (and (/= (point) opoint) (outline-on-heading-p t))
22954 (while (and (> (funcall outline-level) level)
22955 (not (bobp)))
22956 (outline-previous-heading))
22957 (if (< (funcall outline-level) level)
22959 (point)))))
22961 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22962 "Goto to the end of a subtree."
22963 ;; This contains an exact copy of the original function, but it uses
22964 ;; `org-back-to-heading', to make it work also in invisible
22965 ;; trees. And is uses an invisible-ok argument.
22966 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22967 ;; Furthermore, when used inside Org, finding the end of a large subtree
22968 ;; with many children and grandchildren etc, this can be much faster
22969 ;; than the outline version.
22970 (org-back-to-heading invisible-ok)
22971 (let ((first t)
22972 (level (funcall outline-level)))
22973 (if (and (derived-mode-p 'org-mode) (< level 1000))
22974 ;; A true heading (not a plain list item), in Org-mode
22975 ;; This means we can easily find the end by looking
22976 ;; only for the right number of stars. Using a regexp to do
22977 ;; this is so much faster than using a Lisp loop.
22978 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22979 (forward-char 1)
22980 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22981 ;; something else, do it the slow way
22982 (while (and (not (eobp))
22983 (or first (> (funcall outline-level) level)))
22984 (setq first nil)
22985 (outline-next-heading)))
22986 (unless to-heading
22987 (if (memq (preceding-char) '(?\n ?\^M))
22988 (progn
22989 ;; Go to end of line before heading
22990 (forward-char -1)
22991 (if (memq (preceding-char) '(?\n ?\^M))
22992 ;; leave blank line before heading
22993 (forward-char -1))))))
22994 (point))
22996 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22997 "Use Org version in org-mode, for dramatic speed-up."
22998 (if (derived-mode-p 'org-mode)
22999 (progn
23000 (org-end-of-subtree nil t)
23001 (unless (eobp) (backward-char 1)))
23002 ad-do-it))
23004 (defun org-end-of-meta-data-and-drawers ()
23005 "Jump to the first text after meta data and drawers in the current entry.
23006 This will move over empty lines, lines with planning time stamps,
23007 clocking lines, and drawers."
23008 (org-back-to-heading t)
23009 (let ((end (save-excursion (outline-next-heading) (point)))
23010 (re (concat "\\(" org-drawer-regexp "\\)"
23011 "\\|" "[ \t]*" org-keyword-time-regexp)))
23012 (forward-line 1)
23013 (while (re-search-forward re end t)
23014 (if (not (match-end 1))
23015 ;; empty or planning line
23016 (forward-line 1)
23017 ;; a drawer, find the end
23018 (re-search-forward "^[ \t]*:END:" end 'move)
23019 (forward-line 1)))
23020 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23021 (point)))
23023 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23024 "Move forward to the ARG'th subheading at same level as this one.
23025 Stop at the first and last subheadings of a superior heading.
23026 Normally this only looks at visible headings, but when INVISIBLE-OK is
23027 non-nil it will also look at invisible ones."
23028 (interactive "p")
23029 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23030 (if (and arg (< arg 0))
23031 (goto-char (point-min))
23032 (outline-next-heading))
23033 (org-at-heading-p)
23034 (let ((level (- (match-end 0) (match-beginning 0) 1))
23035 (f (if (and arg (< arg 0))
23036 're-search-backward
23037 're-search-forward))
23038 (count (if arg (abs arg) 1))
23039 (result (point)))
23040 (while (and (prog1 (> count 0)
23041 (forward-char (if (and arg (< arg 0)) -1 1)))
23042 (funcall f org-outline-regexp-bol nil 'move))
23043 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23044 (cond ((< l level) (setq count 0))
23045 ((and (= l level)
23046 (or invisible-ok
23047 (progn
23048 (goto-char (line-beginning-position))
23049 (not (outline-invisible-p)))))
23050 (setq count (1- count))
23051 (when (eq l level)
23052 (setq result (point)))))))
23053 (goto-char result))
23054 (beginning-of-line 1)))
23056 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23057 "Move backward to the ARG'th subheading at same level as this one.
23058 Stop at the first and last subheadings of a superior heading."
23059 (interactive "p")
23060 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23062 (defun org-next-block (arg &optional backward block-regexp)
23063 "Jump to the next block.
23064 With a prefix argument ARG, jump forward ARG many source blocks.
23065 When BACKWARD is non-nil, jump to the previous block.
23066 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23067 (interactive "p")
23068 (let ((re (or block-regexp org-block-regexp))
23069 (re-search-fn (or (and backward 're-search-backward)
23070 're-search-forward)))
23071 (if (looking-at re) (forward-char 1))
23072 (condition-case nil
23073 (funcall re-search-fn re nil nil arg)
23074 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23075 (goto-char (match-beginning 0)) (org-show-context)))
23077 (defun org-previous-block (arg &optional block-regexp)
23078 "Jump to the previous block.
23079 With a prefix argument ARG, jump backward ARG many source blocks.
23080 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23081 (interactive "p")
23082 (org-next-block arg t block-regexp))
23084 (defun org-forward-element ()
23085 "Move forward by one element.
23086 Move to the next element at the same level, when possible."
23087 (interactive)
23088 (cond ((eobp) (user-error "Cannot move further down"))
23089 ((org-with-limited-levels (org-at-heading-p))
23090 (let ((origin (point)))
23091 (goto-char (org-end-of-subtree nil t))
23092 (unless (org-with-limited-levels (org-at-heading-p))
23093 (goto-char origin)
23094 (user-error "Cannot move further down"))))
23096 (let* ((elem (org-element-at-point))
23097 (end (org-element-property :end elem))
23098 (parent (org-element-property :parent elem)))
23099 (if (and parent (= (org-element-property :contents-end parent) end))
23100 (goto-char (org-element-property :end parent))
23101 (goto-char end))))))
23103 (defun org-backward-element ()
23104 "Move backward by one element.
23105 Move to the previous element at the same level, when possible."
23106 (interactive)
23107 (cond ((bobp) (user-error "Cannot move further up"))
23108 ((org-with-limited-levels (org-at-heading-p))
23109 ;; At a headline, move to the previous one, if any, or stay
23110 ;; here.
23111 (let ((origin (point)))
23112 (org-with-limited-levels (org-backward-heading-same-level 1))
23113 ;; When current headline has no sibling above, move to its
23114 ;; parent.
23115 (when (= (point) origin)
23116 (or (org-with-limited-levels (org-up-heading-safe))
23117 (progn (goto-char origin)
23118 (user-error "Cannot move further up"))))))
23120 (let* ((trail (org-element-at-point 'keep-trail))
23121 (elem (car trail))
23122 (prev-elem (nth 1 trail))
23123 (beg (org-element-property :begin elem)))
23124 (cond
23125 ;; Move to beginning of current element if point isn't
23126 ;; there already.
23127 ((/= (point) beg) (goto-char beg))
23128 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23129 ((org-before-first-heading-p) (goto-char (point-min)))
23130 (t (org-back-to-heading)))))))
23132 (defun org-up-element ()
23133 "Move to upper element."
23134 (interactive)
23135 (if (org-with-limited-levels (org-at-heading-p))
23136 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23137 (let* ((elem (org-element-at-point))
23138 (parent (org-element-property :parent elem)))
23139 (if parent (goto-char (org-element-property :begin parent))
23140 (if (org-with-limited-levels (org-before-first-heading-p))
23141 (user-error "No surrounding element")
23142 (org-with-limited-levels (org-back-to-heading)))))))
23144 (defvar org-element-greater-elements)
23145 (defun org-down-element ()
23146 "Move to inner element."
23147 (interactive)
23148 (let ((element (org-element-at-point)))
23149 (cond
23150 ((memq (org-element-type element) '(plain-list table))
23151 (goto-char (org-element-property :contents-begin element))
23152 (forward-char))
23153 ((memq (org-element-type element) org-element-greater-elements)
23154 ;; If contents are hidden, first disclose them.
23155 (when (org-element-property :hiddenp element) (org-cycle))
23156 (goto-char (or (org-element-property :contents-begin element)
23157 (user-error "No content for this element"))))
23158 (t (user-error "No inner element")))))
23160 (defun org-drag-element-backward ()
23161 "Move backward element at point."
23162 (interactive)
23163 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23164 (let* ((trail (org-element-at-point 'keep-trail))
23165 (elem (car trail))
23166 (prev-elem (nth 1 trail)))
23167 ;; Error out if no previous element or previous element is
23168 ;; a parent of the current one.
23169 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23170 (user-error "Cannot drag element backward")
23171 (let ((pos (point)))
23172 (org-element-swap-A-B prev-elem elem)
23173 (goto-char (+ (org-element-property :begin prev-elem)
23174 (- pos (org-element-property :begin elem)))))))))
23176 (defun org-drag-element-forward ()
23177 "Move forward element at point."
23178 (interactive)
23179 (let* ((pos (point))
23180 (elem (org-element-at-point)))
23181 (when (= (point-max) (org-element-property :end elem))
23182 (user-error "Cannot drag element forward"))
23183 (goto-char (org-element-property :end elem))
23184 (let ((next-elem (org-element-at-point)))
23185 (when (or (org-element-nested-p elem next-elem)
23186 (and (eq (org-element-type next-elem) 'headline)
23187 (not (eq (org-element-type elem) 'headline))))
23188 (goto-char pos)
23189 (user-error "Cannot drag element forward"))
23190 ;; Compute new position of point: it's shifted by NEXT-ELEM
23191 ;; body's length (without final blanks) and by the length of
23192 ;; blanks between ELEM and NEXT-ELEM.
23193 (let ((size-next (- (save-excursion
23194 (goto-char (org-element-property :end next-elem))
23195 (skip-chars-backward " \r\t\n")
23196 (forward-line)
23197 ;; Small correction if buffer doesn't end
23198 ;; with a newline character.
23199 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23200 (org-element-property :begin next-elem)))
23201 (size-blank (- (org-element-property :end elem)
23202 (save-excursion
23203 (goto-char (org-element-property :end elem))
23204 (skip-chars-backward " \r\t\n")
23205 (forward-line)
23206 (point)))))
23207 (org-element-swap-A-B elem next-elem)
23208 (goto-char (+ pos size-next size-blank))))))
23210 (defun org-drag-line-forward (arg)
23211 "Drag the line at point ARG lines forward."
23212 (interactive "p")
23213 (dotimes (n (abs arg))
23214 (let ((c (current-column)))
23215 (if (< 0 arg)
23216 (progn
23217 (beginning-of-line 2)
23218 (transpose-lines 1)
23219 (beginning-of-line 0))
23220 (transpose-lines 1)
23221 (beginning-of-line -1))
23222 (org-move-to-column c))))
23224 (defun org-drag-line-backward (arg)
23225 "Drag the line at point ARG lines backward."
23226 (interactive "p")
23227 (org-drag-line-forward (- arg)))
23229 (defun org-mark-element ()
23230 "Put point at beginning of this element, mark at end.
23232 Interactively, if this command is repeated or (in Transient Mark
23233 mode) if the mark is active, it marks the next element after the
23234 ones already marked."
23235 (interactive)
23236 (let (deactivate-mark)
23237 (if (and (org-called-interactively-p 'any)
23238 (or (and (eq last-command this-command) (mark t))
23239 (and transient-mark-mode mark-active)))
23240 (set-mark
23241 (save-excursion
23242 (goto-char (mark))
23243 (goto-char (org-element-property :end (org-element-at-point)))))
23244 (let ((element (org-element-at-point)))
23245 (end-of-line)
23246 (push-mark (org-element-property :end element) t t)
23247 (goto-char (org-element-property :begin element))))))
23249 (defun org-narrow-to-element ()
23250 "Narrow buffer to current element."
23251 (interactive)
23252 (let ((elem (org-element-at-point)))
23253 (cond
23254 ((eq (car elem) 'headline)
23255 (narrow-to-region
23256 (org-element-property :begin elem)
23257 (org-element-property :end elem)))
23258 ((memq (car elem) org-element-greater-elements)
23259 (narrow-to-region
23260 (org-element-property :contents-begin elem)
23261 (org-element-property :contents-end elem)))
23263 (narrow-to-region
23264 (org-element-property :begin elem)
23265 (org-element-property :end elem))))))
23267 (defun org-transpose-element ()
23268 "Transpose current and previous elements, keeping blank lines between.
23269 Point is moved after both elements."
23270 (interactive)
23271 (org-skip-whitespace)
23272 (let ((end (org-element-property :end (org-element-at-point))))
23273 (org-drag-element-backward)
23274 (goto-char end)))
23276 (defun org-unindent-buffer ()
23277 "Un-indent the visible part of the buffer.
23278 Relative indentation (between items, inside blocks, etc.) isn't
23279 modified."
23280 (interactive)
23281 (unless (eq major-mode 'org-mode)
23282 (user-error "Cannot un-indent a buffer not in Org mode"))
23283 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23284 unindent-tree ; For byte-compiler.
23285 (unindent-tree
23286 (function
23287 (lambda (contents)
23288 (mapc
23289 (lambda (element)
23290 (if (memq (org-element-type element) '(headline section))
23291 (funcall unindent-tree (org-element-contents element))
23292 (save-excursion
23293 (save-restriction
23294 (narrow-to-region
23295 (org-element-property :begin element)
23296 (org-element-property :end element))
23297 (org-do-remove-indentation)))))
23298 (reverse contents))))))
23299 (funcall unindent-tree (org-element-contents parse-tree))))
23301 (defun org-show-subtree ()
23302 "Show everything after this heading at deeper levels."
23303 (interactive)
23304 (outline-flag-region
23305 (point)
23306 (save-excursion
23307 (org-end-of-subtree t t))
23308 nil))
23310 (defun org-show-entry ()
23311 "Show the body directly following this heading.
23312 Show the heading too, if it is currently invisible."
23313 (interactive)
23314 (save-excursion
23315 (condition-case nil
23316 (progn
23317 (org-back-to-heading t)
23318 (outline-flag-region
23319 (max (point-min) (1- (point)))
23320 (save-excursion
23321 (if (re-search-forward
23322 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23323 (match-beginning 1)
23324 (point-max)))
23325 nil)
23326 (org-cycle-hide-drawers 'children))
23327 (error nil))))
23329 (defun org-make-options-regexp (kwds &optional extra)
23330 "Make a regular expression for keyword lines."
23331 (concat
23332 "^#\\+\\("
23333 (mapconcat 'regexp-quote kwds "\\|")
23334 (if extra (concat "\\|" extra))
23335 "\\):[ \t]*\\(.*\\)"))
23337 ;; Make isearch reveal the necessary context
23338 (defun org-isearch-end ()
23339 "Reveal context after isearch exits."
23340 (when isearch-success ; only if search was successful
23341 (if (featurep 'xemacs)
23342 ;; Under XEmacs, the hook is run in the correct place,
23343 ;; we directly show the context.
23344 (org-show-context 'isearch)
23345 ;; In Emacs the hook runs *before* restoring the overlays.
23346 ;; So we have to use a one-time post-command-hook to do this.
23347 ;; (Emacs 22 has a special variable, see function `org-mode')
23348 (unless (and (boundp 'isearch-mode-end-hook-quit)
23349 isearch-mode-end-hook-quit)
23350 ;; Only when the isearch was not quitted.
23351 (org-add-hook 'post-command-hook 'org-isearch-post-command
23352 'append 'local)))
23353 (org-fix-ellipsis-at-bol)))
23355 (defun org-isearch-post-command ()
23356 "Remove self from hook, and show context."
23357 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23358 (org-show-context 'isearch))
23361 ;;;; Integration with and fixes for other packages
23363 ;;; Imenu support
23365 (defvar org-imenu-markers nil
23366 "All markers currently used by Imenu.")
23367 (make-variable-buffer-local 'org-imenu-markers)
23369 (defun org-imenu-new-marker (&optional pos)
23370 "Return a new marker for use by Imenu, and remember the marker."
23371 (let ((m (make-marker)))
23372 (move-marker m (or pos (point)))
23373 (push m org-imenu-markers)
23376 (defun org-imenu-get-tree ()
23377 "Produce the index for Imenu."
23378 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23379 (setq org-imenu-markers nil)
23380 (let* ((n org-imenu-depth)
23381 (re (concat "^" (org-get-limited-outline-regexp)))
23382 (subs (make-vector (1+ n) nil))
23383 (last-level 0)
23384 m level head0 head)
23385 (save-excursion
23386 (save-restriction
23387 (widen)
23388 (goto-char (point-max))
23389 (while (re-search-backward re nil t)
23390 (setq level (org-reduced-level (funcall outline-level)))
23391 (when (and (<= level n)
23392 (looking-at org-complex-heading-regexp)
23393 (setq head0 (org-match-string-no-properties 4)))
23394 (setq head (org-link-display-format head0)
23395 m (org-imenu-new-marker))
23396 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23397 (if (>= level last-level)
23398 (push (cons head m) (aref subs level))
23399 (push (cons head (aref subs (1+ level))) (aref subs level))
23400 (loop for i from (1+ level) to n do (aset subs i nil)))
23401 (setq last-level level)))))
23402 (aref subs 1)))
23404 (eval-after-load "imenu"
23405 '(progn
23406 (add-hook 'imenu-after-jump-hook
23407 (lambda ()
23408 (if (derived-mode-p 'org-mode)
23409 (org-show-context 'org-goto))))))
23411 (defun org-link-display-format (link)
23412 "Replace a link with its the description.
23413 If there is no description, use the link target."
23414 (save-match-data
23415 (if (string-match org-bracket-link-analytic-regexp link)
23416 (replace-match (if (match-end 5)
23417 (match-string 5 link)
23418 (concat (match-string 1 link)
23419 (match-string 3 link)))
23420 nil t link)
23421 link)))
23423 (defun org-toggle-link-display ()
23424 "Toggle the literal or descriptive display of links."
23425 (interactive)
23426 (if org-descriptive-links
23427 (progn (org-remove-from-invisibility-spec '(org-link))
23428 (org-restart-font-lock)
23429 (setq org-descriptive-links nil))
23430 (progn (add-to-invisibility-spec '(org-link))
23431 (org-restart-font-lock)
23432 (setq org-descriptive-links t))))
23434 ;; Speedbar support
23436 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23437 "Overlay marking the agenda restriction line in speedbar.")
23438 (overlay-put org-speedbar-restriction-lock-overlay
23439 'face 'org-agenda-restriction-lock)
23440 (overlay-put org-speedbar-restriction-lock-overlay
23441 'help-echo "Agendas are currently limited to this item.")
23442 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23444 (defun org-speedbar-set-agenda-restriction ()
23445 "Restrict future agenda commands to the location at point in speedbar.
23446 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23447 (interactive)
23448 (require 'org-agenda)
23449 (let (p m tp np dir txt)
23450 (cond
23451 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23452 'org-imenu t))
23453 (setq m (get-text-property p 'org-imenu-marker))
23454 (with-current-buffer (marker-buffer m)
23455 (goto-char m)
23456 (org-agenda-set-restriction-lock 'subtree)))
23457 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23458 'speedbar-function 'speedbar-find-file))
23459 (setq tp (previous-single-property-change
23460 (1+ p) 'speedbar-function)
23461 np (next-single-property-change
23462 tp 'speedbar-function)
23463 dir (speedbar-line-directory)
23464 txt (buffer-substring-no-properties (or tp (point-min))
23465 (or np (point-max))))
23466 (with-current-buffer (find-file-noselect
23467 (let ((default-directory dir))
23468 (expand-file-name txt)))
23469 (unless (derived-mode-p 'org-mode)
23470 (user-error "Cannot restrict to non-Org-mode file"))
23471 (org-agenda-set-restriction-lock 'file)))
23472 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23473 (move-overlay org-speedbar-restriction-lock-overlay
23474 (point-at-bol) (point-at-eol))
23475 (setq current-prefix-arg nil)
23476 (org-agenda-maybe-redo)))
23478 (eval-after-load "speedbar"
23479 '(progn
23480 (speedbar-add-supported-extension ".org")
23481 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23482 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23483 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23484 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23485 (add-hook 'speedbar-visiting-tag-hook
23486 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23488 ;;; Fixes and Hacks for problems with other packages
23490 ;; Make flyspell not check words in links, to not mess up our keymap
23491 (defvar org-element-affiliated-keywords) ; From org-element.el
23492 (defvar org-element-block-name-alist) ; From org-element.el
23493 (defun org-mode-flyspell-verify ()
23494 "Don't let flyspell put overlays at active buttons, or on
23495 {todo,all-time,additional-option-like}-keywords."
23496 (require 'org-element) ; For `org-element-affiliated-keywords'
23497 (let ((pos (max (1- (point)) (point-min)))
23498 (word (thing-at-point 'word)))
23499 (and (not (get-text-property pos 'keymap))
23500 (not (get-text-property pos 'org-no-flyspell))
23501 (not (member word org-todo-keywords-1))
23502 (not (member word org-all-time-keywords))
23503 (not (member word org-options-keywords))
23504 (not (member word (mapcar 'car org-startup-options)))
23505 (not (member-ignore-case word org-element-affiliated-keywords))
23506 (not (member-ignore-case word (org-get-export-keywords)))
23507 (not (member-ignore-case
23508 word (mapcar 'car org-element-block-name-alist)))
23509 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23511 (defun org-remove-flyspell-overlays-in (beg end)
23512 "Remove flyspell overlays in region."
23513 (and (org-bound-and-true-p flyspell-mode)
23514 (fboundp 'flyspell-delete-region-overlays)
23515 (flyspell-delete-region-overlays beg end))
23516 (add-text-properties beg end '(org-no-flyspell t)))
23518 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23519 (eval-after-load "bookmark"
23520 '(if (boundp 'bookmark-after-jump-hook)
23521 ;; We can use the hook
23522 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23523 ;; Hook not available, use advice
23524 (defadvice bookmark-jump (after org-make-visible activate)
23525 "Make the position visible."
23526 (org-bookmark-jump-unhide))))
23528 ;; Make sure saveplace shows the location if it was hidden
23529 (eval-after-load "saveplace"
23530 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23531 "Make the position visible."
23532 (org-bookmark-jump-unhide)))
23534 ;; Make sure ecb shows the location if it was hidden
23535 (eval-after-load "ecb"
23536 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23537 "Make hierarchy visible when jumping into location from ECB tree buffer."
23538 (if (derived-mode-p 'org-mode)
23539 (org-show-context))))
23541 (defun org-bookmark-jump-unhide ()
23542 "Unhide the current position, to show the bookmark location."
23543 (and (derived-mode-p 'org-mode)
23544 (or (outline-invisible-p)
23545 (save-excursion (goto-char (max (point-min) (1- (point))))
23546 (outline-invisible-p)))
23547 (org-show-context 'bookmark-jump)))
23549 ;; Make session.el ignore our circular variable
23550 (eval-after-load "session"
23551 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23553 ;;;; Finish up
23555 (provide 'org)
23557 (run-hooks 'org-load-hook)
23559 ;;; org.el ends here