Remove two unused functions
[org-mode.git] / lisp / org.el
blob48f362fe0fc3012b5ad99f917b4f171b8318189e
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/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro `org-with-limited-levels'.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches a headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (unless (boundp 'calendar-view-holidays-initially-flag)
107 (org-defvaralias 'calendar-view-holidays-initially-flag
108 'view-calendar-holidays-initially))
109 (unless (boundp 'calendar-view-diary-initially-flag)
110 (org-defvaralias 'calendar-view-diary-initially-flag
111 'view-diary-entries-initially))
112 (unless (boundp 'diary-fancy-buffer)
113 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
115 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
116 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
117 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
118 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
121 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "ox-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-table-set-constants "org-table" ())
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
182 ;;;###autoload
183 (defun org-babel-load-file (file &optional compile)
184 "Load Emacs Lisp source code blocks in the Org-mode FILE.
185 This function exports the source code using `org-babel-tangle'
186 and then loads the resulting file using `load-file'. With prefix
187 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
188 file to byte-code before it is loaded."
189 (interactive "fFile to load: \nP")
190 (require 'ob-core)
191 (let* ((age (lambda (file)
192 (float-time
193 (time-subtract (current-time)
194 (nth 5 (or (file-attributes (file-truename file))
195 (file-attributes file)))))))
196 (base-name (file-name-sans-extension file))
197 (exported-file (concat base-name ".el")))
198 ;; tangle if the org-mode file is newer than the elisp file
199 (unless (and (file-exists-p exported-file)
200 (> (funcall age file) (funcall age exported-file)))
201 (org-babel-tangle-file file exported-file "emacs-lisp"))
202 (message "%s %s"
203 (if compile
204 (progn (byte-compile-file exported-file 'load)
205 "Compiled and loaded")
206 (progn (load-file exported-file) "Loaded"))
207 exported-file)))
209 (defcustom org-babel-load-languages '((emacs-lisp . t))
210 "Languages which can be evaluated in Org-mode buffers.
211 This list can be used to load support for any of the languages
212 below, note that each language will depend on a different set of
213 system executables and/or Emacs modes. When a language is
214 \"loaded\", then code blocks in that language can be evaluated
215 with `org-babel-execute-src-block' bound by default to C-c
216 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
217 be set to remove code block evaluation from the C-c C-c
218 keybinding. By default only Emacs Lisp (which has no
219 requirements) is loaded."
220 :group 'org-babel
221 :set 'org-babel-do-load-languages
222 :version "24.1"
223 :type '(alist :tag "Babel Languages"
224 :key-type
225 (choice
226 (const :tag "Awk" awk)
227 (const :tag "C" C)
228 (const :tag "R" R)
229 (const :tag "Asymptote" asymptote)
230 (const :tag "Calc" calc)
231 (const :tag "Clojure" clojure)
232 (const :tag "CSS" css)
233 (const :tag "Ditaa" ditaa)
234 (const :tag "Dot" dot)
235 (const :tag "Emacs Lisp" emacs-lisp)
236 (const :tag "Fortran" fortran)
237 (const :tag "Gnuplot" gnuplot)
238 (const :tag "Haskell" haskell)
239 (const :tag "IO" io)
240 (const :tag "Java" java)
241 (const :tag "Javascript" js)
242 (const :tag "LaTeX" latex)
243 (const :tag "Ledger" ledger)
244 (const :tag "Lilypond" lilypond)
245 (const :tag "Lisp" lisp)
246 (const :tag "Makefile" makefile)
247 (const :tag "Maxima" maxima)
248 (const :tag "Matlab" matlab)
249 (const :tag "Mscgen" mscgen)
250 (const :tag "Ocaml" ocaml)
251 (const :tag "Octave" octave)
252 (const :tag "Org" org)
253 (const :tag "Perl" perl)
254 (const :tag "Pico Lisp" picolisp)
255 (const :tag "PlantUML" plantuml)
256 (const :tag "Python" python)
257 (const :tag "Ruby" ruby)
258 (const :tag "Sass" sass)
259 (const :tag "Scala" scala)
260 (const :tag "Scheme" scheme)
261 (const :tag "Screen" screen)
262 (const :tag "Shell Script" sh)
263 (const :tag "Shen" shen)
264 (const :tag "Sql" sql)
265 (const :tag "Sqlite" sqlite))
266 :value-type (boolean :tag "Activate" :value t)))
268 ;;;; Customization variables
269 (defcustom org-clone-delete-id nil
270 "Remove ID property of clones of a subtree.
271 When non-nil, clones of a subtree don't inherit the ID property.
272 Otherwise they inherit the ID property with a new unique
273 identifier."
274 :type 'boolean
275 :version "24.1"
276 :group 'org-id)
278 ;;; Version
279 (org-check-version)
281 ;;;###autoload
282 (defun org-version (&optional here full message)
283 "Show the org-mode version in the echo area.
284 With prefix argument HERE, insert it at point.
285 When FULL is non-nil, use a verbose version string.
286 When MESSAGE is non-nil, display a message with the version."
287 (interactive "P")
288 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
289 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
290 (load-suffixes (list ".el"))
291 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
292 (org-trash (or
293 (and (fboundp 'org-release) (fboundp 'org-git-version))
294 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
295 (load-suffixes save-load-suffixes)
296 (org-version (org-release))
297 (git-version (org-git-version))
298 (version (format "Org-mode version %s (%s @ %s)"
299 org-version
300 git-version
301 (if org-install-dir
302 (if (string= org-dir org-install-dir)
303 org-install-dir
304 (concat "mixed installation! " org-install-dir " and " org-dir))
305 "org-loaddefs.el can not be found!")))
306 (_version (if full version org-version)))
307 (if (org-called-interactively-p 'interactive)
308 (if here
309 (insert version)
310 (message version))
311 (if message (message _version))
312 _version)))
314 (defconst org-version (org-version))
316 ;;; Compatibility constants
318 ;;; The custom variables
320 (defgroup org nil
321 "Outline-based notes management and organizer."
322 :tag "Org"
323 :group 'outlines
324 :group 'calendar)
326 (defcustom org-mode-hook nil
327 "Mode hook for Org-mode, run after the mode was turned on."
328 :group 'org
329 :type 'hook)
331 (defcustom org-load-hook nil
332 "Hook that is run after org.el has been loaded."
333 :group 'org
334 :type 'hook)
336 (defcustom org-log-buffer-setup-hook nil
337 "Hook that is run after an Org log buffer is created."
338 :group 'org
339 :version "24.1"
340 :type 'hook)
342 (defvar org-modules) ; defined below
343 (defvar org-modules-loaded nil
344 "Have the modules been loaded already?")
346 (defun org-load-modules-maybe (&optional force)
347 "Load all extensions listed in `org-modules'."
348 (when (or force (not org-modules-loaded))
349 (mapc (lambda (ext)
350 (condition-case nil (require ext)
351 (error (message "Problems while trying to load feature `%s'" ext))))
352 org-modules)
353 (setq org-modules-loaded t)))
355 (defun org-set-modules (var value)
356 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
357 (set var value)
358 (when (featurep 'org)
359 (org-load-modules-maybe 'force)))
361 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
362 "Modules that should always be loaded together with org.el.
364 If a description starts with <C>, the file is not part of Emacs
365 and loading it will require that you have downloaded and properly
366 installed the Org mode distribution.
368 You can also use this system to load external packages (i.e. neither Org
369 core modules, nor modules from the CONTRIB directory). Just add symbols
370 to the end of the list. If the package is called org-xyz.el, then you need
371 to add the symbol `xyz', and the package must have a call to:
373 \(provide 'org-xyz)
375 For export specific modules, see also `org-export-backends'."
376 :group 'org
377 :set 'org-set-modules
378 :version "24.4"
379 :package-version '(Org . "8.0")
380 :type
381 '(set :greedy t
382 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
383 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
384 (const :tag " crypt: Encryption of subtrees" org-crypt)
385 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
386 (const :tag " docview: Links to doc-view buffers" org-docview)
387 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
388 (const :tag " habit: Track your consistency with habits" org-habit)
389 (const :tag " id: Global IDs for identifying entries" org-id)
390 (const :tag " info: Links to Info nodes" org-info)
391 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
392 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
393 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
394 (const :tag " mouse: Additional mouse support" org-mouse)
395 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
396 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
397 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
399 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
400 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
401 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
402 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
403 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
404 (const :tag "C collector: Collect properties into tables" org-collector)
405 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
406 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
407 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
408 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
409 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
410 (const :tag "C eval: Include command output as text" org-eval)
411 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
412 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
413 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
414 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
415 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
416 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
417 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
418 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
419 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
420 (const :tag "C mac-message: Links to messages in Apple Mail" org-mac-message)
421 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
422 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
423 (const :tag "C mew: Links to Mew folders/messages" org-mew)
424 (const :tag "C mtags: Support for muse-like tags" org-mtags)
425 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
426 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
427 (const :tag "C registry: A registry for Org-mode links" org-registry)
428 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
429 (const :tag "C secretary: Team management with org-mode" org-secretary)
430 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
431 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
432 (const :tag "C track: Keep up with Org-mode development" org-track)
433 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
434 (const :tag "C vm: Links to VM folders/messages" org-vm)
435 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
436 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
437 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
439 (defvar org-export-registered-backends) ; From ox.el
440 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
441 (defcustom org-export-backends '(ascii html icalendar latex)
442 "List of export back-ends that should be always available.
444 If a description starts with <C>, the file is not part of Emacs
445 and loading it will require that you have downloaded and properly
446 installed the Org mode distribution.
448 Unlike to `org-modules', libraries in this list will not be
449 loaded along with Org, but only once the export framework is
450 needed.
452 This variable needs to be set before org.el is loaded. If you
453 need to make a change while Emacs is running, use the customize
454 interface or run the following code, where VALUE stands for the
455 new value of the variable, after updating it:
457 \(progn
458 \(setq org-export-registered-backends
459 \(org-remove-if-not
460 \(lambda (backend)
461 \(or (memq backend val)
462 \(catch 'parentp
463 \(mapc
464 \(lambda (b)
465 \(and (org-export-derived-backend-p b (car backend))
466 \(throw 'parentp t)))
467 val)
468 nil)))
469 org-export-registered-backends))
470 \(let ((new-list (mapcar 'car org-export-registered-backends)))
471 \(dolist (backend val)
472 \(cond
473 \((not (load (format \"ox-%s\" backend) t t))
474 \(message \"Problems while trying to load export back-end `%s'\"
475 backend))
476 \((not (memq backend new-list)) (push backend new-list))))
477 \(set-default var new-list)))
479 Adding a back-end to this list will also pull the back-end it
480 depends on, if any."
481 :group 'org
482 :group 'org-export
483 :version "24.4"
484 :package-version '(Org . "8.0")
485 :initialize 'custom-initialize-set
486 :set (lambda (var val)
487 (if (not (featurep 'ox)) (set-default var val)
488 ;; Any back-end not required anymore (not present in VAL and not
489 ;; a parent of any back-end in the new value) is removed from the
490 ;; list of registered back-ends.
491 (setq org-export-registered-backends
492 (org-remove-if-not
493 (lambda (backend)
494 (or (memq backend val)
495 (catch 'parentp
496 (mapc
497 (lambda (b)
498 (and (org-export-derived-backend-p b (car backend))
499 (throw 'parentp t)))
500 val)
501 nil)))
502 org-export-registered-backends))
503 ;; Now build NEW-LIST of both new back-ends and required
504 ;; parents.
505 (let ((new-list (mapcar 'car org-export-registered-backends)))
506 (dolist (backend val)
507 (cond
508 ((not (load (format "ox-%s" backend) t t))
509 (message "Problems while trying to load export back-end `%s'"
510 backend))
511 ((not (memq backend new-list)) (push backend new-list))))
512 ;; Set VAR to that list with fixed dependencies.
513 (set-default var new-list))))
514 :type '(set :greedy t
515 (const :tag " ascii Export buffer to ASCII format" ascii)
516 (const :tag " beamer Export buffer to Beamer presentation" beamer)
517 (const :tag " html Export buffer to HTML format" html)
518 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
519 (const :tag " latex Export buffer to LaTeX format" latex)
520 (const :tag " man Export buffer to MAN format" man)
521 (const :tag " md Export buffer to Markdown format" md)
522 (const :tag " odt Export buffer to ODT format" odt)
523 (const :tag " org Export buffer to Org format" org)
524 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
525 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
526 (const :tag "C deck Export buffer to deck.js presentations" deck)
527 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
528 (const :tag "C groff Export buffer to Groff format" groff)
529 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
530 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
531 (const :tag "C s5 Export buffer to s5 presentations" s5)
532 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
534 (eval-after-load 'ox
535 '(mapc
536 (lambda (backend)
537 (condition-case nil (require (intern (format "ox-%s" backend)))
538 (error (message "Problems while trying to load export back-end `%s'"
539 backend))))
540 org-export-backends))
542 (defcustom org-support-shift-select nil
543 "Non-nil means make shift-cursor commands select text when possible.
545 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
546 start selecting a region, or enlarge regions started in this way.
547 In Org-mode, in special contexts, these same keys are used for
548 other purposes, important enough to compete with shift selection.
549 Org tries to balance these needs by supporting `shift-select-mode'
550 outside these special contexts, under control of this variable.
552 The default of this variable is nil, to avoid confusing behavior. Shifted
553 cursor keys will then execute Org commands in the following contexts:
554 - on a headline, changing TODO state (left/right) and priority (up/down)
555 - on a time stamp, changing the time
556 - in a plain list item, changing the bullet type
557 - in a property definition line, switching between allowed values
558 - in the BEGIN line of a clock table (changing the time block).
559 Outside these contexts, the commands will throw an error.
561 When this variable is t and the cursor is not in a special
562 context, Org-mode will support shift-selection for making and
563 enlarging regions. To make this more effective, the bullet
564 cycling will no longer happen anywhere in an item line, but only
565 if the cursor is exactly on the bullet.
567 If you set this variable to the symbol `always', then the keys
568 will not be special in headlines, property lines, and item lines,
569 to make shift selection work there as well. If this is what you
570 want, you can use the following alternative commands: `C-c C-t'
571 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
572 can be used to switch TODO sets, `C-c -' to cycle item bullet
573 types, and properties can be edited by hand or in column view.
575 However, when the cursor is on a timestamp, shift-cursor commands
576 will still edit the time stamp - this is just too good to give up.
578 XEmacs user should have this variable set to nil, because
579 `shift-select-mode' is in Emacs 23 or later only."
580 :group 'org
581 :type '(choice
582 (const :tag "Never" nil)
583 (const :tag "When outside special context" t)
584 (const :tag "Everywhere except timestamps" always)))
586 (defcustom org-loop-over-headlines-in-active-region nil
587 "Shall some commands act upon headlines in the active region?
589 When set to `t', some commands will be performed in all headlines
590 within the active region.
592 When set to `start-level', some commands will be performed in all
593 headlines within the active region, provided that these headlines
594 are of the same level than the first one.
596 When set to a string, those commands will be performed on the
597 matching headlines within the active region. Such string must be
598 a tags/property/todo match as it is used in the agenda tags view.
600 The list of commands is: `org-schedule', `org-deadline',
601 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
602 `org-archive-to-archive-sibling'. The archiving commands skip
603 already archived entries."
604 :type '(choice (const :tag "Don't loop" nil)
605 (const :tag "All headlines in active region" t)
606 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
607 (string :tag "Tags/Property/Todo matcher"))
608 :version "24.1"
609 :group 'org-todo
610 :group 'org-archive)
612 (defgroup org-startup nil
613 "Options concerning startup of Org-mode."
614 :tag "Org Startup"
615 :group 'org)
617 (defcustom org-startup-folded t
618 "Non-nil means entering Org-mode will switch to OVERVIEW.
619 This can also be configured on a per-file basis by adding one of
620 the following lines anywhere in the buffer:
622 #+STARTUP: fold (or `overview', this is equivalent)
623 #+STARTUP: nofold (or `showall', this is equivalent)
624 #+STARTUP: content
625 #+STARTUP: showeverything
627 By default, this option is ignored when Org opens agenda files
628 for the first time. If you want the agenda to honor the startup
629 option, set `org-agenda-inhibit-startup' to nil."
630 :group 'org-startup
631 :type '(choice
632 (const :tag "nofold: show all" nil)
633 (const :tag "fold: overview" t)
634 (const :tag "content: all headlines" content)
635 (const :tag "show everything, even drawers" showeverything)))
637 (defcustom org-startup-truncated t
638 "Non-nil means entering Org-mode will set `truncate-lines'.
639 This is useful since some lines containing links can be very long and
640 uninteresting. Also tables look terrible when wrapped."
641 :group 'org-startup
642 :type 'boolean)
644 (defcustom org-startup-indented nil
645 "Non-nil means turn on `org-indent-mode' on startup.
646 This can also be configured on a per-file basis by adding one of
647 the following lines anywhere in the buffer:
649 #+STARTUP: indent
650 #+STARTUP: noindent"
651 :group 'org-structure
652 :type '(choice
653 (const :tag "Not" nil)
654 (const :tag "Globally (slow on startup in large files)" t)))
656 (defcustom org-use-sub-superscripts t
657 "Non-nil means interpret \"_\" and \"^\" for display.
658 When this option is turned on, you can use TeX-like syntax for sub- and
659 superscripts. Several characters after \"_\" or \"^\" will be
660 considered as a single item - so grouping with {} is normally not
661 needed. For example, the following things will be parsed as single
662 sub- or superscripts.
664 10^24 or 10^tau several digits will be considered 1 item.
665 10^-12 or 10^-tau a leading sign with digits or a word
666 x^2-y^3 will be read as x^2 - y^3, because items are
667 terminated by almost any nonword/nondigit char.
668 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
670 Still, ambiguity is possible - so when in doubt use {} to enclose
671 the sub/superscript. If you set this variable to the symbol
672 `{}', the braces are *required* in order to trigger
673 interpretations as sub/superscript. This can be helpful in
674 documents that need \"_\" frequently in plain text."
675 :group 'org-startup
676 :version "24.1"
677 :type '(choice
678 (const :tag "Always interpret" t)
679 (const :tag "Only with braces" {})
680 (const :tag "Never interpret" nil)))
682 (defcustom org-startup-with-beamer-mode nil
683 "Non-nil means turn on `org-beamer-mode' on startup.
684 This can also be configured on a per-file basis by adding one of
685 the following lines anywhere in the buffer:
687 #+STARTUP: beamer"
688 :group 'org-startup
689 :version "24.1"
690 :type 'boolean)
692 (defcustom org-startup-align-all-tables nil
693 "Non-nil means align all tables when visiting a file.
694 This is useful when the column width in tables is forced with <N> cookies
695 in table fields. Such tables will look correct only after the first re-align.
696 This can also be configured on a per-file basis by adding one of
697 the following lines anywhere in the buffer:
698 #+STARTUP: align
699 #+STARTUP: noalign"
700 :group 'org-startup
701 :type 'boolean)
703 (defcustom org-startup-with-inline-images nil
704 "Non-nil means show inline images when loading a new Org file.
705 This can also be configured on a per-file basis by adding one of
706 the following lines anywhere in the buffer:
707 #+STARTUP: inlineimages
708 #+STARTUP: noinlineimages"
709 :group 'org-startup
710 :version "24.1"
711 :type 'boolean)
713 (defcustom org-startup-with-latex-preview nil
714 "Non-nil means preview LaTeX fragments when loading a new Org file.
716 This can also be configured on a per-file basis by adding one of
717 the followinglines anywhere in the buffer:
718 #+STARTUP: latexpreview
719 #+STARTUP: nolatexpreview"
720 :group 'org-startup
721 :version "24.4"
722 :package-version '(Org . "8.0")
723 :type 'boolean)
725 (defcustom org-insert-mode-line-in-empty-file nil
726 "Non-nil means insert the first line setting Org-mode in empty files.
727 When the function `org-mode' is called interactively in an empty file, this
728 normally means that the file name does not automatically trigger Org-mode.
729 To ensure that the file will always be in Org-mode in the future, a
730 line enforcing Org-mode will be inserted into the buffer, if this option
731 has been set."
732 :group 'org-startup
733 :type 'boolean)
735 (defcustom org-replace-disputed-keys nil
736 "Non-nil means use alternative key bindings for some keys.
737 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
738 These keys are also used by other packages like shift-selection-mode'
739 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
740 If you want to use Org-mode together with one of these other modes,
741 or more generally if you would like to move some Org-mode commands to
742 other keys, set this variable and configure the keys with the variable
743 `org-disputed-keys'.
745 This option is only relevant at load-time of Org-mode, and must be set
746 *before* org.el is loaded. Changing it requires a restart of Emacs to
747 become effective."
748 :group 'org-startup
749 :type 'boolean)
751 (defcustom org-use-extra-keys nil
752 "Non-nil means use extra key sequence definitions for certain commands.
753 This happens automatically if you run XEmacs or if `window-system'
754 is nil. This variable lets you do the same manually. You must
755 set it before loading org.
757 Example: on Carbon Emacs 22 running graphically, with an external
758 keyboard on a Powerbook, the default way of setting M-left might
759 not work for either Alt or ESC. Setting this variable will make
760 it work for ESC."
761 :group 'org-startup
762 :type 'boolean)
764 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
766 (defcustom org-disputed-keys
767 '(([(shift up)] . [(meta p)])
768 ([(shift down)] . [(meta n)])
769 ([(shift left)] . [(meta -)])
770 ([(shift right)] . [(meta +)])
771 ([(control shift right)] . [(meta shift +)])
772 ([(control shift left)] . [(meta shift -)]))
773 "Keys for which Org-mode and other modes compete.
774 This is an alist, cars are the default keys, second element specifies
775 the alternative to use when `org-replace-disputed-keys' is t.
777 Keys can be specified in any syntax supported by `define-key'.
778 The value of this option takes effect only at Org-mode's startup,
779 therefore you'll have to restart Emacs to apply it after changing."
780 :group 'org-startup
781 :type 'alist)
783 (defun org-key (key)
784 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
785 Or return the original if not disputed.
786 Also apply the translations defined in `org-xemacs-key-equivalents'."
787 (when org-replace-disputed-keys
788 (let* ((nkey (key-description key))
789 (x (org-find-if (lambda (x)
790 (equal (key-description (car x)) nkey))
791 org-disputed-keys)))
792 (setq key (if x (cdr x) key))))
793 (when (featurep 'xemacs)
794 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
795 key)
797 (defun org-find-if (predicate seq)
798 (catch 'exit
799 (while seq
800 (if (funcall predicate (car seq))
801 (throw 'exit (car seq))
802 (pop seq)))))
804 (defun org-defkey (keymap key def)
805 "Define a key, possibly translated, as returned by `org-key'."
806 (define-key keymap (org-key key) def))
808 (defcustom org-ellipsis nil
809 "The ellipsis to use in the Org-mode outline.
810 When nil, just use the standard three dots. When a string, use that instead,
811 When a face, use the standard 3 dots, but with the specified face.
812 The change affects only Org-mode (which will then use its own display table).
813 Changing this requires executing `M-x org-mode' in a buffer to become
814 effective."
815 :group 'org-startup
816 :type '(choice (const :tag "Default" nil)
817 (face :tag "Face" :value org-warning)
818 (string :tag "String" :value "...#")))
820 (defvar org-display-table nil
821 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
823 (defgroup org-keywords nil
824 "Keywords in Org-mode."
825 :tag "Org Keywords"
826 :group 'org)
828 (defcustom org-deadline-string "DEADLINE:"
829 "String to mark deadline entries.
830 A deadline is this string, followed by a time stamp. Should be a word,
831 terminated by a colon. You can insert a schedule keyword and
832 a timestamp with \\[org-deadline].
833 Changes become only effective after restarting Emacs."
834 :group 'org-keywords
835 :type 'string)
837 (defcustom org-scheduled-string "SCHEDULED:"
838 "String to mark scheduled TODO entries.
839 A schedule is this string, followed by a time stamp. Should be a word,
840 terminated by a colon. You can insert a schedule keyword and
841 a timestamp with \\[org-schedule].
842 Changes become only effective after restarting Emacs."
843 :group 'org-keywords
844 :type 'string)
846 (defcustom org-closed-string "CLOSED:"
847 "String used as the prefix for timestamps logging closing a TODO entry."
848 :group 'org-keywords
849 :type 'string)
851 (defcustom org-clock-string "CLOCK:"
852 "String used as prefix for timestamps clocking work hours on an item."
853 :group 'org-keywords
854 :type 'string)
856 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
857 org-scheduled-string "\\|"
858 org-deadline-string "\\|"
859 org-closed-string "\\|"
860 org-clock-string "\\)")
861 "Matches a line with planning or clock info.")
863 (defcustom org-comment-string "COMMENT"
864 "Entries starting with this keyword will never be exported.
865 An entry can be toggled between COMMENT and normal with
866 \\[org-toggle-comment].
867 Changes become only effective after restarting Emacs."
868 :group 'org-keywords
869 :type 'string)
871 (defcustom org-quote-string "QUOTE"
872 "Entries starting with this keyword will be exported in fixed-width font.
873 Quoting applies only to the text in the entry following the headline, and does
874 not extend beyond the next headline, even if that is lower level.
875 An entry can be toggled between QUOTE and normal with
876 \\[org-toggle-fixed-width-section]."
877 :group 'org-keywords
878 :type 'string)
880 (defconst org-repeat-re
881 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
882 "Regular expression for specifying repeated events.
883 After a match, group 1 contains the repeat expression.")
885 (defgroup org-structure nil
886 "Options concerning the general structure of Org-mode files."
887 :tag "Org Structure"
888 :group 'org)
890 (defgroup org-reveal-location nil
891 "Options about how to make context of a location visible."
892 :tag "Org Reveal Location"
893 :group 'org-structure)
895 (defconst org-context-choice
896 '(choice
897 (const :tag "Always" t)
898 (const :tag "Never" nil)
899 (repeat :greedy t :tag "Individual contexts"
900 (cons
901 (choice :tag "Context"
902 (const agenda)
903 (const org-goto)
904 (const occur-tree)
905 (const tags-tree)
906 (const link-search)
907 (const mark-goto)
908 (const bookmark-jump)
909 (const isearch)
910 (const default))
911 (boolean))))
912 "Contexts for the reveal options.")
914 (defcustom org-show-hierarchy-above '((default . t))
915 "Non-nil means show full hierarchy when revealing a location.
916 Org-mode often shows locations in an org-mode file which might have
917 been invisible before. When this is set, the hierarchy of headings
918 above the exposed location is shown.
919 Turning this off for example for sparse trees makes them very compact.
920 Instead of t, this can also be an alist specifying this option for different
921 contexts. Valid contexts are
922 agenda when exposing an entry from the agenda
923 org-goto when using the command `org-goto' on key C-c C-j
924 occur-tree when using the command `org-occur' on key C-c /
925 tags-tree when constructing a sparse tree based on tags matches
926 link-search when exposing search matches associated with a link
927 mark-goto when exposing the jump goal of a mark
928 bookmark-jump when exposing a bookmark location
929 isearch when exiting from an incremental search
930 default default for all contexts not set explicitly"
931 :group 'org-reveal-location
932 :type org-context-choice)
934 (defcustom org-show-following-heading '((default . nil))
935 "Non-nil means show following heading when revealing a location.
936 Org-mode often shows locations in an org-mode file which might have
937 been invisible before. When this is set, the heading following the
938 match is shown.
939 Turning this off for example for sparse trees makes them very compact,
940 but makes it harder to edit the location of the match. In such a case,
941 use the command \\[org-reveal] to show more context.
942 Instead of t, this can also be an alist specifying this option for different
943 contexts. See `org-show-hierarchy-above' for valid contexts."
944 :group 'org-reveal-location
945 :type org-context-choice)
947 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
948 "Non-nil means show all sibling heading when revealing a location.
949 Org-mode often shows locations in an org-mode file which might have
950 been invisible before. When this is set, the sibling of the current entry
951 heading are all made visible. If `org-show-hierarchy-above' is t,
952 the same happens on each level of the hierarchy above the current entry.
954 By default this is on for the isearch context, off for all other contexts.
955 Turning this off for example for sparse trees makes them very compact,
956 but makes it harder to edit the location of the match. In such a case,
957 use the command \\[org-reveal] to show more context.
958 Instead of t, this can also be an alist specifying this option for different
959 contexts. See `org-show-hierarchy-above' for valid contexts."
960 :group 'org-reveal-location
961 :type org-context-choice
962 :version "24.4"
963 :package-version '(Org . "8.0"))
965 (defcustom org-show-entry-below '((default . nil))
966 "Non-nil means show the entry below a headline when revealing a location.
967 Org-mode often shows locations in an org-mode file which might have
968 been invisible before. When this is set, the text below the headline that is
969 exposed is also shown.
971 By default this is off for all contexts.
972 Instead of t, this can also be an alist specifying this option for different
973 contexts. See `org-show-hierarchy-above' for valid contexts."
974 :group 'org-reveal-location
975 :type org-context-choice)
977 (defcustom org-indirect-buffer-display 'other-window
978 "How should indirect tree buffers be displayed?
979 This applies to indirect buffers created with the commands
980 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
981 Valid values are:
982 current-window Display in the current window
983 other-window Just display in another window.
984 dedicated-frame Create one new frame, and re-use it each time.
985 new-frame Make a new frame each time. Note that in this case
986 previously-made indirect buffers are kept, and you need to
987 kill these buffers yourself."
988 :group 'org-structure
989 :group 'org-agenda-windows
990 :type '(choice
991 (const :tag "In current window" current-window)
992 (const :tag "In current frame, other window" other-window)
993 (const :tag "Each time a new frame" new-frame)
994 (const :tag "One dedicated frame" dedicated-frame)))
996 (defcustom org-use-speed-commands nil
997 "Non-nil means activate single letter commands at beginning of a headline.
998 This may also be a function to test for appropriate locations where speed
999 commands should be active."
1000 :group 'org-structure
1001 :type '(choice
1002 (const :tag "Never" nil)
1003 (const :tag "At beginning of headline stars" t)
1004 (function)))
1006 (defcustom org-speed-commands-user nil
1007 "Alist of additional speed commands.
1008 This list will be checked before `org-speed-commands-default'
1009 when the variable `org-use-speed-commands' is non-nil
1010 and when the cursor is at the beginning of a headline.
1011 The car if each entry is a string with a single letter, which must
1012 be assigned to `self-insert-command' in the global map.
1013 The cdr is either a command to be called interactively, a function
1014 to be called, or a form to be evaluated.
1015 An entry that is just a list with a single string will be interpreted
1016 as a descriptive headline that will be added when listing the speed
1017 commands in the Help buffer using the `?' speed command."
1018 :group 'org-structure
1019 :type '(repeat :value ("k" . ignore)
1020 (choice :value ("k" . ignore)
1021 (list :tag "Descriptive Headline" (string :tag "Headline"))
1022 (cons :tag "Letter and Command"
1023 (string :tag "Command letter")
1024 (choice
1025 (function)
1026 (sexp))))))
1028 (defgroup org-cycle nil
1029 "Options concerning visibility cycling in Org-mode."
1030 :tag "Org Cycle"
1031 :group 'org-structure)
1033 (defcustom org-cycle-skip-children-state-if-no-children t
1034 "Non-nil means skip CHILDREN state in entries that don't have any."
1035 :group 'org-cycle
1036 :type 'boolean)
1038 (defcustom org-cycle-max-level nil
1039 "Maximum level which should still be subject to visibility cycling.
1040 Levels higher than this will, for cycling, be treated as text, not a headline.
1041 When `org-odd-levels-only' is set, a value of N in this variable actually
1042 means 2N-1 stars as the limiting headline.
1043 When nil, cycle all levels.
1044 Note that the limiting level of cycling is also influenced by
1045 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1046 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1047 than its value."
1048 :group 'org-cycle
1049 :type '(choice
1050 (const :tag "No limit" nil)
1051 (integer :tag "Maximum level")))
1053 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1054 "Names of drawers. Drawers are not opened by cycling on the headline above.
1055 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1056 this:
1057 :DRAWERNAME:
1058 .....
1059 :END:
1060 The drawer \"PROPERTIES\" is special for capturing properties through
1061 the property API.
1063 Drawers can be defined on the per-file basis with a line like:
1065 #+DRAWERS: HIDDEN STATE PROPERTIES"
1066 :group 'org-structure
1067 :group 'org-cycle
1068 :type '(repeat (string :tag "Drawer Name")))
1070 (defcustom org-hide-block-startup nil
1071 "Non-nil means entering Org-mode will fold all blocks.
1072 This can also be set in on a per-file basis with
1074 #+STARTUP: hideblocks
1075 #+STARTUP: showblocks"
1076 :group 'org-startup
1077 :group 'org-cycle
1078 :type 'boolean)
1080 (defcustom org-cycle-global-at-bob nil
1081 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1082 This makes it possible to do global cycling without having to use S-TAB or
1083 \\[universal-argument] TAB. For this special case to work, the first line
1084 of the buffer must not be a headline -- it may be empty or some other text.
1085 When used in this way, `org-cycle-hook' is disabled temporarily to make
1086 sure the cursor stays at the beginning of the buffer. When this option is
1087 nil, don't do anything special at the beginning of the buffer."
1088 :group 'org-cycle
1089 :type 'boolean)
1091 (defcustom org-cycle-level-after-item/entry-creation t
1092 "Non-nil means cycle entry level or item indentation in new empty entries.
1094 When the cursor is at the end of an empty headline, i.e., with only stars
1095 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1096 and then all possible ancestor states, before returning to the original state.
1097 This makes data entry extremely fast: M-RET to create a new headline,
1098 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1100 When the cursor is at the end of an empty plain list item, one TAB will
1101 make it a subitem, two or more tabs will back up to make this an item
1102 higher up in the item hierarchy."
1103 :group 'org-cycle
1104 :type 'boolean)
1106 (defcustom org-cycle-emulate-tab t
1107 "Where should `org-cycle' emulate TAB.
1108 nil Never
1109 white Only in completely white lines
1110 whitestart Only at the beginning of lines, before the first non-white char
1111 t Everywhere except in headlines
1112 exc-hl-bol Everywhere except at the start of a headline
1113 If TAB is used in a place where it does not emulate TAB, the current subtree
1114 visibility is cycled."
1115 :group 'org-cycle
1116 :type '(choice (const :tag "Never" nil)
1117 (const :tag "Only in completely white lines" white)
1118 (const :tag "Before first char in a line" whitestart)
1119 (const :tag "Everywhere except in headlines" t)
1120 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1123 (defcustom org-cycle-separator-lines 2
1124 "Number of empty lines needed to keep an empty line between collapsed trees.
1125 If you leave an empty line between the end of a subtree and the following
1126 headline, this empty line is hidden when the subtree is folded.
1127 Org-mode will leave (exactly) one empty line visible if the number of
1128 empty lines is equal or larger to the number given in this variable.
1129 So the default 2 means at least 2 empty lines after the end of a subtree
1130 are needed to produce free space between a collapsed subtree and the
1131 following headline.
1133 If the number is negative, and the number of empty lines is at least -N,
1134 all empty lines are shown.
1136 Special case: when 0, never leave empty lines in collapsed view."
1137 :group 'org-cycle
1138 :type 'integer)
1139 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1141 (defcustom org-pre-cycle-hook nil
1142 "Hook that is run before visibility cycling is happening.
1143 The function(s) in this hook must accept a single argument which indicates
1144 the new state that will be set right after running this hook. The
1145 argument is a symbol. Before a global state change, it can have the values
1146 `overview', `content', or `all'. Before a local state change, it can have
1147 the values `folded', `children', or `subtree'."
1148 :group 'org-cycle
1149 :type 'hook)
1151 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1152 org-cycle-hide-drawers
1153 org-cycle-hide-inline-tasks
1154 org-cycle-show-empty-lines
1155 org-optimize-window-after-visibility-change)
1156 "Hook that is run after `org-cycle' has changed the buffer visibility.
1157 The function(s) in this hook must accept a single argument which indicates
1158 the new state that was set by the most recent `org-cycle' command. The
1159 argument is a symbol. After a global state change, it can have the values
1160 `overview', `contents', or `all'. After a local state change, it can have
1161 the values `folded', `children', or `subtree'."
1162 :group 'org-cycle
1163 :type 'hook)
1165 (defgroup org-edit-structure nil
1166 "Options concerning structure editing in Org-mode."
1167 :tag "Org Edit Structure"
1168 :group 'org-structure)
1170 (defcustom org-odd-levels-only nil
1171 "Non-nil means skip even levels and only use odd levels for the outline.
1172 This has the effect that two stars are being added/taken away in
1173 promotion/demotion commands. It also influences how levels are
1174 handled by the exporters.
1175 Changing it requires restart of `font-lock-mode' to become effective
1176 for fontification also in regions already fontified.
1177 You may also set this on a per-file basis by adding one of the following
1178 lines to the buffer:
1180 #+STARTUP: odd
1181 #+STARTUP: oddeven"
1182 :group 'org-edit-structure
1183 :group 'org-appearance
1184 :type 'boolean)
1186 (defcustom org-adapt-indentation t
1187 "Non-nil means adapt indentation to outline node level.
1189 When this variable is set, Org assumes that you write outlines by
1190 indenting text in each node to align with the headline (after the stars).
1191 The following issues are influenced by this variable:
1193 - When this is set and the *entire* text in an entry is indented, the
1194 indentation is increased by one space in a demotion command, and
1195 decreased by one in a promotion command. If any line in the entry
1196 body starts with text at column 0, indentation is not changed at all.
1198 - Property drawers and planning information is inserted indented when
1199 this variable s set. When nil, they will not be indented.
1201 - TAB indents a line relative to context. The lines below a headline
1202 will be indented when this variable is set.
1204 Note that this is all about true indentation, by adding and removing
1205 space characters. See also `org-indent.el' which does level-dependent
1206 indentation in a virtual way, i.e. at display time in Emacs."
1207 :group 'org-edit-structure
1208 :type 'boolean)
1210 (defcustom org-special-ctrl-a/e nil
1211 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1213 When t, `C-a' will bring back the cursor to the beginning of the
1214 headline text, i.e. after the stars and after a possible TODO
1215 keyword. In an item, this will be the position after bullet and
1216 check-box, if any. When the cursor is already at that position,
1217 another `C-a' will bring it to the beginning of the line.
1219 `C-e' will jump to the end of the headline, ignoring the presence
1220 of tags in the headline. A second `C-e' will then jump to the
1221 true end of the line, after any tags. This also means that, when
1222 this variable is non-nil, `C-e' also will never jump beyond the
1223 end of the heading of a folded section, i.e. not after the
1224 ellipses.
1226 When set to the symbol `reversed', the first `C-a' or `C-e' works
1227 normally, going to the true line boundary first. Only a directly
1228 following, identical keypress will bring the cursor to the
1229 special positions.
1231 This may also be a cons cell where the behavior for `C-a' and
1232 `C-e' is set separately."
1233 :group 'org-edit-structure
1234 :type '(choice
1235 (const :tag "off" nil)
1236 (const :tag "on: after stars/bullet and before tags first" t)
1237 (const :tag "reversed: true line boundary first" reversed)
1238 (cons :tag "Set C-a and C-e separately"
1239 (choice :tag "Special C-a"
1240 (const :tag "off" nil)
1241 (const :tag "on: after stars/bullet first" t)
1242 (const :tag "reversed: before stars/bullet first" reversed))
1243 (choice :tag "Special C-e"
1244 (const :tag "off" nil)
1245 (const :tag "on: before tags first" t)
1246 (const :tag "reversed: after tags first" reversed)))))
1247 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1249 (defcustom org-special-ctrl-k nil
1250 "Non-nil means `C-k' will behave specially in headlines.
1251 When nil, `C-k' will call the default `kill-line' command.
1252 When t, the following will happen while the cursor is in the headline:
1254 - When the cursor is at the beginning of a headline, kill the entire
1255 line and possible the folded subtree below the line.
1256 - When in the middle of the headline text, kill the headline up to the tags.
1257 - When after the headline text, kill the tags."
1258 :group 'org-edit-structure
1259 :type 'boolean)
1261 (defcustom org-ctrl-k-protect-subtree nil
1262 "Non-nil means, do not delete a hidden subtree with C-k.
1263 When set to the symbol `error', simply throw an error when C-k is
1264 used to kill (part-of) a headline that has hidden text behind it.
1265 Any other non-nil value will result in a query to the user, if it is
1266 OK to kill that hidden subtree. When nil, kill without remorse."
1267 :group 'org-edit-structure
1268 :version "24.1"
1269 :type '(choice
1270 (const :tag "Do not protect hidden subtrees" nil)
1271 (const :tag "Protect hidden subtrees with a security query" t)
1272 (const :tag "Never kill a hidden subtree with C-k" error)))
1274 (defcustom org-catch-invisible-edits nil
1275 "Check if in invisible region before inserting or deleting a character.
1276 Valid values are:
1278 nil Do not check, so just do invisible edits.
1279 error Throw an error and do nothing.
1280 show Make point visible, and do the requested edit.
1281 show-and-error Make point visible, then throw an error and abort the edit.
1282 smart Make point visible, and do insertion/deletion if it is
1283 adjacent to visible text and the change feels predictable.
1284 Never delete a previously invisible character or add in the
1285 middle or right after an invisible region. Basically, this
1286 allows insertion and backward-delete right before ellipses.
1287 FIXME: maybe in this case we should not even show?"
1288 :group 'org-edit-structure
1289 :version "24.1"
1290 :type '(choice
1291 (const :tag "Do not check" nil)
1292 (const :tag "Throw error when trying to edit" error)
1293 (const :tag "Unhide, but do not do the edit" show-and-error)
1294 (const :tag "Show invisible part and do the edit" show)
1295 (const :tag "Be smart and do the right thing" smart)))
1297 (defcustom org-yank-folded-subtrees t
1298 "Non-nil means when yanking subtrees, fold them.
1299 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1300 it starts with a heading and all other headings in it are either children
1301 or siblings, then fold all the subtrees. However, do this only if no
1302 text after the yank would be swallowed into a folded tree by this action."
1303 :group 'org-edit-structure
1304 :type 'boolean)
1306 (defcustom org-yank-adjusted-subtrees nil
1307 "Non-nil means when yanking subtrees, adjust the level.
1308 With this setting, `org-paste-subtree' is used to insert the subtree, see
1309 this function for details."
1310 :group 'org-edit-structure
1311 :type 'boolean)
1313 (defcustom org-M-RET-may-split-line '((default . t))
1314 "Non-nil means M-RET will split the line at the cursor position.
1315 When nil, it will go to the end of the line before making a
1316 new line.
1317 You may also set this option in a different way for different
1318 contexts. Valid contexts are:
1320 headline when creating a new headline
1321 item when creating a new item
1322 table in a table field
1323 default the value to be used for all contexts not explicitly
1324 customized"
1325 :group 'org-structure
1326 :group 'org-table
1327 :type '(choice
1328 (const :tag "Always" t)
1329 (const :tag "Never" nil)
1330 (repeat :greedy t :tag "Individual contexts"
1331 (cons
1332 (choice :tag "Context"
1333 (const headline)
1334 (const item)
1335 (const table)
1336 (const default))
1337 (boolean)))))
1340 (defcustom org-insert-heading-respect-content nil
1341 "Non-nil means insert new headings after the current subtree.
1342 When nil, the new heading is created directly after the current line.
1343 The commands \\[org-insert-heading-respect-content] and
1344 \\[org-insert-todo-heading-respect-content] turn this variable on
1345 for the duration of the command."
1346 :group 'org-structure
1347 :type 'boolean)
1349 (defcustom org-blank-before-new-entry '((heading . auto)
1350 (plain-list-item . auto))
1351 "Should `org-insert-heading' leave a blank line before new heading/item?
1352 The value is an alist, with `heading' and `plain-list-item' as CAR,
1353 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1354 which case Org will look at the surrounding headings/items and try to
1355 make an intelligent decision whether to insert a blank line or not.
1357 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1358 the setting here is ignored and no empty line is inserted to avoid breaking
1359 the list structure."
1360 :group 'org-edit-structure
1361 :type '(list
1362 (cons (const heading)
1363 (choice (const :tag "Never" nil)
1364 (const :tag "Always" t)
1365 (const :tag "Auto" auto)))
1366 (cons (const plain-list-item)
1367 (choice (const :tag "Never" nil)
1368 (const :tag "Always" t)
1369 (const :tag "Auto" auto)))))
1371 (defcustom org-insert-heading-hook nil
1372 "Hook being run after inserting a new heading."
1373 :group 'org-edit-structure
1374 :type 'hook)
1376 (defcustom org-enable-fixed-width-editor t
1377 "Non-nil means lines starting with \":\" are treated as fixed-width.
1378 This currently only means they are never auto-wrapped.
1379 When nil, such lines will be treated like ordinary lines.
1380 See also the QUOTE keyword."
1381 :group 'org-edit-structure
1382 :type 'boolean)
1384 (defcustom org-goto-auto-isearch t
1385 "Non-nil means typing characters in `org-goto' starts incremental search.
1386 When nil, you can use these keybindings to navigate the buffer:
1388 q Quit the org-goto interface
1389 n Go to the next visible heading
1390 p Go to the previous visible heading
1391 f Go one heading forward on same level
1392 b Go one heading backward on same level
1393 u Go one heading up"
1394 :group 'org-edit-structure
1395 :type 'boolean)
1397 (defgroup org-sparse-trees nil
1398 "Options concerning sparse trees in Org-mode."
1399 :tag "Org Sparse Trees"
1400 :group 'org-structure)
1402 (defcustom org-highlight-sparse-tree-matches t
1403 "Non-nil means highlight all matches that define a sparse tree.
1404 The highlights will automatically disappear the next time the buffer is
1405 changed by an edit command."
1406 :group 'org-sparse-trees
1407 :type 'boolean)
1409 (defcustom org-remove-highlights-with-change t
1410 "Non-nil means any change to the buffer will remove temporary highlights.
1411 Such highlights are created by `org-occur' and `org-clock-display'.
1412 When nil, `C-c C-c needs to be used to get rid of the highlights.
1413 The highlights created by `org-preview-latex-fragment' always need
1414 `C-c C-c' to be removed."
1415 :group 'org-sparse-trees
1416 :group 'org-time
1417 :type 'boolean)
1420 (defcustom org-occur-hook '(org-first-headline-recenter)
1421 "Hook that is run after `org-occur' has constructed a sparse tree.
1422 This can be used to recenter the window to show as much of the structure
1423 as possible."
1424 :group 'org-sparse-trees
1425 :type 'hook)
1427 (defgroup org-imenu-and-speedbar nil
1428 "Options concerning imenu and speedbar in Org-mode."
1429 :tag "Org Imenu and Speedbar"
1430 :group 'org-structure)
1432 (defcustom org-imenu-depth 2
1433 "The maximum level for Imenu access to Org-mode headlines.
1434 This also applied for speedbar access."
1435 :group 'org-imenu-and-speedbar
1436 :type 'integer)
1438 (defgroup org-table nil
1439 "Options concerning tables in Org-mode."
1440 :tag "Org Table"
1441 :group 'org)
1443 (defcustom org-enable-table-editor 'optimized
1444 "Non-nil means lines starting with \"|\" are handled by the table editor.
1445 When nil, such lines will be treated like ordinary lines.
1447 When equal to the symbol `optimized', the table editor will be optimized to
1448 do the following:
1449 - Automatic overwrite mode in front of whitespace in table fields.
1450 This makes the structure of the table stay in tact as long as the edited
1451 field does not exceed the column width.
1452 - Minimize the number of realigns. Normally, the table is aligned each time
1453 TAB or RET are pressed to move to another field. With optimization this
1454 happens only if changes to a field might have changed the column width.
1455 Optimization requires replacing the functions `self-insert-command',
1456 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1457 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1458 very good at guessing when a re-align will be necessary, but you can always
1459 force one with \\[org-ctrl-c-ctrl-c].
1461 If you would like to use the optimized version in Org-mode, but the
1462 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1464 This variable can be used to turn on and off the table editor during a session,
1465 but in order to toggle optimization, a restart is required.
1467 See also the variable `org-table-auto-blank-field'."
1468 :group 'org-table
1469 :type '(choice
1470 (const :tag "off" nil)
1471 (const :tag "on" t)
1472 (const :tag "on, optimized" optimized)))
1474 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1475 (version<= emacs-version "24.1"))
1476 "Non-nil means cluster self-insert commands for undo when possible.
1477 If this is set, then, like in the Emacs command loop, 20 consecutive
1478 characters will be undone together.
1479 This is configurable, because there is some impact on typing performance."
1480 :group 'org-table
1481 :type 'boolean)
1483 (defcustom org-table-tab-recognizes-table.el t
1484 "Non-nil means TAB will automatically notice a table.el table.
1485 When it sees such a table, it moves point into it and - if necessary -
1486 calls `table-recognize-table'."
1487 :group 'org-table-editing
1488 :type 'boolean)
1490 (defgroup org-link nil
1491 "Options concerning links in Org-mode."
1492 :tag "Org Link"
1493 :group 'org)
1495 (defvar org-link-abbrev-alist-local nil
1496 "Buffer-local version of `org-link-abbrev-alist', which see.
1497 The value of this is taken from the #+LINK lines.")
1498 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1500 (defcustom org-link-abbrev-alist nil
1501 "Alist of link abbreviations.
1502 The car of each element is a string, to be replaced at the start of a link.
1503 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1504 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1506 [[linkkey:tag][description]]
1508 The 'linkkey' must be a word word, starting with a letter, followed
1509 by letters, numbers, '-' or '_'.
1511 If REPLACE is a string, the tag will simply be appended to create the link.
1512 If the string contains \"%s\", the tag will be inserted there. If the string
1513 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1514 at that point (see the function `url-hexify-string'). If the string contains
1515 the specifier \"%(my-function)\", then the custom function `my-function' will
1516 be invoked: this function takes the tag as its only argument and must return
1517 a string.
1519 REPLACE may also be a function that will be called with the tag as the
1520 only argument to create the link, which should be returned as a string.
1522 See the manual for examples."
1523 :group 'org-link
1524 :type '(repeat
1525 (cons
1526 (string :tag "Protocol")
1527 (choice
1528 (string :tag "Format")
1529 (function)))))
1531 (defcustom org-descriptive-links t
1532 "Non-nil means Org will display descriptive links.
1533 E.g. [[http://orgmode.org][Org website]] will be displayed as
1534 \"Org Website\", hiding the link itself and just displaying its
1535 description. When set to `nil', Org will display the full links
1536 literally.
1538 You can interactively set the value of this variable by calling
1539 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1540 :group 'org-link
1541 :type 'boolean)
1543 (defcustom org-link-file-path-type 'adaptive
1544 "How the path name in file links should be stored.
1545 Valid values are:
1547 relative Relative to the current directory, i.e. the directory of the file
1548 into which the link is being inserted.
1549 absolute Absolute path, if possible with ~ for home directory.
1550 noabbrev Absolute path, no abbreviation of home directory.
1551 adaptive Use relative path for files in the current directory and sub-
1552 directories of it. For other files, use an absolute path."
1553 :group 'org-link
1554 :type '(choice
1555 (const relative)
1556 (const absolute)
1557 (const noabbrev)
1558 (const adaptive)))
1560 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1561 "Types of links that should be activated in Org-mode files.
1562 This is a list of symbols, each leading to the activation of a certain link
1563 type. In principle, it does not hurt to turn on most link types - there may
1564 be a small gain when turning off unused link types. The types are:
1566 bracket The recommended [[link][description]] or [[link]] links with hiding.
1567 angle Links in angular brackets that may contain whitespace like
1568 <bbdb:Carsten Dominik>.
1569 plain Plain links in normal text, no whitespace, like http://google.com.
1570 radio Text that is matched by a radio target, see manual for details.
1571 tag Tag settings in a headline (link to tag search).
1572 date Time stamps (link to calendar).
1573 footnote Footnote labels.
1575 Changing this variable requires a restart of Emacs to become effective."
1576 :group 'org-link
1577 :type '(set :greedy t
1578 (const :tag "Double bracket links" bracket)
1579 (const :tag "Angular bracket links" angle)
1580 (const :tag "Plain text links" plain)
1581 (const :tag "Radio target matches" radio)
1582 (const :tag "Tags" tag)
1583 (const :tag "Timestamps" date)
1584 (const :tag "Footnotes" footnote)))
1586 (defcustom org-make-link-description-function nil
1587 "Function to use for generating link descriptions from links.
1588 When nil, the link location will be used. This function must take
1589 two parameters: the first one is the link, the second one is the
1590 description generated by `org-insert-link'. The function should
1591 return the description to use."
1592 :group 'org-link
1593 :type 'function)
1595 (defgroup org-link-store nil
1596 "Options concerning storing links in Org-mode."
1597 :tag "Org Store Link"
1598 :group 'org-link)
1600 (defcustom org-url-hexify-p t
1601 "When non-nil, hexify URL when creating a link."
1602 :type 'boolean
1603 :version "24.3"
1604 :group 'org-link-store)
1606 (defcustom org-email-link-description-format "Email %c: %.30s"
1607 "Format of the description part of a link to an email or usenet message.
1608 The following %-escapes will be replaced by corresponding information:
1610 %F full \"From\" field
1611 %f name, taken from \"From\" field, address if no name
1612 %T full \"To\" field
1613 %t first name in \"To\" field, address if no name
1614 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1615 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1616 %s subject
1617 %d date
1618 %m message-id.
1620 You may use normal field width specification between the % and the letter.
1621 This is for example useful to limit the length of the subject.
1623 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1624 :group 'org-link-store
1625 :type 'string)
1627 (defcustom org-from-is-user-regexp
1628 (let (r1 r2)
1629 (when (and user-mail-address (not (string= user-mail-address "")))
1630 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1631 (when (and user-full-name (not (string= user-full-name "")))
1632 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1633 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1634 "Regexp matched against the \"From:\" header of an email or usenet message.
1635 It should match if the message is from the user him/herself."
1636 :group 'org-link-store
1637 :type 'regexp)
1639 (defcustom org-context-in-file-links t
1640 "Non-nil means file links from `org-store-link' contain context.
1641 A search string will be added to the file name with :: as separator and
1642 used to find the context when the link is activated by the command
1643 `org-open-at-point'. When this option is t, the entire active region
1644 will be placed in the search string of the file link. If set to a
1645 positive integer, only the first n lines of context will be stored.
1647 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1648 negates this setting for the duration of the command."
1649 :group 'org-link-store
1650 :type '(choice boolean integer))
1652 (defcustom org-keep-stored-link-after-insertion nil
1653 "Non-nil means keep link in list for entire session.
1655 The command `org-store-link' adds a link pointing to the current
1656 location to an internal list. These links accumulate during a session.
1657 The command `org-insert-link' can be used to insert links into any
1658 Org-mode file (offering completion for all stored links). When this
1659 option is nil, every link which has been inserted once using \\[org-insert-link]
1660 will be removed from the list, to make completing the unused links
1661 more efficient."
1662 :group 'org-link-store
1663 :type 'boolean)
1665 (defgroup org-link-follow nil
1666 "Options concerning following links in Org-mode."
1667 :tag "Org Follow Link"
1668 :group 'org-link)
1670 (defcustom org-link-translation-function nil
1671 "Function to translate links with different syntax to Org syntax.
1672 This can be used to translate links created for example by the Planner
1673 or emacs-wiki packages to Org syntax.
1674 The function must accept two parameters, a TYPE containing the link
1675 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1676 which is everything after the link protocol. It should return a cons
1677 with possibly modified values of type and path.
1678 Org contains a function for this, so if you set this variable to
1679 `org-translate-link-from-planner', you should be able follow many
1680 links created by planner."
1681 :group 'org-link-follow
1682 :type 'function)
1684 (defcustom org-follow-link-hook nil
1685 "Hook that is run after a link has been followed."
1686 :group 'org-link-follow
1687 :type 'hook)
1689 (defcustom org-tab-follows-link nil
1690 "Non-nil means on links TAB will follow the link.
1691 Needs to be set before org.el is loaded.
1692 This really should not be used, it does not make sense, and the
1693 implementation is bad."
1694 :group 'org-link-follow
1695 :type 'boolean)
1697 (defcustom org-return-follows-link nil
1698 "Non-nil means on links RET will follow the link.
1699 In tables, the special behavior of RET has precedence."
1700 :group 'org-link-follow
1701 :type 'boolean)
1703 (defcustom org-mouse-1-follows-link
1704 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1705 "Non-nil means mouse-1 on a link will follow the link.
1706 A longer mouse click will still set point. Does not work on XEmacs.
1707 Needs to be set before org.el is loaded."
1708 :group 'org-link-follow
1709 :type 'boolean)
1711 (defcustom org-mark-ring-length 4
1712 "Number of different positions to be recorded in the ring.
1713 Changing this requires a restart of Emacs to work correctly."
1714 :group 'org-link-follow
1715 :type 'integer)
1717 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1718 "Non-nil means internal links in Org files must exactly match a headline.
1719 When nil, the link search tries to match a phrase with all words
1720 in the search text."
1721 :group 'org-link-follow
1722 :version "24.1"
1723 :type '(choice
1724 (const :tag "Use fuzzy text search" nil)
1725 (const :tag "Match only exact headline" t)
1726 (const :tag "Match exact headline or query to create it"
1727 query-to-create)))
1729 (defcustom org-link-frame-setup
1730 '((vm . vm-visit-folder-other-frame)
1731 (vm-imap . vm-visit-imap-folder-other-frame)
1732 (gnus . org-gnus-no-new-news)
1733 (file . find-file-other-window)
1734 (wl . wl-other-frame))
1735 "Setup the frame configuration for following links.
1736 When following a link with Emacs, it may often be useful to display
1737 this link in another window or frame. This variable can be used to
1738 set this up for the different types of links.
1739 For VM, use any of
1740 `vm-visit-folder'
1741 `vm-visit-folder-other-window'
1742 `vm-visit-folder-other-frame'
1743 For Gnus, use any of
1744 `gnus'
1745 `gnus-other-frame'
1746 `org-gnus-no-new-news'
1747 For FILE, use any of
1748 `find-file'
1749 `find-file-other-window'
1750 `find-file-other-frame'
1751 For Wanderlust use any of
1752 `wl'
1753 `wl-other-frame'
1754 For the calendar, use the variable `calendar-setup'.
1755 For BBDB, it is currently only possible to display the matches in
1756 another window."
1757 :group 'org-link-follow
1758 :type '(list
1759 (cons (const vm)
1760 (choice
1761 (const vm-visit-folder)
1762 (const vm-visit-folder-other-window)
1763 (const vm-visit-folder-other-frame)))
1764 (cons (const gnus)
1765 (choice
1766 (const gnus)
1767 (const gnus-other-frame)
1768 (const org-gnus-no-new-news)))
1769 (cons (const file)
1770 (choice
1771 (const find-file)
1772 (const find-file-other-window)
1773 (const find-file-other-frame)))
1774 (cons (const wl)
1775 (choice
1776 (const wl)
1777 (const wl-other-frame)))))
1779 (defcustom org-display-internal-link-with-indirect-buffer nil
1780 "Non-nil means use indirect buffer to display infile links.
1781 Activating internal links (from one location in a file to another location
1782 in the same file) normally just jumps to the location. When the link is
1783 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1784 is displayed in
1785 another window. When this option is set, the other window actually displays
1786 an indirect buffer clone of the current buffer, to avoid any visibility
1787 changes to the current buffer."
1788 :group 'org-link-follow
1789 :type 'boolean)
1791 (defcustom org-open-non-existing-files nil
1792 "Non-nil means `org-open-file' will open non-existing files.
1793 When nil, an error will be generated.
1794 This variable applies only to external applications because they
1795 might choke on non-existing files. If the link is to a file that
1796 will be opened in Emacs, the variable is ignored."
1797 :group 'org-link-follow
1798 :type 'boolean)
1800 (defcustom org-open-directory-means-index-dot-org nil
1801 "Non-nil means a link to a directory really means to index.org.
1802 When nil, following a directory link will run dired or open a finder/explorer
1803 window on that directory."
1804 :group 'org-link-follow
1805 :type 'boolean)
1807 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1808 "Function and arguments to call for following mailto links.
1809 This is a list with the first element being a Lisp function, and the
1810 remaining elements being arguments to the function. In string arguments,
1811 %a will be replaced by the address, and %s will be replaced by the subject
1812 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1813 :group 'org-link-follow
1814 :type '(choice
1815 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1816 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1817 (const :tag "message-mail" (message-mail "%a" "%s"))
1818 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1820 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1821 "Non-nil means ask for confirmation before executing shell links.
1822 Shell links can be dangerous: just think about a link
1824 [[shell:rm -rf ~/*][Google Search]]
1826 This link would show up in your Org-mode document as \"Google Search\",
1827 but really it would remove your entire home directory.
1828 Therefore we advise against setting this variable to nil.
1829 Just change it to `y-or-n-p' if you want to confirm with a
1830 single keystroke rather than having to type \"yes\"."
1831 :group 'org-link-follow
1832 :type '(choice
1833 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1834 (const :tag "with y-or-n (faster)" y-or-n-p)
1835 (const :tag "no confirmation (dangerous)" nil)))
1836 (put 'org-confirm-shell-link-function
1837 'safe-local-variable
1838 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1840 (defcustom org-confirm-shell-link-not-regexp ""
1841 "A regexp to skip confirmation for shell links."
1842 :group 'org-link-follow
1843 :version "24.1"
1844 :type 'regexp)
1846 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1847 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1848 Elisp links can be dangerous: just think about a link
1850 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1852 This link would show up in your Org-mode document as \"Google Search\",
1853 but really it would remove your entire home directory.
1854 Therefore we advise against setting this variable to nil.
1855 Just change it to `y-or-n-p' if you want to confirm with a
1856 single keystroke rather than having to type \"yes\"."
1857 :group 'org-link-follow
1858 :type '(choice
1859 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1860 (const :tag "with y-or-n (faster)" y-or-n-p)
1861 (const :tag "no confirmation (dangerous)" nil)))
1862 (put 'org-confirm-shell-link-function
1863 'safe-local-variable
1864 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1866 (defcustom org-confirm-elisp-link-not-regexp ""
1867 "A regexp to skip confirmation for Elisp links."
1868 :group 'org-link-follow
1869 :version "24.1"
1870 :type 'regexp)
1872 (defconst org-file-apps-defaults-gnu
1873 '((remote . emacs)
1874 (system . mailcap)
1875 (t . mailcap))
1876 "Default file applications on a UNIX or GNU/Linux system.
1877 See `org-file-apps'.")
1879 (defconst org-file-apps-defaults-macosx
1880 '((remote . emacs)
1881 (t . "open %s")
1882 (system . "open %s")
1883 ("ps.gz" . "gv %s")
1884 ("eps.gz" . "gv %s")
1885 ("dvi" . "xdvi %s")
1886 ("fig" . "xfig %s"))
1887 "Default file applications on a MacOS X system.
1888 The system \"open\" is known as a default, but we use X11 applications
1889 for some files for which the OS does not have a good default.
1890 See `org-file-apps'.")
1892 (defconst org-file-apps-defaults-windowsnt
1893 (list
1894 '(remote . emacs)
1895 (cons t
1896 (list (if (featurep 'xemacs)
1897 'mswindows-shell-execute
1898 'w32-shell-execute)
1899 "open" 'file))
1900 (cons 'system
1901 (list (if (featurep 'xemacs)
1902 'mswindows-shell-execute
1903 'w32-shell-execute)
1904 "open" 'file)))
1905 "Default file applications on a Windows NT system.
1906 The system \"open\" is used for most files.
1907 See `org-file-apps'.")
1909 (defcustom org-file-apps
1911 (auto-mode . emacs)
1912 ("\\.mm\\'" . default)
1913 ("\\.x?html?\\'" . default)
1914 ("\\.pdf\\'" . default)
1916 "External applications for opening `file:path' items in a document.
1917 Org-mode uses system defaults for different file types, but
1918 you can use this variable to set the application for a given file
1919 extension. The entries in this list are cons cells where the car identifies
1920 files and the cdr the corresponding command. Possible values for the
1921 file identifier are
1922 \"string\" A string as a file identifier can be interpreted in different
1923 ways, depending on its contents:
1925 - Alphanumeric characters only:
1926 Match links with this file extension.
1927 Example: (\"pdf\" . \"evince %s\")
1928 to open PDFs with evince.
1930 - Regular expression: Match links where the
1931 filename matches the regexp. If you want to
1932 use groups here, use shy groups.
1934 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1935 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1936 to open *.html and *.xhtml with firefox.
1938 - Regular expression which contains (non-shy) groups:
1939 Match links where the whole link, including \"::\", and
1940 anything after that, matches the regexp.
1941 In a custom command string, %1, %2, etc. are replaced with
1942 the parts of the link that were matched by the groups.
1943 For backwards compatibility, if a command string is given
1944 that does not use any of the group matches, this case is
1945 handled identically to the second one (i.e. match against
1946 file name only).
1947 In a custom lisp form, you can access the group matches with
1948 (match-string n link).
1950 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1951 to open [[file:document.pdf::5]] with evince at page 5.
1953 `directory' Matches a directory
1954 `remote' Matches a remote file, accessible through tramp or efs.
1955 Remote files most likely should be visited through Emacs
1956 because external applications cannot handle such paths.
1957 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1958 so all files Emacs knows how to handle. Using this with
1959 command `emacs' will open most files in Emacs. Beware that this
1960 will also open html files inside Emacs, unless you add
1961 (\"html\" . default) to the list as well.
1962 t Default for files not matched by any of the other options.
1963 `system' The system command to open files, like `open' on Windows
1964 and Mac OS X, and mailcap under GNU/Linux. This is the command
1965 that will be selected if you call `C-c C-o' with a double
1966 \\[universal-argument] \\[universal-argument] prefix.
1968 Possible values for the command are:
1969 `emacs' The file will be visited by the current Emacs process.
1970 `default' Use the default application for this file type, which is the
1971 association for t in the list, most likely in the system-specific
1972 part.
1973 This can be used to overrule an unwanted setting in the
1974 system-specific variable.
1975 `system' Use the system command for opening files, like \"open\".
1976 This command is specified by the entry whose car is `system'.
1977 Most likely, the system-specific version of this variable
1978 does define this command, but you can overrule/replace it
1979 here.
1980 string A command to be executed by a shell; %s will be replaced
1981 by the path to the file.
1982 sexp A Lisp form which will be evaluated. The file path will
1983 be available in the Lisp variable `file'.
1984 For more examples, see the system specific constants
1985 `org-file-apps-defaults-macosx'
1986 `org-file-apps-defaults-windowsnt'
1987 `org-file-apps-defaults-gnu'."
1988 :group 'org-link-follow
1989 :type '(repeat
1990 (cons (choice :value ""
1991 (string :tag "Extension")
1992 (const :tag "System command to open files" system)
1993 (const :tag "Default for unrecognized files" t)
1994 (const :tag "Remote file" remote)
1995 (const :tag "Links to a directory" directory)
1996 (const :tag "Any files that have Emacs modes"
1997 auto-mode))
1998 (choice :value ""
1999 (const :tag "Visit with Emacs" emacs)
2000 (const :tag "Use default" default)
2001 (const :tag "Use the system command" system)
2002 (string :tag "Command")
2003 (sexp :tag "Lisp form")))))
2005 (defcustom org-doi-server-url "http://dx.doi.org/"
2006 "The URL of the DOI server."
2007 :type 'string
2008 :version "24.3"
2009 :group 'org-link-follow)
2011 (defgroup org-refile nil
2012 "Options concerning refiling entries in Org-mode."
2013 :tag "Org Refile"
2014 :group 'org)
2016 (defcustom org-directory "~/org"
2017 "Directory with org files.
2018 This is just a default location to look for Org files. There is no need
2019 at all to put your files into this directory. It is only used in the
2020 following situations:
2022 1. When a capture template specifies a target file that is not an
2023 absolute path. The path will then be interpreted relative to
2024 `org-directory'
2025 2. When a capture note is filed away in an interactive way (when exiting the
2026 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2027 with `org-directory' as the default path."
2028 :group 'org-refile
2029 :group 'org-remember
2030 :group 'org-capture
2031 :type 'directory)
2033 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2034 "Default target for storing notes.
2035 Used as a fall back file for org-remember.el and org-capture.el, for
2036 templates that do not specify a target file."
2037 :group 'org-refile
2038 :group 'org-remember
2039 :group 'org-capture
2040 :type '(choice
2041 (const :tag "Default from remember-data-file" nil)
2042 file))
2044 (defcustom org-goto-interface 'outline
2045 "The default interface to be used for `org-goto'.
2046 Allowed values are:
2047 outline The interface shows an outline of the relevant file
2048 and the correct heading is found by moving through
2049 the outline or by searching with incremental search.
2050 outline-path-completion Headlines in the current buffer are offered via
2051 completion. This is the interface also used by
2052 the refile command."
2053 :group 'org-refile
2054 :type '(choice
2055 (const :tag "Outline" outline)
2056 (const :tag "Outline-path-completion" outline-path-completion)))
2058 (defcustom org-goto-max-level 5
2059 "Maximum target level when running `org-goto' with refile interface."
2060 :group 'org-refile
2061 :type 'integer)
2063 (defcustom org-reverse-note-order nil
2064 "Non-nil means store new notes at the beginning of a file or entry.
2065 When nil, new notes will be filed to the end of a file or entry.
2066 This can also be a list with cons cells of regular expressions that
2067 are matched against file names, and values."
2068 :group 'org-remember
2069 :group 'org-capture
2070 :group 'org-refile
2071 :type '(choice
2072 (const :tag "Reverse always" t)
2073 (const :tag "Reverse never" nil)
2074 (repeat :tag "By file name regexp"
2075 (cons regexp boolean))))
2077 (defcustom org-log-refile nil
2078 "Information to record when a task is refiled.
2080 Possible values are:
2082 nil Don't add anything
2083 time Add a time stamp to the task
2084 note Prompt for a note and add it with template `org-log-note-headings'
2086 This option can also be set with on a per-file-basis with
2088 #+STARTUP: nologrefile
2089 #+STARTUP: logrefile
2090 #+STARTUP: lognoterefile
2092 You can have local logging settings for a subtree by setting the LOGGING
2093 property to one or more of these keywords.
2095 When bulk-refiling from the agenda, the value `note' is forbidden and
2096 will temporarily be changed to `time'."
2097 :group 'org-refile
2098 :group 'org-progress
2099 :version "24.1"
2100 :type '(choice
2101 (const :tag "No logging" nil)
2102 (const :tag "Record timestamp" time)
2103 (const :tag "Record timestamp with note." note)))
2105 (defcustom org-refile-targets nil
2106 "Targets for refiling entries with \\[org-refile].
2107 This is a list of cons cells. Each cell contains:
2108 - a specification of the files to be considered, either a list of files,
2109 or a symbol whose function or variable value will be used to retrieve
2110 a file name or a list of file names. If you use `org-agenda-files' for
2111 that, all agenda files will be scanned for targets. Nil means consider
2112 headings in the current buffer.
2113 - A specification of how to find candidate refile targets. This may be
2114 any of:
2115 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2116 This tag has to be present in all target headlines, inheritance will
2117 not be considered.
2118 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2119 todo keyword.
2120 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2121 headlines that are refiling targets.
2122 - a cons cell (:level . N). Any headline of level N is considered a target.
2123 Note that, when `org-odd-levels-only' is set, level corresponds to
2124 order in hierarchy, not to the number of stars.
2125 - a cons cell (:maxlevel . N). Any headline with level <= N is 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.
2129 Each element of this list generates a set of possible targets.
2130 The union of these sets is presented (with completion) to
2131 the user by `org-refile'.
2133 You can set the variable `org-refile-target-verify-function' to a function
2134 to verify each headline found by the simple criteria above.
2136 When this variable is nil, all top-level headlines in the current buffer
2137 are used, equivalent to the value `((nil . (:level . 1))'."
2138 :group 'org-refile
2139 :type '(repeat
2140 (cons
2141 (choice :value org-agenda-files
2142 (const :tag "All agenda files" org-agenda-files)
2143 (const :tag "Current buffer" nil)
2144 (function) (variable) (file))
2145 (choice :tag "Identify target headline by"
2146 (cons :tag "Specific tag" (const :value :tag) (string))
2147 (cons :tag "TODO keyword" (const :value :todo) (string))
2148 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2149 (cons :tag "Level number" (const :value :level) (integer))
2150 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2152 (defcustom org-refile-target-verify-function nil
2153 "Function to verify if the headline at point should be a refile target.
2154 The function will be called without arguments, with point at the
2155 beginning of the headline. It should return t and leave point
2156 where it is if the headline is a valid target for refiling.
2158 If the target should not be selected, the function must return nil.
2159 In addition to this, it may move point to a place from where the search
2160 should be continued. For example, the function may decide that the entire
2161 subtree of the current entry should be excluded and move point to the end
2162 of the subtree."
2163 :group 'org-refile
2164 :type 'function)
2166 (defcustom org-refile-use-cache nil
2167 "Non-nil means cache refile targets to speed up the process.
2168 The cache for a particular file will be updated automatically when
2169 the buffer has been killed, or when any of the marker used for flagging
2170 refile targets no longer points at a live buffer.
2171 If you have added new entries to a buffer that might themselves be targets,
2172 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2173 find that easier, `C-u C-u C-u C-c C-w'."
2174 :group 'org-refile
2175 :version "24.1"
2176 :type 'boolean)
2178 (defcustom org-refile-use-outline-path nil
2179 "Non-nil means provide refile targets as paths.
2180 So a level 3 headline will be available as level1/level2/level3.
2182 When the value is `file', also include the file name (without directory)
2183 into the path. In this case, you can also stop the completion after
2184 the file name, to get entries inserted as top level in the file.
2186 When `full-file-path', include the full file path."
2187 :group 'org-refile
2188 :type '(choice
2189 (const :tag "Not" nil)
2190 (const :tag "Yes" t)
2191 (const :tag "Start with file name" file)
2192 (const :tag "Start with full file path" full-file-path)))
2194 (defcustom org-outline-path-complete-in-steps t
2195 "Non-nil means complete the outline path in hierarchical steps.
2196 When Org-mode uses the refile interface to select an outline path
2197 \(see variable `org-refile-use-outline-path'), the completion of
2198 the path can be done is a single go, or if can be done in steps down
2199 the headline hierarchy. Going in steps is probably the best if you
2200 do not use a special completion package like `ido' or `icicles'.
2201 However, when using these packages, going in one step can be very
2202 fast, while still showing the whole path to the entry."
2203 :group 'org-refile
2204 :type 'boolean)
2206 (defcustom org-refile-allow-creating-parent-nodes nil
2207 "Non-nil means allow to create new nodes as refile targets.
2208 New nodes are then created by adding \"/new node name\" to the completion
2209 of an existing node. When the value of this variable is `confirm',
2210 new node creation must be confirmed by the user (recommended)
2211 When nil, the completion must match an existing entry.
2213 Note that, if the new heading is not seen by the criteria
2214 listed in `org-refile-targets', multiple instances of the same
2215 heading would be created by trying again to file under the new
2216 heading."
2217 :group 'org-refile
2218 :type '(choice
2219 (const :tag "Never" nil)
2220 (const :tag "Always" t)
2221 (const :tag "Prompt for confirmation" confirm)))
2223 (defcustom org-refile-active-region-within-subtree nil
2224 "Non-nil means also refile active region within a subtree.
2226 By default `org-refile' doesn't allow refiling regions if they
2227 don't contain a set of subtrees, but it might be convenient to
2228 do so sometimes: in that case, the first line of the region is
2229 converted to a headline before refiling."
2230 :group 'org-refile
2231 :version "24.1"
2232 :type 'boolean)
2234 (defgroup org-todo nil
2235 "Options concerning TODO items in Org-mode."
2236 :tag "Org TODO"
2237 :group 'org)
2239 (defgroup org-progress nil
2240 "Options concerning Progress logging in Org-mode."
2241 :tag "Org Progress"
2242 :group 'org-time)
2244 (defvar org-todo-interpretation-widgets
2245 '((:tag "Sequence (cycling hits every state)" sequence)
2246 (:tag "Type (cycling directly to DONE)" type))
2247 "The available interpretation symbols for customizing `org-todo-keywords'.
2248 Interested libraries should add to this list.")
2250 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2251 "List of TODO entry keyword sequences and their interpretation.
2252 \\<org-mode-map>This is a list of sequences.
2254 Each sequence starts with a symbol, either `sequence' or `type',
2255 indicating if the keywords should be interpreted as a sequence of
2256 action steps, or as different types of TODO items. The first
2257 keywords are states requiring action - these states will select a headline
2258 for inclusion into the global TODO list Org-mode produces. If one of
2259 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2260 signify that no further action is necessary. If \"|\" is not found,
2261 the last keyword is treated as the only DONE state of the sequence.
2263 The command \\[org-todo] cycles an entry through these states, and one
2264 additional state where no keyword is present. For details about this
2265 cycling, see the manual.
2267 TODO keywords and interpretation can also be set on a per-file basis with
2268 the special #+SEQ_TODO and #+TYP_TODO lines.
2270 Each keyword can optionally specify a character for fast state selection
2271 \(in combination with the variable `org-use-fast-todo-selection')
2272 and specifiers for state change logging, using the same syntax that
2273 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2274 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2275 indicates to record a time stamp each time this state is selected.
2277 Each keyword may also specify if a timestamp or a note should be
2278 recorded when entering or leaving the state, by adding additional
2279 characters in the parenthesis after the keyword. This looks like this:
2280 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2281 record only the time of the state change. With X and Y being either
2282 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2283 Y when leaving the state if and only if the *target* state does not
2284 define X. You may omit any of the fast-selection key or X or /Y,
2285 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2287 For backward compatibility, this variable may also be just a list
2288 of keywords. In this case the interpretation (sequence or type) will be
2289 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2290 :group 'org-todo
2291 :group 'org-keywords
2292 :type '(choice
2293 (repeat :tag "Old syntax, just keywords"
2294 (string :tag "Keyword"))
2295 (repeat :tag "New syntax"
2296 (cons
2297 (choice
2298 :tag "Interpretation"
2299 ;;Quick and dirty way to see
2300 ;;`org-todo-interpretations'. This takes the
2301 ;;place of item arguments
2302 :convert-widget
2303 (lambda (widget)
2304 (widget-put widget
2305 :args (mapcar
2306 #'(lambda (x)
2307 (widget-convert
2308 (cons 'const x)))
2309 org-todo-interpretation-widgets))
2310 widget))
2311 (repeat
2312 (string :tag "Keyword"))))))
2314 (defvar org-todo-keywords-1 nil
2315 "All TODO and DONE keywords active in a buffer.")
2316 (make-variable-buffer-local 'org-todo-keywords-1)
2317 (defvar org-todo-keywords-for-agenda nil)
2318 (defvar org-done-keywords-for-agenda nil)
2319 (defvar org-drawers-for-agenda nil)
2320 (defvar org-todo-keyword-alist-for-agenda nil)
2321 (defvar org-tag-alist-for-agenda nil
2322 "Alist of all tags from all agenda files.")
2323 (defvar org-tag-groups-alist-for-agenda nil
2324 "Alist of all groups tags from all current agenda files.")
2325 (defvar org-tag-groups-alist nil)
2326 (make-variable-buffer-local 'org-tag-groups-alist)
2327 (defvar org-agenda-contributing-files nil)
2328 (defvar org-not-done-keywords nil)
2329 (make-variable-buffer-local 'org-not-done-keywords)
2330 (defvar org-done-keywords nil)
2331 (make-variable-buffer-local 'org-done-keywords)
2332 (defvar org-todo-heads nil)
2333 (make-variable-buffer-local 'org-todo-heads)
2334 (defvar org-todo-sets nil)
2335 (make-variable-buffer-local 'org-todo-sets)
2336 (defvar org-todo-log-states nil)
2337 (make-variable-buffer-local 'org-todo-log-states)
2338 (defvar org-todo-kwd-alist nil)
2339 (make-variable-buffer-local 'org-todo-kwd-alist)
2340 (defvar org-todo-key-alist nil)
2341 (make-variable-buffer-local 'org-todo-key-alist)
2342 (defvar org-todo-key-trigger nil)
2343 (make-variable-buffer-local 'org-todo-key-trigger)
2345 (defcustom org-todo-interpretation 'sequence
2346 "Controls how TODO keywords are interpreted.
2347 This variable is in principle obsolete and is only used for
2348 backward compatibility, if the interpretation of todo keywords is
2349 not given already in `org-todo-keywords'. See that variable for
2350 more information."
2351 :group 'org-todo
2352 :group 'org-keywords
2353 :type '(choice (const sequence)
2354 (const type)))
2356 (defcustom org-use-fast-todo-selection t
2357 "Non-nil means use the fast todo selection scheme with C-c C-t.
2358 This variable describes if and under what circumstances the cycling
2359 mechanism for TODO keywords will be replaced by a single-key, direct
2360 selection scheme.
2362 When nil, fast selection is never used.
2364 When the symbol `prefix', it will be used when `org-todo' is called
2365 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2366 `C-u t' in an agenda buffer.
2368 When t, fast selection is used by default. In this case, the prefix
2369 argument forces cycling instead.
2371 In all cases, the special interface is only used if access keys have
2372 actually been assigned by the user, i.e. if keywords in the configuration
2373 are followed by a letter in parenthesis, like TODO(t)."
2374 :group 'org-todo
2375 :type '(choice
2376 (const :tag "Never" nil)
2377 (const :tag "By default" t)
2378 (const :tag "Only with C-u C-c C-t" prefix)))
2380 (defcustom org-provide-todo-statistics t
2381 "Non-nil means update todo statistics after insert and toggle.
2382 ALL-HEADLINES means update todo statistics by including headlines
2383 with no TODO keyword as well, counting them as not done.
2384 A list of TODO keywords means the same, but skip keywords that are
2385 not in this list.
2387 When this is set, todo statistics is updated in the parent of the
2388 current entry each time a todo state is changed."
2389 :group 'org-todo
2390 :type '(choice
2391 (const :tag "Yes, only for TODO entries" t)
2392 (const :tag "Yes, including all entries" 'all-headlines)
2393 (repeat :tag "Yes, for TODOs in this list"
2394 (string :tag "TODO keyword"))
2395 (other :tag "No TODO statistics" nil)))
2397 (defcustom org-hierarchical-todo-statistics t
2398 "Non-nil means TODO statistics covers just direct children.
2399 When nil, all entries in the subtree are considered.
2400 This has only an effect if `org-provide-todo-statistics' is set.
2401 To set this to nil for only a single subtree, use a COOKIE_DATA
2402 property and include the word \"recursive\" into the value."
2403 :group 'org-todo
2404 :type 'boolean)
2406 (defcustom org-after-todo-state-change-hook nil
2407 "Hook which is run after the state of a TODO item was changed.
2408 The new state (a string with a TODO keyword, or nil) is available in the
2409 Lisp variable `org-state'."
2410 :group 'org-todo
2411 :type 'hook)
2413 (defvar org-blocker-hook nil
2414 "Hook for functions that are allowed to block a state change.
2416 Functions in this hook should not modify the buffer.
2417 Each function gets as its single argument a property list,
2418 see `org-trigger-hook' for more information about this list.
2420 If any of the functions in this hook returns nil, the state change
2421 is blocked.")
2423 (defvar org-trigger-hook nil
2424 "Hook for functions that are triggered by a state change.
2426 Each function gets as its single argument a property list with at
2427 least the following elements:
2429 (:type type-of-change :position pos-at-entry-start
2430 :from old-state :to new-state)
2432 Depending on the type, more properties may be present.
2434 This mechanism is currently implemented for:
2436 TODO state changes
2437 ------------------
2438 :type todo-state-change
2439 :from previous state (keyword as a string), or nil, or a symbol
2440 'todo' or 'done', to indicate the general type of state.
2441 :to new state, like in :from")
2443 (defcustom org-enforce-todo-dependencies nil
2444 "Non-nil means undone TODO entries will block switching the parent to DONE.
2445 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2446 be blocked if any prior sibling is not yet done.
2447 Finally, if the parent is blocked because of ordered siblings of its own,
2448 the child will also be blocked."
2449 :set (lambda (var val)
2450 (set var val)
2451 (if val
2452 (add-hook 'org-blocker-hook
2453 'org-block-todo-from-children-or-siblings-or-parent)
2454 (remove-hook 'org-blocker-hook
2455 'org-block-todo-from-children-or-siblings-or-parent)))
2456 :group 'org-todo
2457 :type 'boolean)
2459 (defcustom org-enforce-todo-checkbox-dependencies nil
2460 "Non-nil means unchecked boxes will block switching the parent to DONE.
2461 When this is nil, checkboxes have no influence on switching TODO states.
2462 When non-nil, you first need to check off all check boxes before the TODO
2463 entry can be switched to DONE.
2464 This variable needs to be set before org.el is loaded, and you need to
2465 restart Emacs after a change to make the change effective. The only way
2466 to change is while Emacs is running is through the customize interface."
2467 :set (lambda (var val)
2468 (set var val)
2469 (if val
2470 (add-hook 'org-blocker-hook
2471 'org-block-todo-from-checkboxes)
2472 (remove-hook 'org-blocker-hook
2473 'org-block-todo-from-checkboxes)))
2474 :group 'org-todo
2475 :type 'boolean)
2477 (defcustom org-treat-insert-todo-heading-as-state-change nil
2478 "Non-nil means inserting a TODO heading is treated as state change.
2479 So when the command \\[org-insert-todo-heading] is used, state change
2480 logging will apply if appropriate. When nil, the new TODO item will
2481 be inserted directly, and no logging will take place."
2482 :group 'org-todo
2483 :type 'boolean)
2485 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2486 "Non-nil means switching TODO states with S-cursor counts as state change.
2487 This is the default behavior. However, setting this to nil allows a
2488 convenient way to select a TODO state and bypass any logging associated
2489 with that."
2490 :group 'org-todo
2491 :type 'boolean)
2493 (defcustom org-todo-state-tags-triggers nil
2494 "Tag changes that should be triggered by TODO state changes.
2495 This is a list. Each entry is
2497 (state-change (tag . flag) .......)
2499 State-change can be a string with a state, and empty string to indicate the
2500 state that has no TODO keyword, or it can be one of the symbols `todo'
2501 or `done', meaning any not-done or done state, respectively."
2502 :group 'org-todo
2503 :group 'org-tags
2504 :type '(repeat
2505 (cons (choice :tag "When changing to"
2506 (const :tag "Not-done state" todo)
2507 (const :tag "Done state" done)
2508 (string :tag "State"))
2509 (repeat
2510 (cons :tag "Tag action"
2511 (string :tag "Tag")
2512 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2514 (defcustom org-log-done nil
2515 "Information to record when a task moves to the DONE state.
2517 Possible values are:
2519 nil Don't add anything, just change the keyword
2520 time Add a time stamp to the task
2521 note Prompt for a note and add it with template `org-log-note-headings'
2523 This option can also be set with on a per-file-basis with
2525 #+STARTUP: nologdone
2526 #+STARTUP: logdone
2527 #+STARTUP: lognotedone
2529 You can have local logging settings for a subtree by setting the LOGGING
2530 property to one or more of these keywords."
2531 :group 'org-todo
2532 :group 'org-progress
2533 :type '(choice
2534 (const :tag "No logging" nil)
2535 (const :tag "Record CLOSED timestamp" time)
2536 (const :tag "Record CLOSED timestamp with note." note)))
2538 ;; Normalize old uses of org-log-done.
2539 (cond
2540 ((eq org-log-done t) (setq org-log-done 'time))
2541 ((and (listp org-log-done) (memq 'done org-log-done))
2542 (setq org-log-done 'note)))
2544 (defcustom org-log-reschedule nil
2545 "Information to record when the scheduling date of a tasks is modified.
2547 Possible values are:
2549 nil Don't add anything, just change the date
2550 time Add a time stamp to the task
2551 note Prompt for a note and add it with template `org-log-note-headings'
2553 This option can also be set with on a per-file-basis with
2555 #+STARTUP: nologreschedule
2556 #+STARTUP: logreschedule
2557 #+STARTUP: lognotereschedule"
2558 :group 'org-todo
2559 :group 'org-progress
2560 :type '(choice
2561 (const :tag "No logging" nil)
2562 (const :tag "Record timestamp" time)
2563 (const :tag "Record timestamp with note." note)))
2565 (defcustom org-log-redeadline nil
2566 "Information to record when the deadline date of a tasks is modified.
2568 Possible values are:
2570 nil Don't add anything, just change the date
2571 time Add a time stamp to the task
2572 note Prompt for a note and add it with template `org-log-note-headings'
2574 This option can also be set with on a per-file-basis with
2576 #+STARTUP: nologredeadline
2577 #+STARTUP: logredeadline
2578 #+STARTUP: lognoteredeadline
2580 You can have local logging settings for a subtree by setting the LOGGING
2581 property to one or more of these keywords."
2582 :group 'org-todo
2583 :group 'org-progress
2584 :type '(choice
2585 (const :tag "No logging" nil)
2586 (const :tag "Record timestamp" time)
2587 (const :tag "Record timestamp with note." note)))
2589 (defcustom org-log-note-clock-out nil
2590 "Non-nil means record a note when clocking out of an item.
2591 This can also be configured on a per-file basis by adding one of
2592 the following lines anywhere in the buffer:
2594 #+STARTUP: lognoteclock-out
2595 #+STARTUP: nolognoteclock-out"
2596 :group 'org-todo
2597 :group 'org-progress
2598 :type 'boolean)
2600 (defcustom org-log-done-with-time t
2601 "Non-nil means the CLOSED time stamp will contain date and time.
2602 When nil, only the date will be recorded."
2603 :group 'org-progress
2604 :type 'boolean)
2606 (defcustom org-log-note-headings
2607 '((done . "CLOSING NOTE %t")
2608 (state . "State %-12s from %-12S %t")
2609 (note . "Note taken on %t")
2610 (reschedule . "Rescheduled from %S on %t")
2611 (delschedule . "Not scheduled, was %S on %t")
2612 (redeadline . "New deadline from %S on %t")
2613 (deldeadline . "Removed deadline, was %S on %t")
2614 (refile . "Refiled on %t")
2615 (clock-out . ""))
2616 "Headings for notes added to entries.
2617 The value is an alist, with the car being a symbol indicating the note
2618 context, and the cdr is the heading to be used. The heading may also be the
2619 empty string.
2620 %t in the heading will be replaced by a time stamp.
2621 %T will be an active time stamp instead the default inactive one
2622 %d will be replaced by a short-format time stamp.
2623 %D will be replaced by an active short-format time stamp.
2624 %s will be replaced by the new TODO state, in double quotes.
2625 %S will be replaced by the old TODO state, in double quotes.
2626 %u will be replaced by the user name.
2627 %U will be replaced by the full user name.
2629 In fact, it is not a good idea to change the `state' entry, because
2630 agenda log mode depends on the format of these entries."
2631 :group 'org-todo
2632 :group 'org-progress
2633 :type '(list :greedy t
2634 (cons (const :tag "Heading when closing an item" done) string)
2635 (cons (const :tag
2636 "Heading when changing todo state (todo sequence only)"
2637 state) string)
2638 (cons (const :tag "Heading when just taking a note" note) string)
2639 (cons (const :tag "Heading when clocking out" clock-out) string)
2640 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2641 (cons (const :tag "Heading when rescheduling" reschedule) string)
2642 (cons (const :tag "Heading when changing deadline" redeadline) string)
2643 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2644 (cons (const :tag "Heading when refiling" refile) string)))
2646 (unless (assq 'note org-log-note-headings)
2647 (push '(note . "%t") org-log-note-headings))
2649 (defcustom org-log-into-drawer nil
2650 "Non-nil means insert state change notes and time stamps into a drawer.
2651 When nil, state changes notes will be inserted after the headline and
2652 any scheduling and clock lines, but not inside a drawer.
2654 The value of this variable should be the name of the drawer to use.
2655 LOGBOOK is proposed as the default drawer for this purpose, you can
2656 also set this to a string to define the drawer of your choice.
2658 A value of t is also allowed, representing \"LOGBOOK\".
2660 A value of t or nil can also be set with on a per-file-basis with
2662 #+STARTUP: logdrawer
2663 #+STARTUP: nologdrawer
2665 If this variable is set, `org-log-state-notes-insert-after-drawers'
2666 will be ignored.
2668 You can set the property LOG_INTO_DRAWER to overrule this setting for
2669 a subtree."
2670 :group 'org-todo
2671 :group 'org-progress
2672 :type '(choice
2673 (const :tag "Not into a drawer" nil)
2674 (const :tag "LOGBOOK" t)
2675 (string :tag "Other")))
2677 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2679 (defun org-log-into-drawer ()
2680 "Return the value of `org-log-into-drawer', but let properties overrule.
2681 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2682 used instead of the default value."
2683 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2684 (cond
2685 ((not p) org-log-into-drawer)
2686 ((equal p "nil") nil)
2687 ((equal p "t") "LOGBOOK")
2688 (t p))))
2690 (defcustom org-log-state-notes-insert-after-drawers nil
2691 "Non-nil means insert state change notes after any drawers in entry.
2692 Only the drawers that *immediately* follow the headline and the
2693 deadline/scheduled line are skipped.
2694 When nil, insert notes right after the heading and perhaps the line
2695 with deadline/scheduling if present.
2697 This variable will have no effect if `org-log-into-drawer' is
2698 set."
2699 :group 'org-todo
2700 :group 'org-progress
2701 :type 'boolean)
2703 (defcustom org-log-states-order-reversed t
2704 "Non-nil means the latest state note will be directly after heading.
2705 When nil, the state change notes will be ordered according to time.
2707 This option can also be set with on a per-file-basis with
2709 #+STARTUP: logstatesreversed
2710 #+STARTUP: nologstatesreversed"
2711 :group 'org-todo
2712 :group 'org-progress
2713 :type 'boolean)
2715 (defcustom org-todo-repeat-to-state nil
2716 "The TODO state to which a repeater should return the repeating task.
2717 By default this is the first task in a TODO sequence, or the previous state
2718 in a TODO_TYP set. But you can specify another task here.
2719 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2720 :group 'org-todo
2721 :version "24.1"
2722 :type '(choice (const :tag "Head of sequence" nil)
2723 (string :tag "Specific state")))
2725 (defcustom org-log-repeat 'time
2726 "Non-nil means record moving through the DONE state when triggering repeat.
2727 An auto-repeating task is immediately switched back to TODO when
2728 marked DONE. If you are not logging state changes (by adding \"@\"
2729 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2730 record a closing note, there will be no record of the task moving
2731 through DONE. This variable forces taking a note anyway.
2733 nil Don't force a record
2734 time Record a time stamp
2735 note Prompt for a note and add it with template `org-log-note-headings'
2737 This option can also be set with on a per-file-basis with
2739 #+STARTUP: nologrepeat
2740 #+STARTUP: logrepeat
2741 #+STARTUP: lognoterepeat
2743 You can have local logging settings for a subtree by setting the LOGGING
2744 property to one or more of these keywords."
2745 :group 'org-todo
2746 :group 'org-progress
2747 :type '(choice
2748 (const :tag "Don't force a record" nil)
2749 (const :tag "Force recording the DONE state" time)
2750 (const :tag "Force recording a note with the DONE state" note)))
2753 (defgroup org-priorities nil
2754 "Priorities in Org-mode."
2755 :tag "Org Priorities"
2756 :group 'org-todo)
2758 (defcustom org-enable-priority-commands t
2759 "Non-nil means priority commands are active.
2760 When nil, these commands will be disabled, so that you never accidentally
2761 set a priority."
2762 :group 'org-priorities
2763 :type 'boolean)
2765 (defcustom org-highest-priority ?A
2766 "The highest priority of TODO items. A character like ?A, ?B etc.
2767 Must have a smaller ASCII number than `org-lowest-priority'."
2768 :group 'org-priorities
2769 :type 'character)
2771 (defcustom org-lowest-priority ?C
2772 "The lowest priority of TODO items. A character like ?A, ?B etc.
2773 Must have a larger ASCII number than `org-highest-priority'."
2774 :group 'org-priorities
2775 :type 'character)
2777 (defcustom org-default-priority ?B
2778 "The default priority of TODO items.
2779 This is the priority an item gets if no explicit priority is given.
2780 When starting to cycle on an empty priority the first step in the cycle
2781 depends on `org-priority-start-cycle-with-default'. The resulting first
2782 step priority must not exceed the range from `org-highest-priority' to
2783 `org-lowest-priority' which means that `org-default-priority' has to be
2784 in this range exclusive or inclusive the range boundaries. Else the
2785 first step refuses to set the default and the second will fall back
2786 to (depending on the command used) the highest or lowest priority."
2787 :group 'org-priorities
2788 :type 'character)
2790 (defcustom org-priority-start-cycle-with-default t
2791 "Non-nil means start with default priority when starting to cycle.
2792 When this is nil, the first step in the cycle will be (depending on the
2793 command used) one higher or lower than the default priority.
2794 See also `org-default-priority'."
2795 :group 'org-priorities
2796 :type 'boolean)
2798 (defcustom org-get-priority-function nil
2799 "Function to extract the priority from a string.
2800 The string is normally the headline. If this is nil Org computes the
2801 priority from the priority cookie like [#A] in the headline. It returns
2802 an integer, increasing by 1000 for each priority level.
2803 The user can set a different function here, which should take a string
2804 as an argument and return the numeric priority."
2805 :group 'org-priorities
2806 :version "24.1"
2807 :type 'function)
2809 (defgroup org-time nil
2810 "Options concerning time stamps and deadlines in Org-mode."
2811 :tag "Org Time"
2812 :group 'org)
2814 (defcustom org-insert-labeled-timestamps-at-point nil
2815 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2816 When nil, these labeled time stamps are forces into the second line of an
2817 entry, just after the headline. When scheduling from the global TODO list,
2818 the time stamp will always be forced into the second line."
2819 :group 'org-time
2820 :type 'boolean)
2822 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2823 "Formats for `format-time-string' which are used for time stamps.
2824 It is not recommended to change this constant.")
2826 (defcustom org-time-stamp-rounding-minutes '(0 5)
2827 "Number of minutes to round time stamps to.
2828 These are two values, the first applies when first creating a time stamp.
2829 The second applies when changing it with the commands `S-up' and `S-down'.
2830 When changing the time stamp, this means that it will change in steps
2831 of N minutes, as given by the second value.
2833 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2834 numbers should be factors of 60, so for example 5, 10, 15.
2836 When this is larger than 1, you can still force an exact time stamp by using
2837 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2838 and by using a prefix arg to `S-up/down' to specify the exact number
2839 of minutes to shift."
2840 :group 'org-time
2841 :get #'(lambda (var) ; Make sure both elements are there
2842 (if (integerp (default-value var))
2843 (list (default-value var) 5)
2844 (default-value var)))
2845 :type '(list
2846 (integer :tag "when inserting times")
2847 (integer :tag "when modifying times")))
2849 ;; Normalize old customizations of this variable.
2850 (when (integerp org-time-stamp-rounding-minutes)
2851 (setq org-time-stamp-rounding-minutes
2852 (list org-time-stamp-rounding-minutes
2853 org-time-stamp-rounding-minutes)))
2855 (defcustom org-display-custom-times nil
2856 "Non-nil means overlay custom formats over all time stamps.
2857 The formats are defined through the variable `org-time-stamp-custom-formats'.
2858 To turn this on on a per-file basis, insert anywhere in the file:
2859 #+STARTUP: customtime"
2860 :group 'org-time
2861 :set 'set-default
2862 :type 'sexp)
2863 (make-variable-buffer-local 'org-display-custom-times)
2865 (defcustom org-time-stamp-custom-formats
2866 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2867 "Custom formats for time stamps. See `format-time-string' for the syntax.
2868 These are overlaid over the default ISO format if the variable
2869 `org-display-custom-times' is set. Time like %H:%M should be at the
2870 end of the second format. The custom formats are also honored by export
2871 commands, if custom time display is turned on at the time of export."
2872 :group 'org-time
2873 :type 'sexp)
2875 (defun org-time-stamp-format (&optional long inactive)
2876 "Get the right format for a time string."
2877 (let ((f (if long (cdr org-time-stamp-formats)
2878 (car org-time-stamp-formats))))
2879 (if inactive
2880 (concat "[" (substring f 1 -1) "]")
2881 f)))
2883 (defcustom org-time-clocksum-format
2884 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2885 "The format string used when creating CLOCKSUM lines.
2886 This is also used when Org mode generates a time duration.
2888 The value can be a single format string containing two
2889 %-sequences, which will be filled with the number of hours and
2890 minutes in that order.
2892 Alternatively, the value can be a plist associating any of the
2893 keys :years, :months, :weeks, :days, :hours or :minutes with
2894 format strings. The time duration is formatted using only the
2895 time components that are needed and concatenating the results.
2896 If a time unit in absent, it falls back to the next smallest
2897 unit.
2899 The keys :require-years, :require-months, :require-days,
2900 :require-weeks, :require-hours, :require-minutes are also
2901 meaningful. A non-nil value for these keys indicates that the
2902 corresponding time component should always be included, even if
2903 its value is 0.
2906 For example,
2908 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2909 :require-minutes t)
2911 means durations longer than a day will be expressed in days,
2912 hours and minutes, and durations less than a day will always be
2913 expressed in hours and minutes (even for durations less than an
2914 hour).
2916 The value
2918 \(:days \"%dd\" :minutes \"%dm\")
2920 means durations longer than a day will be expressed in days and
2921 minutes, and durations less than a day will be expressed entirely
2922 in minutes (even for durations longer than an hour)."
2923 :group 'org-time
2924 :group 'org-clock
2925 :version "24.4"
2926 :package-version '(Org . "8.0")
2927 :type '(choice (string :tag "Format string")
2928 (set :tag "Plist"
2929 (group :inline t (const :tag "Years" :years)
2930 (string :tag "Format string"))
2931 (group :inline t
2932 (const :tag "Always show years" :require-years)
2933 (const t))
2934 (group :inline t (const :tag "Months" :months)
2935 (string :tag "Format string"))
2936 (group :inline t
2937 (const :tag "Always show months" :require-months)
2938 (const t))
2939 (group :inline t (const :tag "Weeks" :weeks)
2940 (string :tag "Format string"))
2941 (group :inline t
2942 (const :tag "Always show weeks" :require-weeks)
2943 (const t))
2944 (group :inline t (const :tag "Days" :days)
2945 (string :tag "Format string"))
2946 (group :inline t
2947 (const :tag "Always show days" :require-days)
2948 (const t))
2949 (group :inline t (const :tag "Hours" :hours)
2950 (string :tag "Format string"))
2951 (group :inline t
2952 (const :tag "Always show hours" :require-hours)
2953 (const t))
2954 (group :inline t (const :tag "Minutes" :minutes)
2955 (string :tag "Format string"))
2956 (group :inline t
2957 (const :tag "Always show minutes" :require-minutes)
2958 (const t)))))
2960 (defcustom org-time-clocksum-use-fractional nil
2961 "When non-nil, \\[org-clock-display] uses fractional times.
2962 See `org-time-clocksum-format' for more on time clock formats."
2963 :group 'org-time
2964 :group 'org-clock
2965 :version "24.3"
2966 :type 'boolean)
2968 (defcustom org-time-clocksum-use-effort-durations nil
2969 "When non-nil, \\[org-clock-display] uses effort durations.
2970 E.g. by default, one day is considered to be a 8 hours effort,
2971 so a task that has been clocked for 16 hours will be displayed
2972 as during 2 days in the clock display or in the clocktable.
2974 See `org-effort-durations' on how to set effort durations
2975 and `org-time-clocksum-format' for more on time clock formats."
2976 :group 'org-time
2977 :group 'org-clock
2978 :version "24.4"
2979 :package-version '(Org . "8.0")
2980 :type 'boolean)
2982 (defcustom org-time-clocksum-fractional-format "%.2f"
2983 "The format string used when creating CLOCKSUM lines,
2984 or when Org mode generates a time duration, if
2985 `org-time-clocksum-use-fractional' is enabled.
2987 The value can be a single format string containing one
2988 %-sequence, which will be filled with the number of hours as
2989 a float.
2991 Alternatively, the value can be a plist associating any of the
2992 keys :years, :months, :weeks, :days, :hours or :minutes with
2993 a format string. The time duration is formatted using the
2994 largest time unit which gives a non-zero integer part. If all
2995 specified formats have zero integer part, the smallest time unit
2996 is used."
2997 :group 'org-time
2998 :type '(choice (string :tag "Format string")
2999 (set (group :inline t (const :tag "Years" :years)
3000 (string :tag "Format string"))
3001 (group :inline t (const :tag "Months" :months)
3002 (string :tag "Format string"))
3003 (group :inline t (const :tag "Weeks" :weeks)
3004 (string :tag "Format string"))
3005 (group :inline t (const :tag "Days" :days)
3006 (string :tag "Format string"))
3007 (group :inline t (const :tag "Hours" :hours)
3008 (string :tag "Format string"))
3009 (group :inline t (const :tag "Minutes" :minutes)
3010 (string :tag "Format string")))))
3012 (defcustom org-deadline-warning-days 14
3013 "Number of days before expiration during which a deadline becomes active.
3014 This variable governs the display in sparse trees and in the agenda.
3015 When 0 or negative, it means use this number (the absolute value of it)
3016 even if a deadline has a different individual lead time specified.
3018 Custom commands can set this variable in the options section."
3019 :group 'org-time
3020 :group 'org-agenda-daily/weekly
3021 :type 'integer)
3023 (defcustom org-scheduled-delay-days 0
3024 "Number of days before a scheduled item becomes active.
3025 This variable governs the display in sparse trees and in the agenda.
3026 The default value (i.e. 0) means: don't delay scheduled item.
3027 When negative, it means use this number (the absolute value of it)
3028 even if a scheduled item has a different individual delay time
3029 specified.
3031 Custom commands can set this variable in the options section."
3032 :group 'org-time
3033 :group 'org-agenda-daily/weekly
3034 :version "24.4"
3035 :package-version '(Org . "8.0")
3036 :type 'integer)
3038 (defcustom org-read-date-prefer-future t
3039 "Non-nil means assume future for incomplete date input from user.
3040 This affects the following situations:
3041 1. The user gives a month but not a year.
3042 For example, if it is April and you enter \"feb 2\", this will be read
3043 as Feb 2, *next* year. \"May 5\", however, will be this year.
3044 2. The user gives a day, but no month.
3045 For example, if today is the 15th, and you enter \"3\", Org-mode will
3046 read this as the third of *next* month. However, if you enter \"17\",
3047 it will be considered as *this* month.
3049 If you set this variable to the symbol `time', then also the following
3050 will work:
3052 3. If the user gives a time.
3053 If the time is before now, it will be interpreted as tomorrow.
3055 Currently none of this works for ISO week specifications.
3057 When this option is nil, the current day, month and year will always be
3058 used as defaults.
3060 See also `org-agenda-jump-prefer-future'."
3061 :group 'org-time
3062 :type '(choice
3063 (const :tag "Never" nil)
3064 (const :tag "Check month and day" t)
3065 (const :tag "Check month, day, and time" time)))
3067 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3068 "Should the agenda jump command prefer the future for incomplete dates?
3069 The default is to do the same as configured in `org-read-date-prefer-future'.
3070 But you can also set a deviating value here.
3071 This may t or nil, or the symbol `org-read-date-prefer-future'."
3072 :group 'org-agenda
3073 :group 'org-time
3074 :version "24.1"
3075 :type '(choice
3076 (const :tag "Use org-read-date-prefer-future"
3077 org-read-date-prefer-future)
3078 (const :tag "Never" nil)
3079 (const :tag "Always" t)))
3081 (defcustom org-read-date-force-compatible-dates t
3082 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3084 Depending on the system Emacs is running on, certain dates cannot
3085 be represented with the type used internally to represent time.
3086 Dates between 1970-1-1 and 2038-1-1 can always be represented
3087 correctly. Some systems allow for earlier dates, some for later,
3088 some for both. One way to find out it to insert any date into an
3089 Org buffer, putting the cursor on the year and hitting S-up and
3090 S-down to test the range.
3092 When this variable is set to t, the date/time prompt will not let
3093 you specify dates outside the 1970-2037 range, so it is certain that
3094 these dates will work in whatever version of Emacs you are
3095 running, and also that you can move a file from one Emacs implementation
3096 to another. WHenever Org is forcing the year for you, it will display
3097 a message and beep.
3099 When this variable is nil, Org will check if the date is
3100 representable in the specific Emacs implementation you are using.
3101 If not, it will force a year, usually the current year, and beep
3102 to remind you. Currently this setting is not recommended because
3103 the likelihood that you will open your Org files in an Emacs that
3104 has limited date range is not negligible.
3106 A workaround for this problem is to use diary sexp dates for time
3107 stamps outside of this range."
3108 :group 'org-time
3109 :version "24.1"
3110 :type 'boolean)
3112 (defcustom org-read-date-display-live t
3113 "Non-nil means display current interpretation of date prompt live.
3114 This display will be in an overlay, in the minibuffer."
3115 :group 'org-time
3116 :type 'boolean)
3118 (defcustom org-read-date-popup-calendar t
3119 "Non-nil means pop up a calendar when prompting for a date.
3120 In the calendar, the date can be selected with mouse-1. However, the
3121 minibuffer will also be active, and you can simply enter the date as well.
3122 When nil, only the minibuffer will be available."
3123 :group 'org-time
3124 :type 'boolean)
3125 (org-defvaralias 'org-popup-calendar-for-date-prompt
3126 'org-read-date-popup-calendar)
3128 (make-obsolete-variable
3129 'org-read-date-minibuffer-setup-hook
3130 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3131 (defcustom org-read-date-minibuffer-setup-hook nil
3132 "Hook to be used to set up keys for the date/time interface.
3133 Add key definitions to `minibuffer-local-map', which will be a
3134 temporary copy.
3136 WARNING: This option is obsolete, you should use
3137 `org-read-date-minibuffer-local-map' to set up keys."
3138 :group 'org-time
3139 :type 'hook)
3141 (defcustom org-extend-today-until 0
3142 "The hour when your day really ends. Must be an integer.
3143 This has influence for the following applications:
3144 - When switching the agenda to \"today\". It it is still earlier than
3145 the time given here, the day recognized as TODAY is actually yesterday.
3146 - When a date is read from the user and it is still before the time given
3147 here, the current date and time will be assumed to be yesterday, 23:59.
3148 Also, timestamps inserted in capture templates follow this rule.
3150 IMPORTANT: This is a feature whose implementation is and likely will
3151 remain incomplete. Really, it is only here because past midnight seems to
3152 be the favorite working time of John Wiegley :-)"
3153 :group 'org-time
3154 :type 'integer)
3156 (defcustom org-use-effective-time nil
3157 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3158 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3159 \"effective time\" of any timestamps between midnight and 8am will be
3160 23:59 of the previous day."
3161 :group 'org-time
3162 :version "24.1"
3163 :type 'boolean)
3165 (defcustom org-use-last-clock-out-time-as-effective-time nil
3166 "When non-nil, use the last clock out time for `org-todo'.
3167 Note that this option has precedence over the combined use of
3168 `org-use-effective-time' and `org-extend-today-until'."
3169 :group 'org-time
3170 :version "24.4"
3171 :package-version '(Org . "8.0")
3172 :type 'boolean)
3174 (defcustom org-edit-timestamp-down-means-later nil
3175 "Non-nil means S-down will increase the time in a time stamp.
3176 When nil, S-up will increase."
3177 :group 'org-time
3178 :type 'boolean)
3180 (defcustom org-calendar-follow-timestamp-change t
3181 "Non-nil means make the calendar window follow timestamp changes.
3182 When a timestamp is modified and the calendar window is visible, it will be
3183 moved to the new date."
3184 :group 'org-time
3185 :type 'boolean)
3187 (defgroup org-tags nil
3188 "Options concerning tags in Org-mode."
3189 :tag "Org Tags"
3190 :group 'org)
3192 (defcustom org-tag-alist nil
3193 "List of tags allowed in Org-mode files.
3194 When this list is nil, Org-mode will base TAG input on what is already in the
3195 buffer.
3196 The value of this variable is an alist, the car of each entry must be a
3197 keyword as a string, the cdr may be a character that is used to select
3198 that tag through the fast-tag-selection interface.
3199 See the manual for details."
3200 :group 'org-tags
3201 :type '(repeat
3202 (choice
3203 (cons (string :tag "Tag name")
3204 (character :tag "Access char"))
3205 (list :tag "Start radio group"
3206 (const :startgroup)
3207 (option (string :tag "Group description")))
3208 (list :tag "Group tags delimiter"
3209 (const :grouptags))
3210 (list :tag "End radio group"
3211 (const :endgroup)
3212 (option (string :tag "Group description")))
3213 (const :tag "New line" (:newline)))))
3215 (defcustom org-tag-persistent-alist nil
3216 "List of tags that will always appear in all Org-mode files.
3217 This is in addition to any in buffer settings or customizations
3218 of `org-tag-alist'.
3219 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3220 The value of this variable is an alist, the car of each entry must be a
3221 keyword as a string, the cdr may be a character that is used to select
3222 that tag through the fast-tag-selection interface.
3223 See the manual for details.
3224 To disable these tags on a per-file basis, insert anywhere in the file:
3225 #+STARTUP: noptag"
3226 :group 'org-tags
3227 :type '(repeat
3228 (choice
3229 (cons (string :tag "Tag name")
3230 (character :tag "Access char"))
3231 (const :tag "Start radio group" (:startgroup))
3232 (const :tag "Group tags delimiter" (:grouptags))
3233 (const :tag "End radio group" (:endgroup))
3234 (const :tag "New line" (:newline)))))
3236 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3237 "If non-nil, always offer completion for all tags of all agenda files.
3238 Instead of customizing this variable directly, you might want to
3239 set it locally for capture buffers, because there no list of
3240 tags in that file can be created dynamically (there are none).
3242 (add-hook 'org-capture-mode-hook
3243 (lambda ()
3244 (set (make-local-variable
3245 'org-complete-tags-always-offer-all-agenda-tags)
3246 t)))"
3247 :group 'org-tags
3248 :version "24.1"
3249 :type 'boolean)
3251 (defvar org-file-tags nil
3252 "List of tags that can be inherited by all entries in the file.
3253 The tags will be inherited if the variable `org-use-tag-inheritance'
3254 says they should be.
3255 This variable is populated from #+FILETAGS lines.")
3257 (defcustom org-use-fast-tag-selection 'auto
3258 "Non-nil means use fast tag selection scheme.
3259 This is a special interface to select and deselect tags with single keys.
3260 When nil, fast selection is never used.
3261 When the symbol `auto', fast selection is used if and only if selection
3262 characters for tags have been configured, either through the variable
3263 `org-tag-alist' or through a #+TAGS line in the buffer.
3264 When t, fast selection is always used and selection keys are assigned
3265 automatically if necessary."
3266 :group 'org-tags
3267 :type '(choice
3268 (const :tag "Always" t)
3269 (const :tag "Never" nil)
3270 (const :tag "When selection characters are configured" 'auto)))
3272 (defcustom org-fast-tag-selection-single-key nil
3273 "Non-nil means fast tag selection exits after first change.
3274 When nil, you have to press RET to exit it.
3275 During fast tag selection, you can toggle this flag with `C-c'.
3276 This variable can also have the value `expert'. In this case, the window
3277 displaying the tags menu is not even shown, until you press C-c again."
3278 :group 'org-tags
3279 :type '(choice
3280 (const :tag "No" nil)
3281 (const :tag "Yes" t)
3282 (const :tag "Expert" expert)))
3284 (defvar org-fast-tag-selection-include-todo nil
3285 "Non-nil means fast tags selection interface will also offer TODO states.
3286 This is an undocumented feature, you should not rely on it.")
3288 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3289 "The column to which tags should be indented in a headline.
3290 If this number is positive, it specifies the column. If it is negative,
3291 it means that the tags should be flushright to that column. For example,
3292 -80 works well for a normal 80 character screen.
3293 When 0, place tags directly after headline text, with only one space in
3294 between."
3295 :group 'org-tags
3296 :type 'integer)
3298 (defcustom org-auto-align-tags t
3299 "Non-nil keeps tags aligned when modifying headlines.
3300 Some operations (i.e. demoting) change the length of a headline and
3301 therefore shift the tags around. With this option turned on, after
3302 each such operation the tags are again aligned to `org-tags-column'."
3303 :group 'org-tags
3304 :type 'boolean)
3306 (defcustom org-use-tag-inheritance t
3307 "Non-nil means tags in levels apply also for sublevels.
3308 When nil, only the tags directly given in a specific line apply there.
3309 This may also be a list of tags that should be inherited, or a regexp that
3310 matches tags that should be inherited. Additional control is possible
3311 with the variable `org-tags-exclude-from-inheritance' which gives an
3312 explicit list of tags to be excluded from inheritance, even if the value of
3313 `org-use-tag-inheritance' would select it for inheritance.
3315 If this option is t, a match early-on in a tree can lead to a large
3316 number of matches in the subtree when constructing the agenda or creating
3317 a sparse tree. If you only want to see the first match in a tree during
3318 a search, check out the variable `org-tags-match-list-sublevels'."
3319 :group 'org-tags
3320 :type '(choice
3321 (const :tag "Not" nil)
3322 (const :tag "Always" t)
3323 (repeat :tag "Specific tags" (string :tag "Tag"))
3324 (regexp :tag "Tags matched by regexp")))
3326 (defcustom org-tags-exclude-from-inheritance nil
3327 "List of tags that should never be inherited.
3328 This is a way to exclude a few tags from inheritance. For way to do
3329 the opposite, to actively allow inheritance for selected tags,
3330 see the variable `org-use-tag-inheritance'."
3331 :group 'org-tags
3332 :type '(repeat (string :tag "Tag")))
3334 (defun org-tag-inherit-p (tag)
3335 "Check if TAG is one that should be inherited."
3336 (cond
3337 ((member tag org-tags-exclude-from-inheritance) nil)
3338 ((eq org-use-tag-inheritance t) t)
3339 ((not org-use-tag-inheritance) nil)
3340 ((stringp org-use-tag-inheritance)
3341 (string-match org-use-tag-inheritance tag))
3342 ((listp org-use-tag-inheritance)
3343 (member tag org-use-tag-inheritance))
3344 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3346 (defcustom org-tags-match-list-sublevels t
3347 "Non-nil means list also sublevels of headlines matching a search.
3348 This variable applies to tags/property searches, and also to stuck
3349 projects because this search is based on a tags match as well.
3351 When set to the symbol `indented', sublevels are indented with
3352 leading dots.
3354 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3355 the sublevels of a headline matching a tag search often also match
3356 the same search. Listing all of them can create very long lists.
3357 Setting this variable to nil causes subtrees of a match to be skipped.
3359 This variable is semi-obsolete and probably should always be true. It
3360 is better to limit inheritance to certain tags using the variables
3361 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3362 :group 'org-tags
3363 :type '(choice
3364 (const :tag "No, don't list them" nil)
3365 (const :tag "Yes, do list them" t)
3366 (const :tag "List them, indented with leading dots" indented)))
3368 (defcustom org-tags-sort-function nil
3369 "When set, tags are sorted using this function as a comparator."
3370 :group 'org-tags
3371 :type '(choice
3372 (const :tag "No sorting" nil)
3373 (const :tag "Alphabetical" string<)
3374 (const :tag "Reverse alphabetical" string>)
3375 (function :tag "Custom function" nil)))
3377 (defvar org-tags-history nil
3378 "History of minibuffer reads for tags.")
3379 (defvar org-last-tags-completion-table nil
3380 "The last used completion table for tags.")
3381 (defvar org-after-tags-change-hook nil
3382 "Hook that is run after the tags in a line have changed.")
3384 (defgroup org-properties nil
3385 "Options concerning properties in Org-mode."
3386 :tag "Org Properties"
3387 :group 'org)
3389 (defcustom org-property-format "%-10s %s"
3390 "How property key/value pairs should be formatted by `indent-line'.
3391 When `indent-line' hits a property definition, it will format the line
3392 according to this format, mainly to make sure that the values are
3393 lined-up with respect to each other."
3394 :group 'org-properties
3395 :type 'string)
3397 (defcustom org-properties-postprocess-alist nil
3398 "Alist of properties and functions to adjust inserted values.
3399 Elements of this alist must be of the form
3401 ([string] [function])
3403 where [string] must be a property name and [function] must be a
3404 lambda expression: this lambda expression must take one argument,
3405 the value to adjust, and return the new value as a string.
3407 For example, this element will allow the property \"Remaining\"
3408 to be updated wrt the relation between the \"Effort\" property
3409 and the clock summary:
3411 ((\"Remaining\" (lambda(value)
3412 (let ((clocksum (org-clock-sum-current-item))
3413 (effort (org-duration-string-to-minutes
3414 (org-entry-get (point) \"Effort\"))))
3415 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3416 :group 'org-properties
3417 :version "24.1"
3418 :type '(alist :key-type (string :tag "Property")
3419 :value-type (function :tag "Function")))
3421 (defcustom org-use-property-inheritance nil
3422 "Non-nil means properties apply also for sublevels.
3424 This setting is chiefly used during property searches. Turning it on can
3425 cause significant overhead when doing a search, which is why it is not
3426 on by default.
3428 When nil, only the properties directly given in the current entry count.
3429 When t, every property is inherited. The value may also be a list of
3430 properties that should have inheritance, or a regular expression matching
3431 properties that should be inherited.
3433 However, note that some special properties use inheritance under special
3434 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3435 and the properties ending in \"_ALL\" when they are used as descriptor
3436 for valid values of a property.
3438 Note for programmers:
3439 When querying an entry with `org-entry-get', you can control if inheritance
3440 should be used. By default, `org-entry-get' looks only at the local
3441 properties. You can request inheritance by setting the inherit argument
3442 to t (to force inheritance) or to `selective' (to respect the setting
3443 in this variable)."
3444 :group 'org-properties
3445 :type '(choice
3446 (const :tag "Not" nil)
3447 (const :tag "Always" t)
3448 (repeat :tag "Specific properties" (string :tag "Property"))
3449 (regexp :tag "Properties matched by regexp")))
3451 (defun org-property-inherit-p (property)
3452 "Check if PROPERTY is one that should be inherited."
3453 (cond
3454 ((eq org-use-property-inheritance t) t)
3455 ((not org-use-property-inheritance) nil)
3456 ((stringp org-use-property-inheritance)
3457 (string-match org-use-property-inheritance property))
3458 ((listp org-use-property-inheritance)
3459 (member property org-use-property-inheritance))
3460 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3462 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3463 "The default column format, if no other format has been defined.
3464 This variable can be set on the per-file basis by inserting a line
3466 #+COLUMNS: %25ITEM ....."
3467 :group 'org-properties
3468 :type 'string)
3470 (defcustom org-columns-ellipses ".."
3471 "The ellipses to be used when a field in column view is truncated.
3472 When this is the empty string, as many characters as possible are shown,
3473 but then there will be no visual indication that the field has been truncated.
3474 When this is a string of length N, the last N characters of a truncated
3475 field are replaced by this string. If the column is narrower than the
3476 ellipses string, only part of the ellipses string will be shown."
3477 :group 'org-properties
3478 :type 'string)
3480 (defcustom org-columns-modify-value-for-display-function nil
3481 "Function that modifies values for display in column view.
3482 For example, it can be used to cut out a certain part from a time stamp.
3483 The function must take 2 arguments:
3485 column-title The title of the column (*not* the property name)
3486 value The value that should be modified.
3488 The function should return the value that should be displayed,
3489 or nil if the normal value should be used."
3490 :group 'org-properties
3491 :type 'function)
3493 (defcustom org-effort-property "Effort"
3494 "The property that is being used to keep track of effort estimates.
3495 Effort estimates given in this property need to have the format H:MM."
3496 :group 'org-properties
3497 :group 'org-progress
3498 :type '(string :tag "Property"))
3500 (defconst org-global-properties-fixed
3501 '(("VISIBILITY_ALL" . "folded children content all")
3502 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3503 "List of property/value pairs that can be inherited by any entry.
3505 These are fixed values, for the preset properties. The user variable
3506 that can be used to add to this list is `org-global-properties'.
3508 The entries in this list are cons cells where the car is a property
3509 name and cdr is a string with the value. If the value represents
3510 multiple items like an \"_ALL\" property, separate the items by
3511 spaces.")
3513 (defcustom org-global-properties nil
3514 "List of property/value pairs that can be inherited by any entry.
3516 This list will be combined with the constant `org-global-properties-fixed'.
3518 The entries in this list are cons cells where the car is a property
3519 name and cdr is a string with the value.
3521 You can set buffer-local values for the same purpose in the variable
3522 `org-file-properties' this by adding lines like
3524 #+PROPERTY: NAME VALUE"
3525 :group 'org-properties
3526 :type '(repeat
3527 (cons (string :tag "Property")
3528 (string :tag "Value"))))
3530 (defvar org-file-properties nil
3531 "List of property/value pairs that can be inherited by any entry.
3532 Valid for the current buffer.
3533 This variable is populated from #+PROPERTY lines.")
3534 (make-variable-buffer-local 'org-file-properties)
3536 (defgroup org-agenda nil
3537 "Options concerning agenda views in Org-mode."
3538 :tag "Org Agenda"
3539 :group 'org)
3541 (defvar org-category nil
3542 "Variable used by org files to set a category for agenda display.
3543 Such files should use a file variable to set it, for example
3545 # -*- mode: org; org-category: \"ELisp\"
3547 or contain a special line
3549 #+CATEGORY: ELisp
3551 If the file does not specify a category, then file's base name
3552 is used instead.")
3553 (make-variable-buffer-local 'org-category)
3554 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3556 (defcustom org-agenda-files nil
3557 "The files to be used for agenda display.
3558 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3559 \\[org-remove-file]. You can also use customize to edit the list.
3561 If an entry is a directory, all files in that directory that are matched by
3562 `org-agenda-file-regexp' will be part of the file list.
3564 If the value of the variable is not a list but a single file name, then
3565 the list of agenda files is actually stored and maintained in that file, one
3566 agenda file per line. In this file paths can be given relative to
3567 `org-directory'. Tilde expansion and environment variable substitution
3568 are also made."
3569 :group 'org-agenda
3570 :type '(choice
3571 (repeat :tag "List of files and directories" file)
3572 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3574 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3575 "Regular expression to match files for `org-agenda-files'.
3576 If any element in the list in that variable contains a directory instead
3577 of a normal file, all files in that directory that are matched by this
3578 regular expression will be included."
3579 :group 'org-agenda
3580 :type 'regexp)
3582 (defcustom org-agenda-text-search-extra-files nil
3583 "List of extra files to be searched by text search commands.
3584 These files will be search in addition to the agenda files by the
3585 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3586 Note that these files will only be searched for text search commands,
3587 not for the other agenda views like todo lists, tag searches or the weekly
3588 agenda. This variable is intended to list notes and possibly archive files
3589 that should also be searched by these two commands.
3590 In fact, if the first element in the list is the symbol `agenda-archives',
3591 than all archive files of all agenda files will be added to the search
3592 scope."
3593 :group 'org-agenda
3594 :type '(set :greedy t
3595 (const :tag "Agenda Archives" agenda-archives)
3596 (repeat :inline t (file))))
3598 (org-defvaralias 'org-agenda-multi-occur-extra-files
3599 'org-agenda-text-search-extra-files)
3601 (defcustom org-agenda-skip-unavailable-files nil
3602 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3603 A nil value means to remove them, after a query, from the list."
3604 :group 'org-agenda
3605 :type 'boolean)
3607 (defcustom org-calendar-to-agenda-key [?c]
3608 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3609 The command `org-calendar-goto-agenda' will be bound to this key. The
3610 default is the character `c' because then `c' can be used to switch back and
3611 forth between agenda and calendar."
3612 :group 'org-agenda
3613 :type 'sexp)
3615 (defcustom org-calendar-insert-diary-entry-key [?i]
3616 "The key to be installed in `calendar-mode-map' for adding diary entries.
3617 This option is irrelevant until `org-agenda-diary-file' has been configured
3618 to point to an Org-mode file. When that is the case, the command
3619 `org-agenda-diary-entry' will be bound to the key given here, by default
3620 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3621 if you want to continue doing this, you need to change this to a different
3622 key."
3623 :group 'org-agenda
3624 :type 'sexp)
3626 (defcustom org-agenda-diary-file 'diary-file
3627 "File to which to add new entries with the `i' key in agenda and calendar.
3628 When this is the symbol `diary-file', the functionality in the Emacs
3629 calendar will be used to add entries to the `diary-file'. But when this
3630 points to a file, `org-agenda-diary-entry' will be used instead."
3631 :group 'org-agenda
3632 :type '(choice
3633 (const :tag "The standard Emacs diary file" diary-file)
3634 (file :tag "Special Org file diary entries")))
3636 (eval-after-load "calendar"
3637 '(progn
3638 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3639 'org-calendar-goto-agenda)
3640 (add-hook 'calendar-mode-hook
3641 (lambda ()
3642 (unless (eq org-agenda-diary-file 'diary-file)
3643 (define-key calendar-mode-map
3644 org-calendar-insert-diary-entry-key
3645 'org-agenda-diary-entry))))))
3647 (defgroup org-latex nil
3648 "Options for embedding LaTeX code into Org-mode."
3649 :tag "Org LaTeX"
3650 :group 'org)
3652 (defcustom org-format-latex-options
3653 '(:foreground default :background default :scale 1.0
3654 :html-foreground "Black" :html-background "Transparent"
3655 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3656 "Options for creating images from LaTeX fragments.
3657 This is a property list with the following properties:
3658 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3659 `default' means use the foreground of the default face.
3660 `auto' means use the foreground from the text face.
3661 :background the background color, or \"Transparent\".
3662 `default' means use the background of the default face.
3663 `auto' means use the background from the text face.
3664 :scale a scaling factor for the size of the images, to get more pixels
3665 :html-foreground, :html-background, :html-scale
3666 the same numbers for HTML export.
3667 :matchers a list indicating which matchers should be used to
3668 find LaTeX fragments. Valid members of this list are:
3669 \"begin\" find environments
3670 \"$1\" find single characters surrounded by $.$
3671 \"$\" find math expressions surrounded by $...$
3672 \"$$\" find math expressions surrounded by $$....$$
3673 \"\\(\" find math expressions surrounded by \\(...\\)
3674 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3675 :group 'org-latex
3676 :type 'plist)
3678 (defcustom org-format-latex-signal-error t
3679 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3680 When nil, just push out a message."
3681 :group 'org-latex
3682 :version "24.1"
3683 :type 'boolean)
3685 (defcustom org-latex-to-mathml-jar-file nil
3686 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3687 Use this to specify additional executable file say a jar file.
3689 When using MathToWeb as the converter, specify the full-path to
3690 your mathtoweb.jar file."
3691 :group 'org-latex
3692 :version "24.1"
3693 :type '(choice
3694 (const :tag "None" nil)
3695 (file :tag "JAR file" :must-match t)))
3697 (defcustom org-latex-to-mathml-convert-command nil
3698 "Command to convert LaTeX fragments to MathML.
3699 Replace format-specifiers in the command as noted below and use
3700 `shell-command' to convert LaTeX to MathML.
3701 %j: Executable file in fully expanded form as specified by
3702 `org-latex-to-mathml-jar-file'.
3703 %I: Input LaTeX file in fully expanded form
3704 %o: Output MathML file
3705 This command is used by `org-create-math-formula'.
3707 When using MathToWeb as the converter, set this to
3708 \"java -jar %j -unicode -force -df %o %I\"."
3709 :group 'org-latex
3710 :version "24.1"
3711 :type '(choice
3712 (const :tag "None" nil)
3713 (string :tag "\nShell command")))
3715 (defcustom org-latex-create-formula-image-program 'dvipng
3716 "Program to convert LaTeX fragments with.
3718 dvipng Process the LaTeX fragments to dvi file, then convert
3719 dvi files to png files using dvipng.
3720 This will also include processing of non-math environments.
3721 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3722 to convert pdf files to png files"
3723 :group 'org-latex
3724 :version "24.1"
3725 :type '(choice
3726 (const :tag "dvipng" dvipng)
3727 (const :tag "imagemagick" imagemagick)))
3729 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3730 "Path to store latex preview images.
3731 A relative path here creates many directories relative to the
3732 processed org files paths. An absolute path puts all preview
3733 images at the same place."
3734 :group 'org-latex
3735 :version "24.3"
3736 :type 'string)
3738 (defun org-format-latex-mathml-available-p ()
3739 "Return t if `org-latex-to-mathml-convert-command' is usable."
3740 (save-match-data
3741 (when (and (boundp 'org-latex-to-mathml-convert-command)
3742 org-latex-to-mathml-convert-command)
3743 (let ((executable (car (split-string
3744 org-latex-to-mathml-convert-command))))
3745 (when (executable-find executable)
3746 (if (string-match
3747 "%j" org-latex-to-mathml-convert-command)
3748 (file-readable-p org-latex-to-mathml-jar-file)
3749 t))))))
3751 (defcustom org-format-latex-header "\\documentclass{article}
3752 \\usepackage[usenames]{color}
3753 \\usepackage{amsmath}
3754 \\usepackage[mathscr]{eucal}
3755 \\pagestyle{empty} % do not remove
3756 \[PACKAGES]
3757 \[DEFAULT-PACKAGES]
3758 % The settings below are copied from fullpage.sty
3759 \\setlength{\\textwidth}{\\paperwidth}
3760 \\addtolength{\\textwidth}{-3cm}
3761 \\setlength{\\oddsidemargin}{1.5cm}
3762 \\addtolength{\\oddsidemargin}{-2.54cm}
3763 \\setlength{\\evensidemargin}{\\oddsidemargin}
3764 \\setlength{\\textheight}{\\paperheight}
3765 \\addtolength{\\textheight}{-\\headheight}
3766 \\addtolength{\\textheight}{-\\headsep}
3767 \\addtolength{\\textheight}{-\\footskip}
3768 \\addtolength{\\textheight}{-3cm}
3769 \\setlength{\\topmargin}{1.5cm}
3770 \\addtolength{\\topmargin}{-2.54cm}"
3771 "The document header used for processing LaTeX fragments.
3772 It is imperative that this header make sure that no page number
3773 appears on the page. The package defined in the variables
3774 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3775 will either replace the placeholder \"[PACKAGES]\" in this
3776 header, or they will be appended."
3777 :group 'org-latex
3778 :type 'string)
3780 (defun org-set-packages-alist (var val)
3781 "Set the packages alist and make sure it has 3 elements per entry."
3782 (set var (mapcar (lambda (x)
3783 (if (and (consp x) (= (length x) 2))
3784 (list (car x) (nth 1 x) t)
3786 val)))
3788 (defun org-get-packages-alist (var)
3789 "Get the packages alist and make sure it has 3 elements per entry."
3790 (mapcar (lambda (x)
3791 (if (and (consp x) (= (length x) 2))
3792 (list (car x) (nth 1 x) t)
3794 (default-value var)))
3796 (defcustom org-latex-default-packages-alist
3797 '(("AUTO" "inputenc" t)
3798 ("T1" "fontenc" t)
3799 ("" "fixltx2e" nil)
3800 ("" "graphicx" t)
3801 ("" "longtable" nil)
3802 ("" "float" nil)
3803 ("" "wrapfig" nil)
3804 ("" "soul" t)
3805 ("" "textcomp" t)
3806 ("" "marvosym" t)
3807 ("" "wasysym" t)
3808 ("" "latexsym" t)
3809 ("" "amssymb" t)
3810 ("" "hyperref" nil)
3811 "\\tolerance=1000")
3812 "Alist of default packages to be inserted in the header.
3814 Change this only if one of the packages here causes an
3815 incompatibility with another package you are using.
3817 The packages in this list are needed by one part or another of
3818 Org mode to function properly:
3820 - inputenc, fontenc: for basic font and character selection
3821 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3822 symbols used for interpreting the entities in `org-entities'.
3823 You can skip some of these packages if you don't use any of the
3824 symbols in it.
3825 - graphicx: for including images
3826 - float, wrapfig: for figure placement
3827 - longtable: for long tables
3828 - hyperref: for cross references
3830 Therefore you should not modify this variable unless you know
3831 what you are doing. The one reason to change it anyway is that
3832 you might be loading some other package that conflicts with one
3833 of the default packages. Each cell is of the format
3834 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3835 the package also needs to be included when compiling LaTeX
3836 snippets into images for inclusion into non-LaTeX output."
3837 :group 'org-latex
3838 :group 'org-export-latex
3839 :set 'org-set-packages-alist
3840 :get 'org-get-packages-alist
3841 :version "24.1"
3842 :type '(repeat
3843 (choice
3844 (list :tag "options/package pair"
3845 (string :tag "options")
3846 (string :tag "package")
3847 (boolean :tag "Snippet"))
3848 (string :tag "A line of LaTeX"))))
3850 (defcustom org-latex-packages-alist nil
3851 "Alist of packages to be inserted in every LaTeX header.
3853 These will be inserted after `org-latex-default-packages-alist'.
3854 Each cell is of the format:
3856 \(\"options\" \"package\" snippet-flag)
3858 SNIPPET-FLAG, when t, indicates that this package is also needed
3859 when turning LaTeX snippets into images for inclusion into
3860 non-LaTeX output.
3862 Make sure that you only list packages here which:
3864 - you want in every file
3865 - do not conflict with the setup in `org-format-latex-header'.
3866 - do not conflict with the default packages in
3867 `org-latex-default-packages-alist'."
3868 :group 'org-latex
3869 :group 'org-export-latex
3870 :set 'org-set-packages-alist
3871 :get 'org-get-packages-alist
3872 :type '(repeat
3873 (choice
3874 (list :tag "options/package pair"
3875 (string :tag "options")
3876 (string :tag "package")
3877 (boolean :tag "Snippet"))
3878 (string :tag "A line of LaTeX"))))
3880 (defgroup org-appearance nil
3881 "Settings for Org-mode appearance."
3882 :tag "Org Appearance"
3883 :group 'org)
3885 (defcustom org-level-color-stars-only nil
3886 "Non-nil means fontify only the stars in each headline.
3887 When nil, the entire headline is fontified.
3888 Changing it requires restart of `font-lock-mode' to become effective
3889 also in regions already fontified."
3890 :group 'org-appearance
3891 :type 'boolean)
3893 (defcustom org-hide-leading-stars nil
3894 "Non-nil means hide the first N-1 stars in a headline.
3895 This works by using the face `org-hide' for these stars. This
3896 face is white for a light background, and black for a dark
3897 background. You may have to customize the face `org-hide' to
3898 make this work.
3899 Changing it requires restart of `font-lock-mode' to become effective
3900 also in regions already fontified.
3901 You may also set this on a per-file basis by adding one of the following
3902 lines to the buffer:
3904 #+STARTUP: hidestars
3905 #+STARTUP: showstars"
3906 :group 'org-appearance
3907 :type 'boolean)
3909 (defcustom org-hidden-keywords nil
3910 "List of symbols corresponding to keywords to be hidden the org buffer.
3911 For example, a value '(title) for this list will make the document's title
3912 appear in the buffer without the initial #+TITLE: keyword."
3913 :group 'org-appearance
3914 :version "24.1"
3915 :type '(set (const :tag "#+AUTHOR" author)
3916 (const :tag "#+DATE" date)
3917 (const :tag "#+EMAIL" email)
3918 (const :tag "#+TITLE" title)))
3920 (defcustom org-custom-properties nil
3921 "List of properties (as strings) with a special meaning.
3922 The default use of these custom properties is to let the user
3923 hide them with `org-toggle-custom-properties-visibility'."
3924 :group 'org-properties
3925 :group 'org-appearance
3926 :version "24.3"
3927 :type '(repeat (string :tag "Property Name")))
3929 (defcustom org-fontify-done-headline nil
3930 "Non-nil means change the face of a headline if it is marked DONE.
3931 Normally, only the TODO/DONE keyword indicates the state of a headline.
3932 When this is non-nil, the headline after the keyword is set to the
3933 `org-headline-done' as an additional indication."
3934 :group 'org-appearance
3935 :type 'boolean)
3937 (defcustom org-fontify-emphasized-text t
3938 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3939 Changing this variable requires a restart of Emacs to take effect."
3940 :group 'org-appearance
3941 :type 'boolean)
3943 (defcustom org-fontify-whole-heading-line nil
3944 "Non-nil means fontify the whole line for headings.
3945 This is useful when setting a background color for the
3946 org-level-* faces."
3947 :group 'org-appearance
3948 :type 'boolean)
3950 (defcustom org-highlight-latex-and-related nil
3951 "Non-nil means highlight LaTeX related syntax in the buffer.
3952 When non nil, the value should be a list containing any of the
3953 following symbols:
3954 `latex' Highlight LaTeX snippets and environments.
3955 `script' Highlight subscript and superscript.
3956 `entities' Highlight entities."
3957 :group 'org-appearance
3958 :version "24.4"
3959 :package-version '(Org . "8.0")
3960 :type '(choice
3961 (const :tag "No highlighting" nil)
3962 (set :greedy t :tag "Highlight"
3963 (const :tag "LaTeX snippets and environments" latex)
3964 (const :tag "Subscript and superscript" script)
3965 (const :tag "Entities" entities))))
3967 (defcustom org-hide-emphasis-markers nil
3968 "Non-nil mean font-lock should hide the emphasis marker characters."
3969 :group 'org-appearance
3970 :type 'boolean)
3972 (defcustom org-pretty-entities nil
3973 "Non-nil means show entities as UTF8 characters.
3974 When nil, the \\name form remains in the buffer."
3975 :group 'org-appearance
3976 :version "24.1"
3977 :type 'boolean)
3979 (defcustom org-pretty-entities-include-sub-superscripts t
3980 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3981 :group 'org-appearance
3982 :version "24.1"
3983 :type 'boolean)
3985 (defvar org-emph-re nil
3986 "Regular expression for matching emphasis.
3987 After a match, the match groups contain these elements:
3988 0 The match of the full regular expression, including the characters
3989 before and after the proper match
3990 1 The character before the proper match, or empty at beginning of line
3991 2 The proper match, including the leading and trailing markers
3992 3 The leading marker like * or /, indicating the type of highlighting
3993 4 The text between the emphasis markers, not including the markers
3994 5 The character after the match, empty at the end of a line")
3995 (defvar org-verbatim-re nil
3996 "Regular expression for matching verbatim text.")
3997 (defvar org-emphasis-regexp-components) ; defined just below
3998 (defvar org-emphasis-alist) ; defined just below
3999 (defun org-set-emph-re (var val)
4000 "Set variable and compute the emphasis regular expression."
4001 (set var val)
4002 (when (and (boundp 'org-emphasis-alist)
4003 (boundp 'org-emphasis-regexp-components)
4004 org-emphasis-alist org-emphasis-regexp-components)
4005 (let* ((e org-emphasis-regexp-components)
4006 (pre (car e))
4007 (post (nth 1 e))
4008 (border (nth 2 e))
4009 (body (nth 3 e))
4010 (nl (nth 4 e))
4011 (body1 (concat body "*?"))
4012 (markers (mapconcat 'car org-emphasis-alist ""))
4013 (vmarkers (mapconcat
4014 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
4015 org-emphasis-alist "")))
4016 ;; make sure special characters appear at the right position in the class
4017 (if (string-match "\\^" markers)
4018 (setq markers (concat (replace-match "" t t markers) "^")))
4019 (if (string-match "-" markers)
4020 (setq markers (concat (replace-match "" t t markers) "-")))
4021 (if (string-match "\\^" vmarkers)
4022 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4023 (if (string-match "-" vmarkers)
4024 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4025 (if (> nl 0)
4026 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4027 (int-to-string nl) "\\}")))
4028 ;; Make the regexp
4029 (setq org-emph-re
4030 (concat "\\([" pre "]\\|^\\)"
4031 "\\("
4032 "\\([" markers "]\\)"
4033 "\\("
4034 "[^" border "]\\|"
4035 "[^" border "]"
4036 body1
4037 "[^" border "]"
4038 "\\)"
4039 "\\3\\)"
4040 "\\([" post "]\\|$\\)"))
4041 (setq org-verbatim-re
4042 (concat "\\([" pre "]\\|^\\)"
4043 "\\("
4044 "\\([" vmarkers "]\\)"
4045 "\\("
4046 "[^" border "]\\|"
4047 "[^" border "]"
4048 body1
4049 "[^" border "]"
4050 "\\)"
4051 "\\3\\)"
4052 "\\([" post "]\\|$\\)")))))
4054 (defcustom org-emphasis-regexp-components
4055 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4056 "Components used to build the regular expression for emphasis.
4057 This is a list with five entries. Terminology: In an emphasis string
4058 like \" *strong word* \", we call the initial space PREMATCH, the final
4059 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4060 and \"trong wor\" is the body. The different components in this variable
4061 specify what is allowed/forbidden in each part:
4063 pre Chars allowed as prematch. Beginning of line will be allowed too.
4064 post Chars allowed as postmatch. End of line will be allowed too.
4065 border The chars *forbidden* as border characters.
4066 body-regexp A regexp like \".\" to match a body character. Don't use
4067 non-shy groups here, and don't allow newline here.
4068 newline The maximum number of newlines allowed in an emphasis exp.
4070 Use customize to modify this, or restart Emacs after changing it."
4071 :group 'org-appearance
4072 :set 'org-set-emph-re
4073 :type '(list
4074 (sexp :tag "Allowed chars in pre ")
4075 (sexp :tag "Allowed chars in post ")
4076 (sexp :tag "Forbidden chars in border ")
4077 (sexp :tag "Regexp for body ")
4078 (integer :tag "number of newlines allowed")
4079 (option (boolean :tag "Please ignore this button"))))
4081 (defcustom org-emphasis-alist
4082 `(("*" bold "<b>" "</b>")
4083 ("/" italic "<i>" "</i>")
4084 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4085 ("=" org-code "<code>" "</code>" verbatim)
4086 ("~" org-verbatim "<code>" "</code>" verbatim)
4087 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4088 "<del>" "</del>")
4090 "Special syntax for emphasized text.
4091 Text starting and ending with a special character will be emphasized, for
4092 example *bold*, _underlined_ and /italic/. This variable sets the marker
4093 characters, the face to be used by font-lock for highlighting in Org-mode
4094 Emacs buffers, and the HTML tags to be used for this.
4095 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4096 Use customize to modify this, or restart Emacs after changing it."
4097 :group 'org-appearance
4098 :set 'org-set-emph-re
4099 :type '(repeat
4100 (list
4101 (string :tag "Marker character")
4102 (choice
4103 (face :tag "Font-lock-face")
4104 (plist :tag "Face property list"))
4105 (string :tag "HTML start tag")
4106 (string :tag "HTML end tag")
4107 (option (const verbatim)))))
4109 (defvar org-protecting-blocks
4110 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4111 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4112 This is needed for font-lock setup.")
4114 ;;; Miscellaneous options
4116 (defgroup org-completion nil
4117 "Completion in Org-mode."
4118 :tag "Org Completion"
4119 :group 'org)
4121 (defcustom org-completion-use-ido nil
4122 "Non-nil means use ido completion wherever possible.
4123 Note that `ido-mode' must be active for this variable to be relevant.
4124 If you decide to turn this variable on, you might well want to turn off
4125 `org-outline-path-complete-in-steps'.
4126 See also `org-completion-use-iswitchb'."
4127 :group 'org-completion
4128 :type 'boolean)
4130 (defcustom org-completion-use-iswitchb nil
4131 "Non-nil means use iswitchb completion wherever possible.
4132 Note that `iswitchb-mode' must be active for this variable to be relevant.
4133 If you decide to turn this variable on, you might well want to turn off
4134 `org-outline-path-complete-in-steps'.
4135 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4136 :group 'org-completion
4137 :type 'boolean)
4139 (defcustom org-completion-fallback-command 'hippie-expand
4140 "The expansion command called by \\[pcomplete] in normal context.
4141 Normal means, no org-mode-specific context."
4142 :group 'org-completion
4143 :type 'function)
4145 ;;; Functions and variables from their packages
4146 ;; Declared here to avoid compiler warnings
4148 ;; XEmacs only
4149 (defvar outline-mode-menu-heading)
4150 (defvar outline-mode-menu-show)
4151 (defvar outline-mode-menu-hide)
4152 (defvar zmacs-regions) ; XEmacs regions
4154 ;; Emacs only
4155 (defvar mark-active)
4157 ;; Various packages
4158 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4159 (declare-function calendar-forward-day "cal-move" (arg))
4160 (declare-function calendar-goto-date "cal-move" (date))
4161 (declare-function calendar-goto-today "cal-move" ())
4162 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4163 (defvar calc-embedded-close-formula)
4164 (defvar calc-embedded-open-formula)
4165 (declare-function cdlatex-tab "ext:cdlatex" ())
4166 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4167 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4168 (defvar font-lock-unfontify-region-function)
4169 (declare-function iswitchb-read-buffer "iswitchb"
4170 (prompt &optional default require-match start matches-set))
4171 (defvar iswitchb-temp-buflist)
4172 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4173 (defvar org-agenda-tags-todo-honor-ignore-options)
4174 (declare-function org-agenda-skip "org-agenda" ())
4175 (declare-function
4176 org-agenda-format-item "org-agenda"
4177 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4178 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4179 (declare-function org-agenda-change-all-lines "org-agenda"
4180 (newhead hdmarker &optional fixface just-this))
4181 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4182 (declare-function org-agenda-maybe-redo "org-agenda" ())
4183 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4184 (beg end))
4185 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4186 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4187 "org-agenda" (&optional end))
4188 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4189 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4190 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4191 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4192 (declare-function org-indent-mode "org-indent" (&optional arg))
4193 (declare-function parse-time-string "parse-time" (string))
4194 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4195 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4196 (defvar remember-data-file)
4197 (defvar texmathp-why)
4198 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4199 (declare-function table--at-cell-p "table" (position &optional object at-column))
4201 (defvar org-latex-regexps)
4203 ;;; Autoload and prepare some org modules
4205 ;; Some table stuff that needs to be defined here, because it is used
4206 ;; by the functions setting up org-mode or checking for table context.
4208 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4209 "Detect an org-type or table-type table.")
4210 (defconst org-table-line-regexp "^[ \t]*|"
4211 "Detect an org-type table line.")
4212 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4213 "Detect an org-type table line.")
4214 (defconst org-table-hline-regexp "^[ \t]*|-"
4215 "Detect an org-type table hline.")
4216 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4217 "Detect a table-type table hline.")
4218 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4219 "Detect the first line outside a table when searching from within it.
4220 This works for both table types.")
4222 ;; Autoload the functions in org-table.el that are needed by functions here.
4224 (eval-and-compile
4225 (org-autoload "org-table"
4226 '(org-table-begin org-table-blank-field org-table-end)))
4228 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4229 "Detect a #+TBLFM line.")
4231 ;;;###autoload
4232 (defun turn-on-orgtbl ()
4233 "Unconditionally turn on `orgtbl-mode'."
4234 (require 'org-table)
4235 (orgtbl-mode 1))
4237 (defun org-at-table-p (&optional table-type)
4238 "Return t if the cursor is inside an org-type table.
4239 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4240 (if org-enable-table-editor
4241 (save-excursion
4242 (beginning-of-line 1)
4243 (looking-at (if table-type org-table-any-line-regexp
4244 org-table-line-regexp)))
4245 nil))
4246 (defsubst org-table-p () (org-at-table-p))
4248 (defun org-at-table.el-p ()
4249 "Return t if and only if we are at a table.el table."
4250 (and (org-at-table-p 'any)
4251 (save-excursion
4252 (goto-char (org-table-begin 'any))
4253 (looking-at org-table1-hline-regexp))))
4255 (defun org-table-recognize-table.el ()
4256 "If there is a table.el table nearby, recognize it and move into it."
4257 (if org-table-tab-recognizes-table.el
4258 (if (org-at-table.el-p)
4259 (progn
4260 (beginning-of-line 1)
4261 (if (looking-at org-table-dataline-regexp)
4263 (if (looking-at org-table1-hline-regexp)
4264 (progn
4265 (beginning-of-line 2)
4266 (if (looking-at org-table-any-border-regexp)
4267 (beginning-of-line -1)))))
4268 (if (re-search-forward "|" (org-table-end t) t)
4269 (progn
4270 (require 'table)
4271 (if (table--at-cell-p (point))
4273 (message "recognizing table.el table...")
4274 (table-recognize-table)
4275 (message "recognizing table.el table...done")))
4276 (error "This should not happen"))
4278 nil)
4279 nil))
4281 (defun org-at-table-hline-p ()
4282 "Return t if the cursor is inside a hline in a table."
4283 (if org-enable-table-editor
4284 (save-excursion
4285 (beginning-of-line 1)
4286 (looking-at org-table-hline-regexp))
4287 nil))
4289 (defvar org-table-clean-did-remove-column nil)
4290 (defun org-table-map-tables (function &optional quietly)
4291 "Apply FUNCTION to the start of all tables in the buffer."
4292 (save-excursion
4293 (save-restriction
4294 (widen)
4295 (goto-char (point-min))
4296 (while (re-search-forward org-table-any-line-regexp nil t)
4297 (unless quietly
4298 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4299 (beginning-of-line 1)
4300 (when (and (looking-at org-table-line-regexp)
4301 ;; Exclude tables in src/example/verbatim/clocktable blocks
4302 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4303 (save-excursion (funcall function))
4304 (or (looking-at org-table-line-regexp)
4305 (forward-char 1)))
4306 (re-search-forward org-table-any-border-regexp nil 1))))
4307 (unless quietly (message "Mapping tables: done")))
4309 ;; Declare and autoload functions from ox.el and al.
4311 (declare-function org-export-get-environment "ox"
4312 (&optional backend subtreep ext-plist))
4313 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4315 ;; Declare and autoload functions from org-agenda.el
4317 (eval-and-compile
4318 (org-autoload "org-agenda"
4319 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4321 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4322 (declare-function org-clock-update-mode-line "org-clock" ())
4323 (declare-function org-resolve-clocks "org-clock"
4324 (&optional also-non-dangling-p prompt last-valid))
4326 (defun org-at-TBLFM-p (&optional pos)
4327 "Return t when point (or POS) is in #+TBLFM line."
4328 (save-excursion
4329 (let ((pos pos)))
4330 (goto-char (or pos (point)))
4331 (beginning-of-line 1)
4332 (looking-at org-TBLFM-regexp)))
4334 (defvar org-clock-start-time)
4335 (defvar org-clock-marker (make-marker)
4336 "Marker recording the last clock-in.")
4337 (defvar org-clock-hd-marker (make-marker)
4338 "Marker recording the last clock-in, but the headline position.")
4339 (defvar org-clock-heading ""
4340 "The heading of the current clock entry.")
4341 (defun org-clock-is-active ()
4342 "Return non-nil if clock is currently running.
4343 The return value is actually the clock marker."
4344 (marker-buffer org-clock-marker))
4346 (eval-and-compile
4347 (org-autoload "org-clock" '(org-clock-remove-overlays
4348 org-clock-update-time-maybe
4349 org-clocktable-shift)))
4351 (defun org-check-running-clock ()
4352 "Check if the current buffer contains the running clock.
4353 If yes, offer to stop it and to save the buffer with the changes."
4354 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4355 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4356 (buffer-name))))
4357 (org-clock-out)
4358 (when (y-or-n-p "Save changed buffer?")
4359 (save-buffer))))
4361 (defun org-clocktable-try-shift (dir n)
4362 "Check if this line starts a clock table, if yes, shift the time block."
4363 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4364 (org-clocktable-shift dir n)))
4366 ;;;###autoload
4367 (defun org-clock-persistence-insinuate ()
4368 "Set up hooks for clock persistence."
4369 (require 'org-clock)
4370 (add-hook 'org-mode-hook 'org-clock-load)
4371 (add-hook 'kill-emacs-hook 'org-clock-save))
4373 ;; Define the variable already here, to make sure we have it.
4374 (defvar org-indent-mode nil
4375 "Non-nil if Org-Indent mode is enabled.
4376 Use the command `org-indent-mode' to change this variable.")
4378 ;; Autoload archiving code
4379 ;; The stuff that is needed for cycling and tags has to be defined here.
4381 (defgroup org-archive nil
4382 "Options concerning archiving in Org-mode."
4383 :tag "Org Archive"
4384 :group 'org-structure)
4386 (defcustom org-archive-location "%s_archive::"
4387 "The location where subtrees should be archived.
4389 The value of this variable is a string, consisting of two parts,
4390 separated by a double-colon. The first part is a filename and
4391 the second part is a headline.
4393 When the filename is omitted, archiving happens in the same file.
4394 %s in the filename will be replaced by the current file
4395 name (without the directory part). Archiving to a different file
4396 is useful to keep archived entries from contributing to the
4397 Org-mode Agenda.
4399 The archived entries will be filed as subtrees of the specified
4400 headline. When the headline is omitted, the subtrees are simply
4401 filed away at the end of the file, as top-level entries. Also in
4402 the heading you can use %s to represent the file name, this can be
4403 useful when using the same archive for a number of different files.
4405 Here are a few examples:
4406 \"%s_archive::\"
4407 If the current file is Projects.org, archive in file
4408 Projects.org_archive, as top-level trees. This is the default.
4410 \"::* Archived Tasks\"
4411 Archive in the current file, under the top-level headline
4412 \"* Archived Tasks\".
4414 \"~/org/archive.org::\"
4415 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4417 \"~/org/archive.org::* From %s\"
4418 Archive in file ~/org/archive.org (absolute path), under headlines
4419 \"From FILENAME\" where file name is the current file name.
4421 \"~/org/datetree.org::datetree/* Finished Tasks\"
4422 The \"datetree/\" string is special, signifying to archive
4423 items to the datetree. Items are placed in either the CLOSED
4424 date of the item, or the current date if there is no CLOSED date.
4425 The heading will be a subentry to the current date. There doesn't
4426 need to be a heading, but there always needs to be a slash after
4427 datetree. For example, to store archived items directly in the
4428 datetree, use \"~/org/datetree.org::datetree/\".
4430 \"basement::** Finished Tasks\"
4431 Archive in file ./basement (relative path), as level 3 trees
4432 below the level 2 heading \"** Finished Tasks\".
4434 You may set this option on a per-file basis by adding to the buffer a
4435 line like
4437 #+ARCHIVE: basement::** Finished Tasks
4439 You may also define it locally for a subtree by setting an ARCHIVE property
4440 in the entry. If such a property is found in an entry, or anywhere up
4441 the hierarchy, it will be used."
4442 :group 'org-archive
4443 :type 'string)
4445 (defcustom org-archive-tag "ARCHIVE"
4446 "The tag that marks a subtree as archived.
4447 An archived subtree does not open during visibility cycling, and does
4448 not contribute to the agenda listings.
4449 After changing this, font-lock must be restarted in the relevant buffers to
4450 get the proper fontification."
4451 :group 'org-archive
4452 :group 'org-keywords
4453 :type 'string)
4455 (defcustom org-agenda-skip-archived-trees t
4456 "Non-nil means the agenda will skip any items located in archived trees.
4457 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4458 variable is no longer recommended, you should leave it at the value t.
4459 Instead, use the key `v' to cycle the archives-mode in the agenda."
4460 :group 'org-archive
4461 :group 'org-agenda-skip
4462 :type 'boolean)
4464 (defcustom org-columns-skip-archived-trees t
4465 "Non-nil means ignore archived trees when creating column view."
4466 :group 'org-archive
4467 :group 'org-properties
4468 :type 'boolean)
4470 (defcustom org-cycle-open-archived-trees nil
4471 "Non-nil means `org-cycle' will open archived trees.
4472 An archived tree is a tree marked with the tag ARCHIVE.
4473 When nil, archived trees will stay folded. You can still open them with
4474 normal outline commands like `show-all', but not with the cycling commands."
4475 :group 'org-archive
4476 :group 'org-cycle
4477 :type 'boolean)
4479 (defcustom org-sparse-tree-open-archived-trees nil
4480 "Non-nil means sparse tree construction shows matches in archived trees.
4481 When nil, matches in these trees are highlighted, but the trees are kept in
4482 collapsed state."
4483 :group 'org-archive
4484 :group 'org-sparse-trees
4485 :type 'boolean)
4487 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4488 "The default date type when building a sparse tree.
4489 When this is nil, a date is a scheduled or a deadline timestamp.
4490 Otherwise, these types are allowed:
4492 all: all timestamps
4493 active: only active timestamps (<...>)
4494 inactive: only inactive timestamps (<...)
4495 scheduled: only scheduled timestamps
4496 deadline: only deadline timestamps"
4497 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4498 (const :tag "All timestamps" all)
4499 (const :tag "Only active timestamps" active)
4500 (const :tag "Only inactive timestamps" inactive)
4501 (const :tag "Only scheduled timestamps" scheduled)
4502 (const :tag "Only deadline timestamps" deadline)
4503 (const :tag "Only closed timestamps" closed))
4504 :version "24.3"
4505 :group 'org-sparse-trees)
4507 (defun org-cycle-hide-archived-subtrees (state)
4508 "Re-hide all archived subtrees after a visibility state change."
4509 (when (and (not org-cycle-open-archived-trees)
4510 (not (memq state '(overview folded))))
4511 (save-excursion
4512 (let* ((globalp (memq state '(contents all)))
4513 (beg (if globalp (point-min) (point)))
4514 (end (if globalp (point-max) (org-end-of-subtree t))))
4515 (org-hide-archived-subtrees beg end)
4516 (goto-char beg)
4517 (if (looking-at (concat ".*:" org-archive-tag ":"))
4518 (message "%s" (substitute-command-keys
4519 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4521 (defun org-force-cycle-archived ()
4522 "Cycle subtree even if it is archived."
4523 (interactive)
4524 (setq this-command 'org-cycle)
4525 (let ((org-cycle-open-archived-trees t))
4526 (call-interactively 'org-cycle)))
4528 (defun org-hide-archived-subtrees (beg end)
4529 "Re-hide all archived subtrees after a visibility state change."
4530 (save-excursion
4531 (let* ((re (concat ":" org-archive-tag ":")))
4532 (goto-char beg)
4533 (while (re-search-forward re end t)
4534 (when (org-at-heading-p)
4535 (org-flag-subtree t)
4536 (org-end-of-subtree t))))))
4538 (declare-function outline-end-of-heading "outline" ())
4539 (declare-function outline-flag-region "outline" (from to flag))
4540 (defun org-flag-subtree (flag)
4541 (save-excursion
4542 (org-back-to-heading t)
4543 (outline-end-of-heading)
4544 (outline-flag-region (point)
4545 (progn (org-end-of-subtree t) (point))
4546 flag)))
4548 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4550 (eval-and-compile
4551 (org-autoload "org-archive"
4552 '(org-add-archive-files)))
4554 ;; Autoload Column View Code
4556 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4557 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4558 (declare-function org-columns-compute "org-colview" (property))
4560 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4561 '(org-columns-number-to-string
4562 org-columns-get-format-and-top-level
4563 org-columns-compute
4564 org-columns-remove-overlays))
4566 ;; Autoload ID code
4568 (declare-function org-id-store-link "org-id")
4569 (declare-function org-id-locations-load "org-id")
4570 (declare-function org-id-locations-save "org-id")
4571 (defvar org-id-track-globally)
4572 (org-autoload "org-id"
4573 '(org-id-new
4574 org-id-copy
4575 org-id-get-with-outline-path-completion
4576 org-id-get-with-outline-drilling))
4578 ;;; Variables for pre-computed regular expressions, all buffer local
4580 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4581 "Matches first line of a hidden block.")
4582 (make-variable-buffer-local 'org-drawer-regexp)
4583 (defvar org-todo-regexp nil
4584 "Matches any of the TODO state keywords.")
4585 (make-variable-buffer-local 'org-todo-regexp)
4586 (defvar org-not-done-regexp nil
4587 "Matches any of the TODO state keywords except the last one.")
4588 (make-variable-buffer-local 'org-not-done-regexp)
4589 (defvar org-not-done-heading-regexp nil
4590 "Matches a TODO headline that is not done.")
4591 (make-variable-buffer-local 'org-not-done-regexp)
4592 (defvar org-todo-line-regexp nil
4593 "Matches a headline and puts TODO state into group 2 if present.")
4594 (make-variable-buffer-local 'org-todo-line-regexp)
4595 (defvar org-complex-heading-regexp nil
4596 "Matches a headline and puts everything into groups:
4597 group 1: the stars
4598 group 2: The todo keyword, maybe
4599 group 3: Priority cookie
4600 group 4: True headline
4601 group 5: Tags")
4602 (make-variable-buffer-local 'org-complex-heading-regexp)
4603 (defvar org-complex-heading-regexp-format nil
4604 "Printf format to make regexp to match an exact headline.
4605 This regexp will match the headline of any node which has the
4606 exact headline text that is put into the format, but may have any
4607 TODO state, priority and tags.")
4608 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4609 (defvar org-todo-line-tags-regexp nil
4610 "Matches a headline and puts TODO state into group 2 if present.
4611 Also put tags into group 4 if tags are present.")
4612 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4613 (defvar org-ds-keyword-length 12
4614 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4615 (make-variable-buffer-local 'org-ds-keyword-length)
4616 (defvar org-deadline-regexp nil
4617 "Matches the DEADLINE keyword.")
4618 (make-variable-buffer-local 'org-deadline-regexp)
4619 (defvar org-deadline-time-regexp nil
4620 "Matches the DEADLINE keyword together with a time stamp.")
4621 (make-variable-buffer-local 'org-deadline-time-regexp)
4622 (defvar org-deadline-time-hour-regexp nil
4623 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4624 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4625 (defvar org-deadline-line-regexp nil
4626 "Matches the DEADLINE keyword and the rest of the line.")
4627 (make-variable-buffer-local 'org-deadline-line-regexp)
4628 (defvar org-scheduled-regexp nil
4629 "Matches the SCHEDULED keyword.")
4630 (make-variable-buffer-local 'org-scheduled-regexp)
4631 (defvar org-scheduled-time-regexp nil
4632 "Matches the SCHEDULED keyword together with a time stamp.")
4633 (make-variable-buffer-local 'org-scheduled-time-regexp)
4634 (defvar org-scheduled-time-hour-regexp nil
4635 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4636 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4637 (defvar org-closed-time-regexp nil
4638 "Matches the CLOSED keyword together with a time stamp.")
4639 (make-variable-buffer-local 'org-closed-time-regexp)
4641 (defvar org-keyword-time-regexp nil
4642 "Matches any of the 4 keywords, together with the time stamp.")
4643 (make-variable-buffer-local 'org-keyword-time-regexp)
4644 (defvar org-keyword-time-not-clock-regexp nil
4645 "Matches any of the 3 keywords, together with the time stamp.")
4646 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4647 (defvar org-maybe-keyword-time-regexp nil
4648 "Matches a timestamp, possibly preceded by a keyword.")
4649 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4650 (defvar org-all-time-keywords nil
4651 "List of time keywords.")
4652 (make-variable-buffer-local 'org-all-time-keywords)
4654 (defconst org-plain-time-of-day-regexp
4655 (concat
4656 "\\(\\<[012]?[0-9]"
4657 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4658 "\\(--?"
4659 "\\(\\<[012]?[0-9]"
4660 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4661 "\\)?")
4662 "Regular expression to match a plain time or time range.
4663 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4664 groups carry important information:
4665 0 the full match
4666 1 the first time, range or not
4667 8 the second time, if it is a range.")
4669 (defconst org-plain-time-extension-regexp
4670 (concat
4671 "\\(\\<[012]?[0-9]"
4672 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4673 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4674 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4675 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4676 groups carry important information:
4677 0 the full match
4678 7 hours of duration
4679 9 minutes of duration")
4681 (defconst org-stamp-time-of-day-regexp
4682 (concat
4683 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4684 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4685 "\\(--?"
4686 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4687 "Regular expression to match a timestamp time or time range.
4688 After a match, the following groups carry important information:
4689 0 the full match
4690 1 date plus weekday, for back referencing to make sure both times are on the same day
4691 2 the first time, range or not
4692 4 the second time, if it is a range.")
4694 (defconst org-startup-options
4695 '(("fold" org-startup-folded t)
4696 ("overview" org-startup-folded t)
4697 ("nofold" org-startup-folded nil)
4698 ("showall" org-startup-folded nil)
4699 ("showeverything" org-startup-folded showeverything)
4700 ("content" org-startup-folded content)
4701 ("indent" org-startup-indented t)
4702 ("noindent" org-startup-indented nil)
4703 ("hidestars" org-hide-leading-stars t)
4704 ("showstars" org-hide-leading-stars nil)
4705 ("odd" org-odd-levels-only t)
4706 ("oddeven" org-odd-levels-only nil)
4707 ("align" org-startup-align-all-tables t)
4708 ("noalign" org-startup-align-all-tables nil)
4709 ("inlineimages" org-startup-with-inline-images t)
4710 ("noinlineimages" org-startup-with-inline-images nil)
4711 ("latexpreview" org-startup-with-latex-preview t)
4712 ("nolatexpreview" org-startup-with-latex-preview nil)
4713 ("customtime" org-display-custom-times t)
4714 ("logdone" org-log-done time)
4715 ("lognotedone" org-log-done note)
4716 ("nologdone" org-log-done nil)
4717 ("lognoteclock-out" org-log-note-clock-out t)
4718 ("nolognoteclock-out" org-log-note-clock-out nil)
4719 ("logrepeat" org-log-repeat state)
4720 ("lognoterepeat" org-log-repeat note)
4721 ("logdrawer" org-log-into-drawer t)
4722 ("nologdrawer" org-log-into-drawer nil)
4723 ("logstatesreversed" org-log-states-order-reversed t)
4724 ("nologstatesreversed" org-log-states-order-reversed nil)
4725 ("nologrepeat" org-log-repeat nil)
4726 ("logreschedule" org-log-reschedule time)
4727 ("lognotereschedule" org-log-reschedule note)
4728 ("nologreschedule" org-log-reschedule nil)
4729 ("logredeadline" org-log-redeadline time)
4730 ("lognoteredeadline" org-log-redeadline note)
4731 ("nologredeadline" org-log-redeadline nil)
4732 ("logrefile" org-log-refile time)
4733 ("lognoterefile" org-log-refile note)
4734 ("nologrefile" org-log-refile nil)
4735 ("fninline" org-footnote-define-inline t)
4736 ("nofninline" org-footnote-define-inline nil)
4737 ("fnlocal" org-footnote-section nil)
4738 ("fnauto" org-footnote-auto-label t)
4739 ("fnprompt" org-footnote-auto-label nil)
4740 ("fnconfirm" org-footnote-auto-label confirm)
4741 ("fnplain" org-footnote-auto-label plain)
4742 ("fnadjust" org-footnote-auto-adjust t)
4743 ("nofnadjust" org-footnote-auto-adjust nil)
4744 ("constcgs" constants-unit-system cgs)
4745 ("constSI" constants-unit-system SI)
4746 ("noptag" org-tag-persistent-alist nil)
4747 ("hideblocks" org-hide-block-startup t)
4748 ("nohideblocks" org-hide-block-startup nil)
4749 ("beamer" org-startup-with-beamer-mode t)
4750 ("entitiespretty" org-pretty-entities t)
4751 ("entitiesplain" org-pretty-entities nil))
4752 "Variable associated with STARTUP options for org-mode.
4753 Each element is a list of three items: the startup options (as written
4754 in the #+STARTUP line), the corresponding variable, and the value to set
4755 this variable to if the option is found. An optional forth element PUSH
4756 means to push this value onto the list in the variable.")
4758 (defun org-update-property-plist (key val props)
4759 "Update PROPS with KEY and VAL."
4760 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4761 (key (if appending (substring key 0 (- (length key) 1)) key))
4762 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4763 (previous (cdr (assoc key props))))
4764 (if appending
4765 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4766 (cons (cons key val) remainder))))
4768 (defconst org-block-regexp
4769 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4770 "Regular expression for hiding blocks.")
4771 (defconst org-heading-keyword-regexp-format
4772 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4773 "Printf format for a regexp matching a headline with some keyword.
4774 This regexp will match the headline of any node which has the
4775 exact keyword that is put into the format. The keyword isn't in
4776 any group by default, but the stars and the body are.")
4777 (defconst org-heading-keyword-maybe-regexp-format
4778 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4779 "Printf format for a regexp matching a headline, possibly with some keyword.
4780 This regexp can match any headline with the specified keyword, or
4781 without a keyword. The keyword isn't in any group by default,
4782 but the stars and the body are.")
4784 (defcustom org-group-tags t
4785 "When non-nil (the default), use group tags.
4786 This can be turned on/off through `org-toggle-tags-groups'."
4787 :group 'org-tags
4788 :group 'org-startup
4789 :type 'boolean)
4791 (defun org-toggle-tags-groups ()
4792 "Toggle support for group tags.
4793 Support for group tags is controlled by the option
4794 `org-group-tags', which is non-nil by default."
4795 (interactive)
4796 (setq org-group-tags (not org-group-tags))
4797 (cond ((and (derived-mode-p 'org-agenda-mode)
4798 org-group-tags)
4799 (org-agenda-redo))
4800 ((derived-mode-p 'org-mode)
4801 (let ((org-inhibit-startup t)) (org-mode))))
4802 (message "Groups tags support has been turned %s"
4803 (if org-group-tags "on" "off")))
4805 (defun org-set-regexps-and-options-for-tags ()
4806 "Precompute regular expressions used for tags in the current buffer."
4807 (when (derived-mode-p 'org-mode)
4808 (org-set-local 'org-file-tags nil)
4809 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4810 (splitre "[ \t]+")
4811 (start 0)
4812 tags ftags key value)
4813 (save-excursion
4814 (save-restriction
4815 (widen)
4816 (goto-char (point-min))
4817 (while (re-search-forward re nil t)
4818 (setq key (upcase (org-match-string-no-properties 1))
4819 value (org-match-string-no-properties 2))
4820 (if (stringp value) (setq value (org-trim value)))
4821 (cond
4822 ((equal key "TAGS")
4823 (setq tags (append tags (if tags '("\\n") nil)
4824 (org-split-string value splitre))))
4825 ((equal key "FILETAGS")
4826 (when (string-match "\\S-" value)
4827 (setq ftags
4828 (append
4829 ftags
4830 (apply 'append
4831 (mapcar (lambda (x) (org-split-string x ":"))
4832 (org-split-string value)))))))))))
4833 ;; Process the file tags.
4834 (and ftags (org-set-local 'org-file-tags
4835 (mapcar 'org-add-prop-inherited ftags)))
4836 (org-set-local 'org-tag-groups-alist nil)
4837 ;; Process the tags.
4838 ;; FIXME
4839 (when tags
4840 (let (e tgs g)
4841 (while (setq e (pop tags))
4842 (cond
4843 ((equal e "{")
4844 (progn (push '(:startgroup) tgs)
4845 (when (equal (nth 1 tags) ":")
4846 (push (list (replace-regexp-in-string
4847 "(.+)$" "" (nth 0 tags)))
4848 org-tag-groups-alist)
4849 (setq g 0))))
4850 ((equal e ":") (push '(:grouptags) tgs))
4851 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4852 ((equal e "\\n") (push '(:newline) tgs))
4853 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4854 (push (cons (match-string 1 e)
4855 (string-to-char (match-string 2 e))) tgs)
4856 (if (and g (> g 0))
4857 (setcar org-tag-groups-alist
4858 (append (car org-tag-groups-alist)
4859 (list (match-string 1 e)))))
4860 (if g (setq g (1+ g))))
4861 (t (push (list e) tgs)
4862 (if (and g (> g 0))
4863 (setcar org-tag-groups-alist
4864 (append (car org-tag-groups-alist) (list e))))
4865 (if g (setq g (1+ g))))))
4866 (org-set-local 'org-tag-alist nil)
4867 (while (setq e (pop tgs))
4868 (or (and (stringp (car e))
4869 (assoc (car e) org-tag-alist))
4870 (push e org-tag-alist))))))))
4872 (defun org-set-regexps-and-options ()
4873 "Precompute regular expressions used in the current buffer."
4874 (when (derived-mode-p 'org-mode)
4875 (org-set-local 'org-todo-kwd-alist nil)
4876 (org-set-local 'org-todo-key-alist nil)
4877 (org-set-local 'org-todo-key-trigger nil)
4878 (org-set-local 'org-todo-keywords-1 nil)
4879 (org-set-local 'org-done-keywords nil)
4880 (org-set-local 'org-todo-heads nil)
4881 (org-set-local 'org-todo-sets nil)
4882 (org-set-local 'org-todo-log-states nil)
4883 (org-set-local 'org-file-properties nil)
4884 (let ((re (org-make-options-regexp
4885 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4886 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4887 "SETUPFILE" "OPTIONS")
4888 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4889 (splitre "[ \t]+")
4890 (scripts org-use-sub-superscripts)
4891 kwds kws0 kwsa key log value cat arch const links hw dws
4892 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4893 (start 0))
4894 (save-excursion
4895 (save-restriction
4896 (widen)
4897 (goto-char (point-min))
4898 (while (or (and ext-setup-or-nil
4899 (let (ret)
4900 (with-temp-buffer
4901 (insert ext-setup-or-nil)
4902 (let ((major-mode 'org-mode))
4903 (org-set-regexps-and-options-for-tags)
4904 (setq ret (list org-file-tags org-tag-alist
4905 org-tag-groups-alist))))
4906 (setq org-file-tags (nth 0 ret)
4907 org-tag-alist (nth 1 ret)
4908 org-tag-groups-alist (nth 2 ret))))
4909 (and ext-setup-or-nil
4910 (string-match re ext-setup-or-nil start)
4911 (setq start (match-end 0)))
4912 (and (setq ext-setup-or-nil nil start 0)
4913 (re-search-forward re nil t)))
4914 (setq key (upcase (match-string 1 ext-setup-or-nil))
4915 value (org-match-string-no-properties 2 ext-setup-or-nil))
4916 (if (stringp value) (setq value (org-trim value)))
4917 (cond
4918 ((equal key "CATEGORY")
4919 (setq cat value))
4920 ((member key '("SEQ_TODO" "TODO"))
4921 (push (cons 'sequence (org-split-string value splitre)) kwds))
4922 ((equal key "TYP_TODO")
4923 (push (cons 'type (org-split-string value splitre)) kwds))
4924 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4925 ;; general TODO-like setup
4926 (push (cons (intern (downcase (match-string 1 key)))
4927 (org-split-string value splitre)) kwds))
4928 ((equal key "COLUMNS")
4929 (org-set-local 'org-columns-default-format value))
4930 ((equal key "LINK")
4931 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4932 (push (cons (match-string 1 value)
4933 (org-trim (match-string 2 value)))
4934 links)))
4935 ((equal key "PRIORITIES")
4936 (setq prio (org-split-string value " +")))
4937 ((equal key "PROPERTY")
4938 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4939 (setq props (org-update-property-plist (match-string 1 value)
4940 (match-string 2 value)
4941 props))))
4942 ((equal key "DRAWERS")
4943 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4944 ((equal key "CONSTANTS")
4945 (org-table-set-constants))
4946 ((equal key "STARTUP")
4947 (let ((opts (org-split-string value splitre))
4948 l var val)
4949 (while (setq l (pop opts))
4950 (when (setq l (assoc l org-startup-options))
4951 (setq var (nth 1 l) val (nth 2 l))
4952 (if (not (nth 3 l))
4953 (set (make-local-variable var) val)
4954 (if (not (listp (symbol-value var)))
4955 (set (make-local-variable var) nil))
4956 (set (make-local-variable var) (symbol-value var))
4957 (add-to-list var val))))))
4958 ((equal key "ARCHIVE")
4959 (setq arch value)
4960 (remove-text-properties 0 (length arch)
4961 '(face t fontified t) arch))
4962 ((equal key "OPTIONS")
4963 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4964 (setq scripts (read (match-string 2 value)))))
4965 ((and (equal key "SETUPFILE")
4966 ;; Prevent checking in Gnus messages
4967 (not buffer-read-only))
4968 (setq setup-contents (org-file-contents
4969 (expand-file-name
4970 (org-remove-double-quotes value))
4971 'noerror))
4972 (if (not ext-setup-or-nil)
4973 (setq ext-setup-or-nil setup-contents start 0)
4974 (setq ext-setup-or-nil
4975 (concat (substring ext-setup-or-nil 0 start)
4976 "\n" setup-contents "\n"
4977 (substring ext-setup-or-nil start)))))))
4978 ;; search for property blocks
4979 (goto-char (point-min))
4980 (while (re-search-forward org-block-regexp nil t)
4981 (when (equal "PROPERTY" (upcase (match-string 1)))
4982 (setq value (replace-regexp-in-string
4983 "[\n\r]" " " (match-string 4)))
4984 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4985 (setq props (org-update-property-plist (match-string 1 value)
4986 (match-string 2 value)
4987 props)))))))
4988 (org-set-local 'org-use-sub-superscripts scripts)
4989 (when cat
4990 (org-set-local 'org-category (intern cat))
4991 (push (cons "CATEGORY" cat) props))
4992 (when prio
4993 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4994 (setq prio (mapcar 'string-to-char prio))
4995 (org-set-local 'org-highest-priority (nth 0 prio))
4996 (org-set-local 'org-lowest-priority (nth 1 prio))
4997 (org-set-local 'org-default-priority (nth 2 prio)))
4998 (and props (org-set-local 'org-file-properties (nreverse props)))
4999 (and drawers (org-set-local 'org-drawers drawers))
5000 (and arch (org-set-local 'org-archive-location arch))
5001 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5002 ;; Process the TODO keywords
5003 (unless kwds
5004 ;; Use the global values as if they had been given locally.
5005 (setq kwds (default-value 'org-todo-keywords))
5006 (if (stringp (car kwds))
5007 (setq kwds (list (cons org-todo-interpretation
5008 (default-value 'org-todo-keywords)))))
5009 (setq kwds (reverse kwds)))
5010 (setq kwds (nreverse kwds))
5011 (let (inter kws kw)
5012 (while (setq kws (pop kwds))
5013 (let ((kws (or
5014 (run-hook-with-args-until-success
5015 'org-todo-setup-filter-hook kws)
5016 kws)))
5017 (setq inter (pop kws) sep (member "|" kws)
5018 kws0 (delete "|" (copy-sequence kws))
5019 kwsa nil
5020 kws1 (mapcar
5021 (lambda (x)
5022 ;; 1 2
5023 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5024 (progn
5025 (setq kw (match-string 1 x)
5026 key (and (match-end 2) (match-string 2 x))
5027 log (org-extract-log-state-settings x))
5028 (push (cons kw (and key (string-to-char key))) kwsa)
5029 (and log (push log org-todo-log-states))
5031 (error "Invalid TODO keyword %s" x)))
5032 kws0)
5033 kwsa (if kwsa (append '((:startgroup))
5034 (nreverse kwsa)
5035 '((:endgroup))))
5036 hw (car kws1)
5037 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5038 tail (list inter hw (car dws) (org-last dws))))
5039 (add-to-list 'org-todo-heads hw 'append)
5040 (push kws1 org-todo-sets)
5041 (setq org-done-keywords (append org-done-keywords dws nil))
5042 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5043 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5044 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5045 (setq org-todo-sets (nreverse org-todo-sets)
5046 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5047 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5048 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5049 ;; Compute the regular expressions and other local variables.
5050 ;; Using `org-outline-regexp-bol' would complicate them much,
5051 ;; because of the fixed white space at the end of that string.
5052 (if (not org-done-keywords)
5053 (setq org-done-keywords (and org-todo-keywords-1
5054 (list (org-last org-todo-keywords-1)))))
5055 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5056 (length org-scheduled-string)
5057 (length org-clock-string)
5058 (length org-closed-string)))
5059 org-drawer-regexp
5060 (concat "^[ \t]*:\\("
5061 (mapconcat 'regexp-quote org-drawers "\\|")
5062 "\\):[ \t]*$")
5063 org-not-done-keywords
5064 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5065 org-todo-regexp
5066 (concat "\\("
5067 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5068 "\\)")
5069 org-not-done-regexp
5070 (concat "\\("
5071 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5072 "\\)")
5073 org-not-done-heading-regexp
5074 (format org-heading-keyword-regexp-format org-not-done-regexp)
5075 org-todo-line-regexp
5076 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5077 org-complex-heading-regexp
5078 (concat "^\\(\\*+\\)"
5079 "\\(?: +" org-todo-regexp "\\)?"
5080 "\\(?: +\\(\\[#.\\]\\)\\)?"
5081 "\\(?: +\\(.*?\\)\\)??"
5082 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5083 "[ \t]*$")
5084 org-complex-heading-regexp-format
5085 (concat "^\\(\\*+\\)"
5086 "\\(?: +" org-todo-regexp "\\)?"
5087 "\\(?: +\\(\\[#.\\]\\)\\)?"
5088 "\\(?: +"
5089 ;; Stats cookies can be stuck to body.
5090 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5091 "\\(%s\\)"
5092 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5093 "\\)"
5094 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5095 "[ \t]*$")
5096 org-todo-line-tags-regexp
5097 (concat "^\\(\\*+\\)"
5098 "\\(?: +" org-todo-regexp "\\)?"
5099 "\\(?: +\\(.*?\\)\\)??"
5100 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5101 "[ \t]*$")
5102 org-deadline-regexp (concat "\\<" org-deadline-string)
5103 org-deadline-time-regexp
5104 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5105 org-deadline-time-hour-regexp
5106 (concat "\\<" org-deadline-string
5107 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5108 org-deadline-line-regexp
5109 (concat "\\<\\(" org-deadline-string "\\).*")
5110 org-scheduled-regexp
5111 (concat "\\<" org-scheduled-string)
5112 org-scheduled-time-regexp
5113 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5114 org-scheduled-time-hour-regexp
5115 (concat "\\<" org-scheduled-string
5116 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5117 org-closed-time-regexp
5118 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5119 org-keyword-time-regexp
5120 (concat "\\<\\(" org-scheduled-string
5121 "\\|" org-deadline-string
5122 "\\|" org-closed-string
5123 "\\|" org-clock-string "\\)"
5124 " *[[<]\\([^]>]+\\)[]>]")
5125 org-keyword-time-not-clock-regexp
5126 (concat "\\<\\(" org-scheduled-string
5127 "\\|" org-deadline-string
5128 "\\|" org-closed-string
5129 "\\)"
5130 " *[[<]\\([^]>]+\\)[]>]")
5131 org-maybe-keyword-time-regexp
5132 (concat "\\(\\<\\(" org-scheduled-string
5133 "\\|" org-deadline-string
5134 "\\|" org-closed-string
5135 "\\|" org-clock-string "\\)\\)?"
5136 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5137 org-all-time-keywords
5138 (mapcar (lambda (w) (substring w 0 -1))
5139 (list org-scheduled-string org-deadline-string
5140 org-clock-string org-closed-string)))
5141 (org-compute-latex-and-related-regexp)
5142 (org-set-font-lock-defaults))))
5144 (defun org-file-contents (file &optional noerror)
5145 "Return the contents of FILE, as a string."
5146 (if (or (not file)
5147 (not (file-readable-p file)))
5148 (if noerror
5149 (message "Cannot read file \"%s\"" file)
5150 (error "Cannot read file \"%s\"" file))
5151 (with-temp-buffer
5152 (insert-file-contents file)
5153 (buffer-string))))
5155 (defun org-extract-log-state-settings (x)
5156 "Extract the log state setting from a TODO keyword string.
5157 This will extract info from a string like \"WAIT(w@/!)\"."
5158 (let (kw key log1 log2)
5159 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5160 (setq kw (match-string 1 x)
5161 key (and (match-end 2) (match-string 2 x))
5162 log1 (and (match-end 3) (match-string 3 x))
5163 log2 (and (match-end 4) (match-string 4 x)))
5164 (and (or log1 log2)
5165 (list kw
5166 (and log1 (if (equal log1 "!") 'time 'note))
5167 (and log2 (if (equal log2 "!") 'time 'note)))))))
5169 (defun org-remove-keyword-keys (list)
5170 "Remove a pair of parenthesis at the end of each string in LIST."
5171 (mapcar (lambda (x)
5172 (if (string-match "(.*)$" x)
5173 (substring x 0 (match-beginning 0))
5175 list))
5177 (defun org-assign-fast-keys (alist)
5178 "Assign fast keys to a keyword-key alist.
5179 Respect keys that are already there."
5180 (let (new e (alt ?0))
5181 (while (setq e (pop alist))
5182 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5183 (cdr e)) ;; Key already assigned.
5184 (push e new)
5185 (let ((clist (string-to-list (downcase (car e))))
5186 (used (append new alist)))
5187 (when (= (car clist) ?@)
5188 (pop clist))
5189 (while (and clist (rassoc (car clist) used))
5190 (pop clist))
5191 (unless clist
5192 (while (rassoc alt used)
5193 (incf alt)))
5194 (push (cons (car e) (or (car clist) alt)) new))))
5195 (nreverse new)))
5197 ;;; Some variables used in various places
5199 (defvar org-window-configuration nil
5200 "Used in various places to store a window configuration.")
5201 (defvar org-selected-window nil
5202 "Used in various places to store a window configuration.")
5203 (defvar org-finish-function nil
5204 "Function to be called when `C-c C-c' is used.
5205 This is for getting out of special buffers like capture.")
5208 ;; FIXME: Occasionally check by commenting these, to make sure
5209 ;; no other functions uses these, forgetting to let-bind them.
5210 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5211 (defvar org-last-state)
5212 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5214 ;; Defined somewhere in this file, but used before definition.
5215 (defvar org-entities) ;; defined in org-entities.el
5216 (defvar org-struct-menu)
5217 (defvar org-org-menu)
5218 (defvar org-tbl-menu)
5220 ;;;; Define the Org-mode
5222 ;; We use a before-change function to check if a table might need
5223 ;; an update.
5224 (defvar org-table-may-need-update t
5225 "Indicates that a table might need an update.
5226 This variable is set by `org-before-change-function'.
5227 `org-table-align' sets it back to nil.")
5228 (defun org-before-change-function (beg end)
5229 "Every change indicates that a table might need an update."
5230 (setq org-table-may-need-update t))
5231 (defvar org-mode-map)
5232 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5233 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5234 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5235 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5236 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5237 (defvar org-table-buffer-is-an nil)
5239 (defvar bidi-paragraph-direction)
5240 (defvar buffer-face-mode-face)
5242 (require 'outline)
5243 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5244 (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"))
5245 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5247 ;; Other stuff we need.
5248 (require 'time-date)
5249 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5250 (require 'easymenu)
5251 (require 'overlay)
5253 ;; (require 'org-macs) moved higher up in the file before it is first used
5254 (require 'org-entities)
5255 ;; (require 'org-compat) moved higher up in the file before it is first used
5256 (require 'org-faces)
5257 (require 'org-list)
5258 (require 'org-pcomplete)
5259 (require 'org-src)
5260 (require 'org-footnote)
5261 (require 'org-macro)
5263 ;; babel
5264 (require 'ob)
5266 ;;;###autoload
5267 (define-derived-mode org-mode outline-mode "Org"
5268 "Outline-based notes management and organizer, alias
5269 \"Carsten's outline-mode for keeping track of everything.\"
5271 Org-mode develops organizational tasks around a NOTES file which
5272 contains information about projects as plain text. Org-mode is
5273 implemented on top of outline-mode, which is ideal to keep the content
5274 of large files well structured. It supports ToDo items, deadlines and
5275 time stamps, which magically appear in the diary listing of the Emacs
5276 calendar. Tables are easily created with a built-in table editor.
5277 Plain text URL-like links connect to websites, emails (VM), Usenet
5278 messages (Gnus), BBDB entries, and any files related to the project.
5279 For printing and sharing of notes, an Org-mode file (or a part of it)
5280 can be exported as a structured ASCII or HTML file.
5282 The following commands are available:
5284 \\{org-mode-map}"
5286 ;; Get rid of Outline menus, they are not needed
5287 ;; Need to do this here because define-derived-mode sets up
5288 ;; the keymap so late. Still, it is a waste to call this each time
5289 ;; we switch another buffer into org-mode.
5290 (if (featurep 'xemacs)
5291 (when (boundp 'outline-mode-menu-heading)
5292 ;; Assume this is Greg's port, it uses easymenu
5293 (easy-menu-remove outline-mode-menu-heading)
5294 (easy-menu-remove outline-mode-menu-show)
5295 (easy-menu-remove outline-mode-menu-hide))
5296 (define-key org-mode-map [menu-bar headings] 'undefined)
5297 (define-key org-mode-map [menu-bar hide] 'undefined)
5298 (define-key org-mode-map [menu-bar show] 'undefined))
5300 (org-load-modules-maybe)
5301 (easy-menu-add org-org-menu)
5302 (easy-menu-add org-tbl-menu)
5303 (org-install-agenda-files-menu)
5304 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5305 (add-to-invisibility-spec '(org-cwidth))
5306 (add-to-invisibility-spec '(org-hide-block . t))
5307 (when (featurep 'xemacs)
5308 (org-set-local 'line-move-ignore-invisible t))
5309 (org-set-local 'outline-regexp org-outline-regexp)
5310 (org-set-local 'outline-level 'org-outline-level)
5311 (setq bidi-paragraph-direction 'left-to-right)
5312 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5313 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5314 (when (and org-ellipsis
5315 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5316 (fboundp 'make-glyph-code))
5317 (unless org-display-table
5318 (setq org-display-table (make-display-table)))
5319 (set-display-table-slot
5320 org-display-table 4
5321 (vconcat (mapcar
5322 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5323 org-ellipsis)))
5324 (if (stringp org-ellipsis) org-ellipsis "..."))))
5325 (setq buffer-display-table org-display-table))
5326 (org-set-regexps-and-options-for-tags)
5327 (org-set-regexps-and-options)
5328 (when (and org-tag-faces (not org-tags-special-faces-re))
5329 ;; tag faces set outside customize.... force initialization.
5330 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5331 ;; Calc embedded
5332 (org-set-local 'calc-embedded-open-mode "# ")
5333 ;; Modify a few syntax entries
5334 (modify-syntax-entry ?@ "w")
5335 (modify-syntax-entry ?\" "\"")
5336 (if org-startup-truncated (setq truncate-lines t))
5337 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5338 (org-set-local 'font-lock-unfontify-region-function
5339 'org-unfontify-region)
5340 ;; Activate before-change-function
5341 (org-set-local 'org-table-may-need-update t)
5342 (org-add-hook 'before-change-functions 'org-before-change-function nil
5343 'local)
5344 ;; Check for running clock before killing a buffer
5345 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5346 ;; Initialize macros templates.
5347 (org-macro-initialize-templates)
5348 ;; Initialize radio targets.
5349 (org-update-radio-target-regexp)
5350 ;; Indentation.
5351 (org-set-local 'indent-line-function 'org-indent-line)
5352 (org-set-local 'indent-region-function 'org-indent-region)
5353 ;; Filling and auto-filling.
5354 (org-setup-filling)
5355 ;; Comments.
5356 (org-setup-comments-handling)
5357 ;; Beginning/end of defun
5358 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5359 (org-set-local 'end-of-defun-function 'org-forward-element)
5360 ;; Next error for sparse trees
5361 (org-set-local 'next-error-function 'org-occur-next-match)
5362 ;; Make sure dependence stuff works reliably, even for users who set it
5363 ;; too late :-(
5364 (if org-enforce-todo-dependencies
5365 (add-hook 'org-blocker-hook
5366 'org-block-todo-from-children-or-siblings-or-parent)
5367 (remove-hook 'org-blocker-hook
5368 'org-block-todo-from-children-or-siblings-or-parent))
5369 (if org-enforce-todo-checkbox-dependencies
5370 (add-hook 'org-blocker-hook
5371 'org-block-todo-from-checkboxes)
5372 (remove-hook 'org-blocker-hook
5373 'org-block-todo-from-checkboxes))
5375 ;; Align options lines
5376 (org-set-local
5377 'align-mode-rules-list
5378 '((org-in-buffer-settings
5379 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5380 (modes . '(org-mode)))))
5382 ;; Imenu
5383 (org-set-local 'imenu-create-index-function
5384 'org-imenu-get-tree)
5386 ;; Make isearch reveal context
5387 (if (or (featurep 'xemacs)
5388 (not (boundp 'outline-isearch-open-invisible-function)))
5389 ;; Emacs 21 and XEmacs make use of the hook
5390 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5391 ;; Emacs 22 deals with this through a special variable
5392 (org-set-local 'outline-isearch-open-invisible-function
5393 (lambda (&rest ignore) (org-show-context 'isearch)))
5394 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5396 ;; Setup the pcomplete hooks
5397 (set (make-local-variable 'pcomplete-command-completion-function)
5398 'org-pcomplete-initial)
5399 (set (make-local-variable 'pcomplete-command-name-function)
5400 'org-command-at-point)
5401 (set (make-local-variable 'pcomplete-default-completion-function)
5402 'ignore)
5403 (set (make-local-variable 'pcomplete-parse-arguments-function)
5404 'org-parse-arguments)
5405 (set (make-local-variable 'pcomplete-termination-string) "")
5406 (when (>= emacs-major-version 23)
5407 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5409 ;; If empty file that did not turn on org-mode automatically, make it to.
5410 (if (and org-insert-mode-line-in-empty-file
5411 (org-called-interactively-p 'any)
5412 (= (point-min) (point-max)))
5413 (insert "# -*- mode: org -*-\n\n"))
5414 (unless org-inhibit-startup
5415 (org-unmodified
5416 (and org-startup-with-beamer-mode (org-beamer-mode))
5417 (when org-startup-align-all-tables
5418 (org-table-map-tables 'org-table-align 'quietly))
5419 (when org-startup-with-inline-images
5420 (org-display-inline-images))
5421 (when org-startup-with-latex-preview
5422 (org-preview-latex-fragment))
5423 (unless org-inhibit-startup-visibility-stuff
5424 (org-set-startup-visibility))))
5425 ;; Try to set org-hide correctly
5426 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5428 ;; Update `customize-package-emacs-version-alist'
5429 (add-to-list 'customize-package-emacs-version-alist
5430 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5431 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5432 ("8.0" . "24.4")))
5434 (defvar org-mode-transpose-word-syntax-table
5435 (let ((st (make-syntax-table)))
5436 (mapc (lambda(c) (modify-syntax-entry
5437 (string-to-char (car c)) "w p" st))
5438 org-emphasis-alist)
5439 st))
5441 (when (fboundp 'abbrev-table-put)
5442 (abbrev-table-put org-mode-abbrev-table
5443 :parents (list text-mode-abbrev-table)))
5445 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5447 (defsubst org-fix-ellipsis-at-bol ()
5448 (save-excursion (goto-char (window-start)) (recenter 0)))
5450 (defun org-find-invisible-foreground ()
5451 (let ((candidates (remove
5452 "unspecified-bg"
5453 (nconc
5454 (list (face-background 'default)
5455 (face-background 'org-default))
5456 (mapcar
5457 (lambda (alist)
5458 (when (boundp alist)
5459 (cdr (assoc 'background-color (symbol-value alist)))))
5460 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5461 (list (face-foreground 'org-hide))))))
5462 (car (remove nil candidates))))
5464 (defun org-current-time (&optional rounding-minutes past)
5465 "Current time, possibly rounded to ROUNDING-MINUTES.
5466 When ROUNDING-MINUTES is not an integer, fall back on the car of
5467 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5468 the rounding returns a past time."
5469 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5470 (car org-time-stamp-rounding-minutes)))
5471 (time (decode-time)) res)
5472 (if (< r 1)
5473 (current-time)
5474 (setq res
5475 (apply 'encode-time
5476 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5477 (nthcdr 2 time))))
5478 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5479 (seconds-to-time (- (org-float-time res) (* r 60)))
5480 res))))
5482 (defun org-today ()
5483 "Return today date, considering `org-extend-today-until'."
5484 (time-to-days
5485 (time-subtract (current-time)
5486 (list 0 (* 3600 org-extend-today-until) 0))))
5488 ;;;; Font-Lock stuff, including the activators
5490 (defvar org-mouse-map (make-sparse-keymap))
5491 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5492 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5493 (when org-mouse-1-follows-link
5494 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5495 (when org-tab-follows-link
5496 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5497 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5499 (require 'font-lock)
5501 (defconst org-non-link-chars "]\t\n\r<>")
5502 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5503 "shell" "elisp" "doi" "message"))
5504 (defvar org-link-types-re nil
5505 "Matches a link that has a url-like prefix like \"http:\"")
5506 (defvar org-link-re-with-space nil
5507 "Matches a link with spaces, optional angular brackets around it.")
5508 (defvar org-link-re-with-space2 nil
5509 "Matches a link with spaces, optional angular brackets around it.")
5510 (defvar org-link-re-with-space3 nil
5511 "Matches a link with spaces, only for internal part in bracket links.")
5512 (defvar org-angle-link-re nil
5513 "Matches link with angular brackets, spaces are allowed.")
5514 (defvar org-plain-link-re nil
5515 "Matches plain link, without spaces.")
5516 (defvar org-bracket-link-regexp nil
5517 "Matches a link in double brackets.")
5518 (defvar org-bracket-link-analytic-regexp nil
5519 "Regular expression used to analyze links.
5520 Here is what the match groups contain after a match:
5521 1: http:
5522 2: http
5523 3: path
5524 4: [desc]
5525 5: desc")
5526 (defvar org-bracket-link-analytic-regexp++ nil
5527 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5528 (defvar org-any-link-re nil
5529 "Regular expression matching any link.")
5531 (defconst org-match-sexp-depth 3
5532 "Number of stacked braces for sub/superscript matching.")
5534 (defun org-create-multibrace-regexp (left right n)
5535 "Create a regular expression which will match a balanced sexp.
5536 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5537 as single character strings.
5538 The regexp returned will match the entire expression including the
5539 delimiters. It will also define a single group which contains the
5540 match except for the outermost delimiters. The maximum depth of
5541 stacked delimiters is N. Escaping delimiters is not possible."
5542 (let* ((nothing (concat "[^" left right "]*?"))
5543 (or "\\|")
5544 (re nothing)
5545 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5546 (while (> n 1)
5547 (setq n (1- n)
5548 re (concat re or next)
5549 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5550 (concat left "\\(" re "\\)" right)))
5552 (defvar org-match-substring-regexp
5553 (concat
5554 "\\(\\S-\\)\\([_^]\\)\\("
5555 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5556 "\\|"
5557 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5558 "\\|"
5559 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5560 "The regular expression matching a sub- or superscript.")
5562 (defvar org-match-substring-with-braces-regexp
5563 (concat
5564 "\\(\\S-\\)\\([_^]\\)\\("
5565 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5566 "\\)")
5567 "The regular expression matching a sub- or superscript, forcing braces.")
5569 (defun org-make-link-regexps ()
5570 "Update the link regular expressions.
5571 This should be called after the variable `org-link-types' has changed."
5572 (setq org-link-types-re
5573 (concat
5574 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5575 org-link-re-with-space
5576 (concat
5577 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5578 "\\([^" org-non-link-chars " ]"
5579 "[^" org-non-link-chars "]*"
5580 "[^" org-non-link-chars " ]\\)>?")
5581 org-link-re-with-space2
5582 (concat
5583 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5584 "\\([^" org-non-link-chars " ]"
5585 "[^\t\n\r]*"
5586 "[^" org-non-link-chars " ]\\)>?")
5587 org-link-re-with-space3
5588 (concat
5589 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5590 "\\([^" org-non-link-chars " ]"
5591 "[^\t\n\r]*\\)")
5592 org-angle-link-re
5593 (concat
5594 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5595 "\\([^" org-non-link-chars " ]"
5596 "[^" org-non-link-chars "]*"
5597 "\\)>")
5598 org-plain-link-re
5599 (concat
5600 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5601 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5602 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5603 org-bracket-link-regexp
5604 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5605 org-bracket-link-analytic-regexp
5606 (concat
5607 "\\[\\["
5608 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5609 "\\([^]]+\\)"
5610 "\\]"
5611 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5612 "\\]")
5613 org-bracket-link-analytic-regexp++
5614 (concat
5615 "\\[\\["
5616 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5617 "\\([^]]+\\)"
5618 "\\]"
5619 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5620 "\\]")
5621 org-any-link-re
5622 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5623 org-angle-link-re "\\)\\|\\("
5624 org-plain-link-re "\\)")))
5626 (org-make-link-regexps)
5628 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5629 "Regular expression for fast time stamp matching.")
5630 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5631 "Regular expression for fast time stamp matching.")
5632 (defconst org-ts-regexp0
5633 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5634 "Regular expression matching time strings for analysis.
5635 This one does not require the space after the date, so it can be used
5636 on a string that terminates immediately after the date.")
5637 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5638 "Regular expression matching time strings for analysis.")
5639 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5640 "Regular expression matching time stamps, with groups.")
5641 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5642 "Regular expression matching time stamps (also [..]), with groups.")
5643 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5644 "Regular expression matching a time stamp range.")
5645 (defconst org-tr-regexp-both
5646 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5647 "Regular expression matching a time stamp range.")
5648 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5649 org-ts-regexp "\\)?")
5650 "Regular expression matching a time stamp or time stamp range.")
5651 (defconst org-tsr-regexp-both
5652 (concat org-ts-regexp-both "\\(--?-?"
5653 org-ts-regexp-both "\\)?")
5654 "Regular expression matching a time stamp or time stamp range.
5655 The time stamps may be either active or inactive.")
5657 (defvar org-emph-face nil)
5659 (defun org-do-emphasis-faces (limit)
5660 "Run through the buffer and add overlays to emphasized strings."
5661 (let (rtn a)
5662 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5663 (if (not (= (char-after (match-beginning 3))
5664 (char-after (match-beginning 4))))
5665 (progn
5666 (setq rtn t)
5667 (setq a (assoc (match-string 3) org-emphasis-alist))
5668 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5669 'face
5670 (nth 1 a))
5671 (and (nth 4 a)
5672 (org-remove-flyspell-overlays-in
5673 (match-beginning 0) (match-end 0)))
5674 (add-text-properties (match-beginning 2) (match-end 2)
5675 '(font-lock-multiline t org-emphasis t))
5676 (when org-hide-emphasis-markers
5677 (add-text-properties (match-end 4) (match-beginning 5)
5678 '(invisible org-link))
5679 (add-text-properties (match-beginning 3) (match-end 3)
5680 '(invisible org-link)))))
5681 (backward-char 1))
5682 rtn))
5684 (defun org-emphasize (&optional char)
5685 "Insert or change an emphasis, i.e. a font like bold or italic.
5686 If there is an active region, change that region to a new emphasis.
5687 If there is no region, just insert the marker characters and position
5688 the cursor between them.
5689 CHAR should be either the marker character, or the first character of the
5690 HTML tag associated with that emphasis. If CHAR is a space, the means
5691 to remove the emphasis of the selected region.
5692 If char is not given (for example in an interactive call) it
5693 will be prompted for."
5694 (interactive)
5695 (let ((eal org-emphasis-alist) e det
5696 (erc org-emphasis-regexp-components)
5697 (prompt "")
5698 (string "") beg end move tag c s)
5699 (if (org-region-active-p)
5700 (setq beg (region-beginning) end (region-end)
5701 string (buffer-substring beg end))
5702 (setq move t))
5704 (while (setq e (pop eal))
5705 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5706 c (aref tag 0))
5707 (push (cons c (string-to-char (car e))) det)
5708 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5709 (substring tag 1)))))
5710 (setq det (nreverse det))
5711 (unless char
5712 (message "%s" (concat "Emphasis marker or tag:" prompt))
5713 (setq char (read-char-exclusive)))
5714 (setq char (or (cdr (assoc char det)) char))
5715 (if (equal char ?\ )
5716 (setq s "" move nil)
5717 (unless (assoc (char-to-string char) org-emphasis-alist)
5718 (error "No such emphasis marker: \"%c\"" char))
5719 (setq s (char-to-string char)))
5720 (while (and (> (length string) 1)
5721 (equal (substring string 0 1) (substring string -1))
5722 (assoc (substring string 0 1) org-emphasis-alist))
5723 (setq string (substring string 1 -1)))
5724 (setq string (concat s string s))
5725 (if beg (delete-region beg end))
5726 (unless (or (bolp)
5727 (string-match (concat "[" (nth 0 erc) "\n]")
5728 (char-to-string (char-before (point)))))
5729 (insert " "))
5730 (unless (or (eobp)
5731 (string-match (concat "[" (nth 1 erc) "\n]")
5732 (char-to-string (char-after (point)))))
5733 (insert " ") (backward-char 1))
5734 (insert string)
5735 (and move (backward-char 1))))
5737 (defconst org-nonsticky-props
5738 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5740 (defsubst org-rear-nonsticky-at (pos)
5741 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5743 (defun org-activate-plain-links (limit)
5744 "Run through the buffer and add overlays to links."
5745 (let (f hl)
5746 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5747 (not (org-in-src-block-p)))
5748 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5749 (setq f (get-text-property (match-beginning 0) 'face))
5750 (setq hl (org-match-string-no-properties 0))
5751 (if (or (eq f 'org-tag)
5752 (and (listp f) (memq 'org-tag f)))
5754 (add-text-properties (match-beginning 0) (match-end 0)
5755 (list 'mouse-face 'highlight
5756 'face 'org-link
5757 'htmlize-link `(:uri ,hl)
5758 'keymap org-mouse-map))
5759 (org-rear-nonsticky-at (match-end 0)))
5760 t)))
5762 (defun org-activate-code (limit)
5763 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5764 (progn
5765 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5766 (remove-text-properties (match-beginning 0) (match-end 0)
5767 '(display t invisible t intangible t))
5768 t)))
5770 (defcustom org-src-fontify-natively nil
5771 "When non-nil, fontify code in code blocks."
5772 :type 'boolean
5773 :version "24.1"
5774 :group 'org-appearance
5775 :group 'org-babel)
5777 (defcustom org-allow-promoting-top-level-subtree nil
5778 "When non-nil, allow promoting a top level subtree.
5779 The leading star of the top level headline will be replaced
5780 by a #."
5781 :type 'boolean
5782 :version "24.1"
5783 :group 'org-appearance)
5785 (defun org-fontify-meta-lines-and-blocks (limit)
5786 (condition-case nil
5787 (org-fontify-meta-lines-and-blocks-1 limit)
5788 (error (message "org-mode fontification error"))))
5790 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5791 "Fontify #+ lines and blocks."
5792 (let ((case-fold-search t))
5793 (if (re-search-forward
5794 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5795 limit t)
5796 (let ((beg (match-beginning 0))
5797 (block-start (match-end 0))
5798 (block-end nil)
5799 (lang (match-string 7))
5800 (beg1 (line-beginning-position 2))
5801 (dc1 (downcase (match-string 2)))
5802 (dc3 (downcase (match-string 3)))
5803 end end1 quoting block-type ovl)
5804 (cond
5805 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5806 ;; a single line of backend-specific content
5807 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5808 (remove-text-properties (match-beginning 0) (match-end 0)
5809 '(display t invisible t intangible t))
5810 (add-text-properties (match-beginning 1) (match-end 3)
5811 '(font-lock-fontified t face org-meta-line))
5812 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5813 '(font-lock-fontified t face org-block))
5814 ; for backend-specific code
5816 ((and (match-end 4) (equal dc3 "+begin"))
5817 ;; Truly a block
5818 (setq block-type (downcase (match-string 5))
5819 quoting (member block-type org-protecting-blocks))
5820 (when (re-search-forward
5821 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5822 nil t) ;; on purpose, we look further than LIMIT
5823 (setq end (min (point-max) (match-end 0))
5824 end1 (min (point-max) (1- (match-beginning 0))))
5825 (setq block-end (match-beginning 0))
5826 (when quoting
5827 (remove-text-properties beg end
5828 '(display t invisible t intangible t)))
5829 (add-text-properties
5830 beg end
5831 '(font-lock-fontified t font-lock-multiline t))
5832 (add-text-properties beg beg1 '(face org-meta-line))
5833 (add-text-properties end1 (min (point-max) (1+ end))
5834 '(face org-meta-line)) ; for end_src
5835 (cond
5836 ((and lang (not (string= lang "")) org-src-fontify-natively)
5837 (org-src-font-lock-fontify-block lang block-start block-end)
5838 ;; remove old background overlays
5839 (mapc (lambda (ov)
5840 (if (eq (overlay-get ov 'face) 'org-block-background)
5841 (delete-overlay ov)))
5842 (overlays-at (/ (+ beg1 block-end) 2)))
5843 ;; add a background overlay
5844 (setq ovl (make-overlay beg1 block-end))
5845 (overlay-put ovl 'face 'org-block-background)
5846 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5847 (quoting
5848 (add-text-properties beg1 (min (point-max) (1+ end1))
5849 '(face org-block))) ; end of source block
5850 ((not org-fontify-quote-and-verse-blocks))
5851 ((string= block-type "quote")
5852 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5853 ((string= block-type "verse")
5854 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5855 (add-text-properties beg beg1 '(face org-block-begin-line))
5856 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5857 '(face org-block-end-line))
5859 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5860 (add-text-properties
5861 beg (match-end 3)
5862 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5863 '(font-lock-fontified t invisible t)
5864 '(font-lock-fontified t face org-document-info-keyword)))
5865 (add-text-properties
5866 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5867 (if (string-equal dc1 "+title:")
5868 '(font-lock-fontified t face org-document-title)
5869 '(font-lock-fontified t face org-document-info))))
5870 ((or (equal dc1 "+results")
5871 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5872 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5873 "+call:" "+header:" "+headers:" "+name:"))
5874 (and (match-end 4) (equal dc3 "+attr")))
5875 (add-text-properties
5876 beg (match-end 0)
5877 '(font-lock-fontified t face org-meta-line))
5879 ((member dc3 '(" " ""))
5880 (add-text-properties
5881 beg (match-end 0)
5882 '(font-lock-fontified t face font-lock-comment-face)))
5883 ((not (member (char-after beg) '(?\ ?\t)))
5884 ;; just any other in-buffer setting, but not indented
5885 (add-text-properties
5886 beg (match-end 0)
5887 '(font-lock-fontified t face org-meta-line))
5889 (t nil))))))
5891 (defun org-activate-angle-links (limit)
5892 "Run through the buffer and add overlays to links."
5893 (if (and (re-search-forward org-angle-link-re limit t)
5894 (not (org-in-src-block-p)))
5895 (progn
5896 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5897 (add-text-properties (match-beginning 0) (match-end 0)
5898 (list 'mouse-face 'highlight
5899 'keymap org-mouse-map))
5900 (org-rear-nonsticky-at (match-end 0))
5901 t)))
5903 (defun org-activate-footnote-links (limit)
5904 "Run through the buffer and add overlays to footnotes."
5905 (let ((fn (org-footnote-next-reference-or-definition limit)))
5906 (when fn
5907 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5908 (org-remove-flyspell-overlays-in beg end)
5909 (add-text-properties beg end
5910 (list 'mouse-face 'highlight
5911 'keymap org-mouse-map
5912 'help-echo
5913 (if (= (point-at-bol) beg)
5914 "Footnote definition"
5915 "Footnote reference")
5916 'font-lock-fontified t
5917 'font-lock-multiline t
5918 'face 'org-footnote))))))
5920 (defun org-activate-bracket-links (limit)
5921 "Run through the buffer and add overlays to bracketed links."
5922 (if (and (re-search-forward org-bracket-link-regexp limit t)
5923 (not (org-in-src-block-p)))
5924 (let* ((hl (org-match-string-no-properties 1))
5925 (help (concat "LINK: " hl))
5926 ;; FIXME: Above we should remove the escapes. But that
5927 ;; requires another match, protecting match data, a lot
5928 ;; of overhead for font-lock.
5929 (ip (org-maybe-intangible
5930 (list 'invisible 'org-link
5931 'keymap org-mouse-map 'mouse-face 'highlight
5932 'font-lock-multiline t 'help-echo help
5933 'htmlize-link `(:uri ,hl))))
5934 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5935 'font-lock-multiline t 'help-echo help
5936 'htmlize-link `(:uri ,hl))))
5937 ;; We need to remove the invisible property here. Table narrowing
5938 ;; may have made some of this invisible.
5939 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5940 (remove-text-properties (match-beginning 0) (match-end 0)
5941 '(invisible nil))
5942 (if (match-end 3)
5943 (progn
5944 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5945 (org-rear-nonsticky-at (match-beginning 3))
5946 (add-text-properties (match-beginning 3) (match-end 3) vp)
5947 (org-rear-nonsticky-at (match-end 3))
5948 (add-text-properties (match-end 3) (match-end 0) ip)
5949 (org-rear-nonsticky-at (match-end 0)))
5950 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5951 (org-rear-nonsticky-at (match-beginning 1))
5952 (add-text-properties (match-beginning 1) (match-end 1) vp)
5953 (org-rear-nonsticky-at (match-end 1))
5954 (add-text-properties (match-end 1) (match-end 0) ip)
5955 (org-rear-nonsticky-at (match-end 0)))
5956 t)))
5958 (defun org-activate-dates (limit)
5959 "Run through the buffer and add overlays to dates."
5960 (if (and (re-search-forward org-tsr-regexp-both limit t)
5961 (not (equal (char-before (match-beginning 0)) 91)))
5962 (progn
5963 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5964 (add-text-properties (match-beginning 0) (match-end 0)
5965 (list 'mouse-face 'highlight
5966 'keymap org-mouse-map))
5967 (org-rear-nonsticky-at (match-end 0))
5968 (when org-display-custom-times
5969 (if (match-end 3)
5970 (org-display-custom-time (match-beginning 3) (match-end 3)))
5971 (org-display-custom-time (match-beginning 1) (match-end 1)))
5972 t)))
5974 (defvar org-target-link-regexp nil
5975 "Regular expression matching radio targets in plain text.")
5976 (make-variable-buffer-local 'org-target-link-regexp)
5977 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5978 "Regular expression matching a link target.")
5979 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5980 "Regular expression matching a radio target.")
5981 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5982 "Regular expression matching any target.")
5984 (defun org-activate-target-links (limit)
5985 "Run through the buffer and add overlays to target matches."
5986 (when org-target-link-regexp
5987 (let ((case-fold-search t))
5988 (if (re-search-forward org-target-link-regexp limit t)
5989 (progn
5990 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5991 (add-text-properties (match-beginning 0) (match-end 0)
5992 (list 'mouse-face 'highlight
5993 'keymap org-mouse-map
5994 'help-echo "Radio target link"
5995 'org-linked-text t))
5996 (org-rear-nonsticky-at (match-end 0))
5997 t)))))
5999 (defun org-update-radio-target-regexp ()
6000 "Find all radio targets in this file and update the regular expression."
6001 (interactive)
6002 (when (memq 'radio org-activate-links)
6003 (setq org-target-link-regexp
6004 (org-make-target-link-regexp (org-all-targets 'radio)))
6005 (org-restart-font-lock)))
6007 (defun org-hide-wide-columns (limit)
6008 (let (s e)
6009 (setq s (text-property-any (point) (or limit (point-max))
6010 'org-cwidth t))
6011 (when s
6012 (setq e (next-single-property-change s 'org-cwidth))
6013 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6014 (goto-char e)
6015 t)))
6017 (defvar org-latex-and-related-regexp nil
6018 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6019 (defvar org-match-substring-regexp)
6020 (defvar org-match-substring-with-braces-regexp)
6022 (defun org-compute-latex-and-related-regexp ()
6023 "Compute regular expression for LaTeX, entities and sub/superscript.
6024 Result depends on variable `org-highlight-latex-and-related'."
6025 (org-set-local
6026 'org-latex-and-related-regexp
6027 (let* ((re-sub
6028 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6029 ((eq org-use-sub-superscripts '{})
6030 (list org-match-substring-with-braces-regexp))
6031 (org-use-sub-superscripts (list org-match-substring-regexp))))
6032 (re-latex
6033 (when (memq 'latex org-highlight-latex-and-related)
6034 (let ((matchers (plist-get org-format-latex-options :matchers)))
6035 (delq nil
6036 (mapcar (lambda (x)
6037 (and (member (car x) matchers) (nth 1 x)))
6038 org-latex-regexps)))))
6039 (re-entities
6040 (when (memq 'entities org-highlight-latex-and-related)
6041 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6042 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6044 (defun org-do-latex-and-related (limit)
6045 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6046 LIMIT bounds the search for syntax to highlight. Stop at first
6047 highlighted object, if any. Return t if some highlighting was
6048 done, nil otherwise."
6049 (when (org-string-nw-p org-latex-and-related-regexp)
6050 (catch 'found
6051 (while (re-search-forward org-latex-and-related-regexp limit t)
6052 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6053 'face))
6054 '(org-code org-verbatim underline))
6055 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6056 '(?_ ?^))
6058 0)))
6059 (font-lock-prepend-text-property
6060 (+ offset (match-beginning 0)) (match-end 0)
6061 'face 'org-latex-and-related)
6062 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6063 '(font-lock-multiline t)))
6064 (throw 'found t)))
6065 nil)))
6067 (defun org-restart-font-lock ()
6068 "Restart `font-lock-mode', to force refontification."
6069 (when (and (boundp 'font-lock-mode) font-lock-mode)
6070 (font-lock-mode -1)
6071 (font-lock-mode 1)))
6073 (defun org-all-targets (&optional radio)
6074 "Return a list of all targets in this file.
6075 When optional argument RADIO is non-nil, only find radio
6076 targets."
6077 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6078 (save-excursion
6079 (goto-char (point-min))
6080 (while (re-search-forward re nil t)
6081 ;; Make sure point is really within the object.
6082 (backward-char)
6083 (let ((obj (org-element-context)))
6084 (when (memq (org-element-type obj) '(radio-target target))
6085 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6086 rtn)))
6088 (defun org-make-target-link-regexp (targets)
6089 "Make regular expression matching all strings in TARGETS.
6090 The regular expression finds the targets also if there is a line break
6091 between words."
6092 (and targets
6093 (concat
6094 "\\<\\("
6095 (mapconcat
6096 (lambda (x)
6097 (setq x (regexp-quote x))
6098 (while (string-match " +" x)
6099 (setq x (replace-match "\\s-+" t t x)))
6101 targets
6102 "\\|")
6103 "\\)\\>")))
6105 (defun org-activate-tags (limit)
6106 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6107 (progn
6108 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6109 (add-text-properties (match-beginning 1) (match-end 1)
6110 (list 'mouse-face 'highlight
6111 'keymap org-mouse-map))
6112 (org-rear-nonsticky-at (match-end 1))
6113 t)))
6115 (defun org-outline-level ()
6116 "Compute the outline level of the heading at point.
6117 If this is called at a normal headline, the level is the number of stars.
6118 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6119 (save-excursion
6120 (if (not (condition-case nil
6121 (org-back-to-heading t)
6122 (error nil)))
6124 (looking-at org-outline-regexp)
6125 (1- (- (match-end 0) (match-beginning 0))))))
6127 (defvar org-font-lock-keywords nil)
6129 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6130 "Regular expression matching a property line.")
6132 (defvar org-font-lock-hook nil
6133 "Functions to be called for special font lock stuff.")
6135 (defvar org-font-lock-set-keywords-hook nil
6136 "Functions that can manipulate `org-font-lock-extra-keywords'.
6137 This is called after `org-font-lock-extra-keywords' is defined, but before
6138 it is installed to be used by font lock. This can be useful if something
6139 needs to be inserted at a specific position in the font-lock sequence.")
6141 (defun org-font-lock-hook (limit)
6142 "Run `org-font-lock-hook' within LIMIT."
6143 (run-hook-with-args 'org-font-lock-hook limit))
6145 (defun org-set-font-lock-defaults ()
6146 "Set font lock defaults for the current buffer."
6147 (let* ((em org-fontify-emphasized-text)
6148 (lk org-activate-links)
6149 (org-font-lock-extra-keywords
6150 (list
6151 ;; Call the hook
6152 '(org-font-lock-hook)
6153 ;; Headlines
6154 `(,(if org-fontify-whole-heading-line
6155 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6156 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6157 (1 (org-get-level-face 1))
6158 (2 (org-get-level-face 2))
6159 (3 (org-get-level-face 3)))
6160 ;; Table lines
6161 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6162 (1 'org-table t))
6163 ;; Table internals
6164 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6165 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6166 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6167 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6168 ;; Drawers
6169 (list org-drawer-regexp '(0 'org-special-keyword t))
6170 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6171 ;; Properties
6172 (list org-property-re
6173 '(1 'org-special-keyword t)
6174 '(3 'org-property-value t))
6175 ;; Links
6176 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6177 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6178 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6179 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6180 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6181 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6182 (if (memq 'footnote lk) '(org-activate-footnote-links))
6183 ;; Targets.
6184 (list org-any-target-regexp '(0 'org-target t))
6185 ;; Diary sexps.
6186 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6187 ;; Macro
6188 '("{{{.+}}}" (0 'org-macro t))
6189 '(org-hide-wide-columns (0 nil append))
6190 ;; TODO keyword
6191 (list (format org-heading-keyword-regexp-format
6192 org-todo-regexp)
6193 '(2 (org-get-todo-face 2) t))
6194 ;; DONE
6195 (if org-fontify-done-headline
6196 (list (format org-heading-keyword-regexp-format
6197 (concat
6198 "\\(?:"
6199 (mapconcat 'regexp-quote org-done-keywords "\\|")
6200 "\\)"))
6201 '(2 'org-headline-done t))
6202 nil)
6203 ;; Priorities
6204 '(org-font-lock-add-priority-faces)
6205 ;; Tags
6206 '(org-font-lock-add-tag-faces)
6207 ;; Tags groups
6208 (if (and org-group-tags org-tag-groups-alist)
6209 (list (concat org-outline-regexp-bol ".+\\(:"
6210 (regexp-opt (mapcar 'car org-tag-groups-alist))
6211 ":\\).*$")
6212 '(1 'org-tag-group prepend)))
6213 ;; Special keywords
6214 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6215 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6216 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6217 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6218 ;; Emphasis
6219 (if em
6220 (if (featurep 'xemacs)
6221 '(org-do-emphasis-faces (0 nil append))
6222 '(org-do-emphasis-faces)))
6223 ;; Checkboxes
6224 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6225 1 'org-checkbox prepend)
6226 (if (cdr (assq 'checkbox org-list-automatic-rules))
6227 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6228 (0 (org-get-checkbox-statistics-face) t)))
6229 ;; Description list items
6230 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6231 1 'org-list-dt prepend)
6232 ;; ARCHIVEd headings
6233 (list (concat
6234 org-outline-regexp-bol
6235 "\\(.*:" org-archive-tag ":.*\\)")
6236 '(1 'org-archived prepend))
6237 ;; Specials
6238 '(org-do-latex-and-related)
6239 '(org-fontify-entities)
6240 '(org-raise-scripts)
6241 ;; Code
6242 '(org-activate-code (1 'org-code t))
6243 ;; COMMENT
6244 (list (format org-heading-keyword-regexp-format
6245 (concat "\\("
6246 org-comment-string "\\|" org-quote-string
6247 "\\)"))
6248 '(2 'org-special-keyword t))
6249 ;; Blocks and meta lines
6250 '(org-fontify-meta-lines-and-blocks)
6252 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6253 (run-hooks 'org-font-lock-set-keywords-hook)
6254 ;; Now set the full font-lock-keywords
6255 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6256 (org-set-local 'font-lock-defaults
6257 '(org-font-lock-keywords t nil nil backward-paragraph))
6258 (kill-local-variable 'font-lock-keywords) nil))
6260 (defun org-toggle-pretty-entities ()
6261 "Toggle the composition display of entities as UTF8 characters."
6262 (interactive)
6263 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6264 (org-restart-font-lock)
6265 (if org-pretty-entities
6266 (message "Entities are now displayed as UTF8 characters")
6267 (save-restriction
6268 (widen)
6269 (org-decompose-region (point-min) (point-max))
6270 (message "Entities are now displayed as plain text"))))
6272 (defvar org-custom-properties-overlays nil
6273 "List of overlays used for custom properties.")
6274 (make-variable-buffer-local 'org-custom-properties-overlays)
6276 (defun org-toggle-custom-properties-visibility ()
6277 "Display or hide properties in `org-custom-properties'."
6278 (interactive)
6279 (if org-custom-properties-overlays
6280 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6281 (setq org-custom-properties-overlays nil))
6282 (unless (not org-custom-properties)
6283 (save-excursion
6284 (save-restriction
6285 (widen)
6286 (goto-char (point-min))
6287 (while (re-search-forward org-property-re nil t)
6288 (mapc (lambda(p)
6289 (when (equal p (substring (match-string 1) 1 -1))
6290 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6291 (overlay-put o 'invisible t)
6292 (overlay-put o 'org-custom-property t)
6293 (push o org-custom-properties-overlays))))
6294 org-custom-properties)))))))
6296 (defun org-fontify-entities (limit)
6297 "Find an entity to fontify."
6298 (let (ee)
6299 (when org-pretty-entities
6300 (catch 'match
6301 (while (re-search-forward
6302 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6303 limit t)
6304 (if (and (not (org-in-indented-comment-line))
6305 (setq ee (org-entity-get (match-string 1)))
6306 (= (length (nth 6 ee)) 1))
6307 (let*
6308 ((end (if (equal (match-string 2) "{}")
6309 (match-end 2)
6310 (match-end 1))))
6311 (add-text-properties
6312 (match-beginning 0) end
6313 (list 'font-lock-fontified t))
6314 (compose-region (match-beginning 0) end
6315 (nth 6 ee) nil)
6316 (backward-char 1)
6317 (throw 'match t))))
6318 nil))))
6320 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6321 "Fontify string S like in Org-mode."
6322 (with-temp-buffer
6323 (insert s)
6324 (let ((org-odd-levels-only odd-levels))
6325 (org-mode)
6326 (font-lock-fontify-buffer)
6327 (buffer-string))))
6329 (defvar org-m nil)
6330 (defvar org-l nil)
6331 (defvar org-f nil)
6332 (defun org-get-level-face (n)
6333 "Get the right face for match N in font-lock matching of headlines."
6334 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6335 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6336 (if org-cycle-level-faces
6337 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6338 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6339 (cond
6340 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6341 ((eq n 2) org-f)
6342 (t (if org-level-color-stars-only nil org-f))))
6345 (defun org-get-todo-face (kwd)
6346 "Get the right face for a TODO keyword KWD.
6347 If KWD is a number, get the corresponding match group."
6348 (if (numberp kwd) (setq kwd (match-string kwd)))
6349 (or (org-face-from-face-or-color
6350 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6351 (and (member kwd org-done-keywords) 'org-done)
6352 'org-todo))
6354 (defun org-face-from-face-or-color (context inherit face-or-color)
6355 "Create a face list that inherits INHERIT, but sets the foreground color.
6356 When FACE-OR-COLOR is not a string, just return it."
6357 (if (stringp face-or-color)
6358 (list :inherit inherit
6359 (cdr (assoc context org-faces-easy-properties))
6360 face-or-color)
6361 face-or-color))
6363 (defun org-font-lock-add-tag-faces (limit)
6364 "Add the special tag faces."
6365 (when (and org-tag-faces org-tags-special-faces-re)
6366 (while (re-search-forward org-tags-special-faces-re limit t)
6367 (add-text-properties (match-beginning 1) (match-end 1)
6368 (list 'face (org-get-tag-face 1)
6369 'font-lock-fontified t))
6370 (backward-char 1))))
6372 (defun org-font-lock-add-priority-faces (limit)
6373 "Add the special priority faces."
6374 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6375 (when (save-match-data (org-at-heading-p))
6376 (add-text-properties
6377 (match-beginning 0) (match-end 0)
6378 (list 'face (or (org-face-from-face-or-color
6379 'priority 'org-priority
6380 (cdr (assoc (char-after (match-beginning 1))
6381 org-priority-faces)))
6382 'org-priority)
6383 'font-lock-fontified t)))))
6385 (defun org-get-tag-face (kwd)
6386 "Get the right face for a TODO keyword KWD.
6387 If KWD is a number, get the corresponding match group."
6388 (if (numberp kwd) (setq kwd (match-string kwd)))
6389 (or (org-face-from-face-or-color
6390 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6391 'org-tag))
6393 (defun org-unfontify-region (beg end &optional maybe_loudly)
6394 "Remove fontification and activation overlays from links."
6395 (font-lock-default-unfontify-region beg end)
6396 (let* ((buffer-undo-list t)
6397 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6398 (inhibit-modification-hooks t)
6399 deactivate-mark buffer-file-name buffer-file-truename)
6400 (org-decompose-region beg end)
6401 (remove-text-properties beg end
6402 '(mouse-face t keymap t org-linked-text t
6403 invisible t intangible t
6404 org-no-flyspell t org-emphasis t))
6405 (org-remove-font-lock-display-properties beg end)))
6407 (defconst org-script-display '(((raise -0.3) (height 0.7))
6408 ((raise 0.3) (height 0.7))
6409 ((raise -0.5))
6410 ((raise 0.5)))
6411 "Display properties for showing superscripts and subscripts.")
6413 (defun org-remove-font-lock-display-properties (beg end)
6414 "Remove specific display properties that have been added by font lock.
6415 The will remove the raise properties that are used to show superscripts
6416 and subscripts."
6417 (let (next prop)
6418 (while (< beg end)
6419 (setq next (next-single-property-change beg 'display nil end)
6420 prop (get-text-property beg 'display))
6421 (if (member prop org-script-display)
6422 (put-text-property beg next 'display nil))
6423 (setq beg next))))
6425 (defun org-raise-scripts (limit)
6426 "Add raise properties to sub/superscripts."
6427 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6428 (if (re-search-forward
6429 (if (eq org-use-sub-superscripts t)
6430 org-match-substring-regexp
6431 org-match-substring-with-braces-regexp)
6432 limit t)
6433 (let* ((pos (point)) table-p comment-p
6434 (mpos (match-beginning 3))
6435 (emph-p (get-text-property mpos 'org-emphasis))
6436 (link-p (get-text-property mpos 'mouse-face))
6437 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6438 (goto-char (point-at-bol))
6439 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6440 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6441 (goto-char pos)
6442 ;; Handle a_b^c
6443 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6444 (if (or comment-p emph-p link-p keyw-p)
6446 (put-text-property (match-beginning 3) (match-end 0)
6447 'display
6448 (if (equal (char-after (match-beginning 2)) ?^)
6449 (nth (if table-p 3 1) org-script-display)
6450 (nth (if table-p 2 0) org-script-display)))
6451 (add-text-properties (match-beginning 2) (match-end 2)
6452 (list 'invisible t
6453 'org-dwidth t 'org-dwidth-n 1))
6454 (if (and (eq (char-after (match-beginning 3)) ?{)
6455 (eq (char-before (match-end 3)) ?}))
6456 (progn
6457 (add-text-properties
6458 (match-beginning 3) (1+ (match-beginning 3))
6459 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6460 (add-text-properties
6461 (1- (match-end 3)) (match-end 3)
6462 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6463 t)))))
6465 ;;;; Visibility cycling, including org-goto and indirect buffer
6467 ;;; Cycling
6469 (defvar org-cycle-global-status nil)
6470 (make-variable-buffer-local 'org-cycle-global-status)
6471 (put 'org-cycle-global-status 'org-state t)
6472 (defvar org-cycle-subtree-status nil)
6473 (make-variable-buffer-local 'org-cycle-subtree-status)
6474 (put 'org-cycle-subtree-status 'org-state t)
6476 (defvar org-inlinetask-min-level)
6478 ;;;###autoload
6479 (defun org-cycle (&optional arg)
6480 "TAB-action and visibility cycling for Org-mode.
6482 This is the command invoked in Org-mode by the TAB key. Its main purpose
6483 is outline visibility cycling, but it also invokes other actions
6484 in special contexts.
6486 - When this function is called with a prefix argument, rotate the entire
6487 buffer through 3 states (global cycling)
6488 1. OVERVIEW: Show only top-level headlines.
6489 2. CONTENTS: Show all headlines of all levels, but no body text.
6490 3. SHOW ALL: Show everything.
6491 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6492 determined by the variable `org-startup-folded', and by any VISIBILITY
6493 properties in the buffer.
6494 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6495 including any drawers.
6497 - When inside a table, re-align the table and move to the next field.
6499 - When point is at the beginning of a headline, rotate the subtree started
6500 by this line through 3 different states (local cycling)
6501 1. FOLDED: Only the main headline is shown.
6502 2. CHILDREN: The main headline and the direct children are shown.
6503 From this state, you can move to one of the children
6504 and zoom in further.
6505 3. SUBTREE: Show the entire subtree, including body text.
6506 If there is no subtree, switch directly from CHILDREN to FOLDED.
6508 - When point is at the beginning of an empty headline and the variable
6509 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6510 of the headline by demoting and promoting it to likely levels. This
6511 speeds up creation document structure by pressing TAB once or several
6512 times right after creating a new headline.
6514 - When there is a numeric prefix, go up to a heading with level ARG, do
6515 a `show-subtree' and return to the previous cursor position. If ARG
6516 is negative, go up that many levels.
6518 - When point is not at the beginning of a headline, execute the global
6519 binding for TAB, which is re-indenting the line. See the option
6520 `org-cycle-emulate-tab' for details.
6522 - Special case: if point is at the beginning of the buffer and there is
6523 no headline in line 1, this function will act as if called with prefix arg
6524 (C-u TAB, same as S-TAB) also when called without prefix arg.
6525 But only if also the variable `org-cycle-global-at-bob' is t."
6526 (interactive "P")
6527 (org-load-modules-maybe)
6528 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6529 (and org-cycle-level-after-item/entry-creation
6530 (or (org-cycle-level)
6531 (org-cycle-item-indentation))))
6532 (let* (message-log-max ; Don't populate the *Messages* buffer
6533 (limit-level
6534 (or org-cycle-max-level
6535 (and (boundp 'org-inlinetask-min-level)
6536 org-inlinetask-min-level
6537 (1- org-inlinetask-min-level))))
6538 (nstars (and limit-level
6539 (if org-odd-levels-only
6540 (and limit-level (1- (* limit-level 2)))
6541 limit-level)))
6542 (org-outline-regexp
6543 (if (not (derived-mode-p 'org-mode))
6544 outline-regexp
6545 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6546 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6547 (not (looking-at org-outline-regexp))))
6548 (org-cycle-hook
6549 (if bob-special
6550 (delq 'org-optimize-window-after-visibility-change
6551 (copy-sequence org-cycle-hook))
6552 org-cycle-hook))
6553 (pos (point)))
6555 (if (or bob-special (equal arg '(4)))
6556 ;; special case: use global cycling
6557 (setq arg t))
6559 (cond
6561 ((equal arg '(16))
6562 (setq last-command 'dummy)
6563 (org-set-startup-visibility)
6564 (message "Startup visibility, plus VISIBILITY properties"))
6566 ((equal arg '(64))
6567 (show-all)
6568 (message "Entire buffer visible, including drawers"))
6570 ;; Table: enter it or move to the next field.
6571 ((org-at-table-p 'any)
6572 (if (org-at-table.el-p)
6573 (message "Use C-c ' to edit table.el tables")
6574 (if arg (org-table-edit-field t)
6575 (org-table-justify-field-maybe)
6576 (call-interactively 'org-table-next-field))))
6578 ((run-hook-with-args-until-success
6579 'org-tab-after-check-for-table-hook))
6581 ;; Global cycling: delegate to `org-cycle-internal-global'.
6582 ((eq arg t) (org-cycle-internal-global))
6584 ;; Drawers: delegate to `org-flag-drawer'.
6585 ((and org-drawers org-drawer-regexp
6586 (save-excursion
6587 (beginning-of-line 1)
6588 (looking-at org-drawer-regexp)))
6589 (org-flag-drawer ; toggle block visibility
6590 (not (get-char-property (match-end 0) 'invisible))))
6592 ;; Show-subtree, ARG levels up from here.
6593 ((integerp arg)
6594 (save-excursion
6595 (org-back-to-heading)
6596 (outline-up-heading (if (< arg 0) (- arg)
6597 (- (funcall outline-level) arg)))
6598 (org-show-subtree)))
6600 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6601 ((and (featurep 'org-inlinetask)
6602 (org-inlinetask-at-task-p)
6603 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6604 (org-inlinetask-toggle-visibility))
6606 ((org-try-cdlatex-tab))
6608 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6609 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6610 (save-excursion (beginning-of-line 1)
6611 (looking-at org-outline-regexp)))
6612 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6613 (org-cycle-internal-local))
6615 ;; From there: TAB emulation and template completion.
6616 (buffer-read-only (org-back-to-heading))
6618 ((run-hook-with-args-until-success
6619 'org-tab-after-check-for-cycling-hook))
6621 ((org-try-structure-completion))
6623 ((run-hook-with-args-until-success
6624 'org-tab-before-tab-emulation-hook))
6626 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6627 (or (not (bolp))
6628 (not (looking-at org-outline-regexp))))
6629 (call-interactively (global-key-binding "\t")))
6631 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6632 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6633 (or (and (eq org-cycle-emulate-tab 'white)
6634 (= (match-end 0) (point-at-eol)))
6635 (and (eq org-cycle-emulate-tab 'whitestart)
6636 (>= (match-end 0) pos))))
6638 (eq org-cycle-emulate-tab t))
6639 (call-interactively (global-key-binding "\t")))
6641 (t (save-excursion
6642 (org-back-to-heading)
6643 (org-cycle)))))))
6645 (defun org-cycle-internal-global ()
6646 "Do the global cycling action."
6647 ;; Hack to avoid display of messages for .org attachments in Gnus
6648 (let (message-log-max ; Don't populate the *Messages* buffer
6649 (ga (string-match "\\*fontification" (buffer-name))))
6650 (cond
6651 ((and (eq last-command this-command)
6652 (eq org-cycle-global-status 'overview))
6653 ;; We just created the overview - now do table of contents
6654 ;; This can be slow in very large buffers, so indicate action
6655 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6656 (unless ga (message "CONTENTS..."))
6657 (org-content)
6658 (unless ga (message "CONTENTS...done"))
6659 (setq org-cycle-global-status 'contents)
6660 (run-hook-with-args 'org-cycle-hook 'contents))
6662 ((and (eq last-command this-command)
6663 (eq org-cycle-global-status 'contents))
6664 ;; We just showed the table of contents - now show everything
6665 (run-hook-with-args 'org-pre-cycle-hook 'all)
6666 (show-all)
6667 (unless ga (message "SHOW ALL"))
6668 (setq org-cycle-global-status 'all)
6669 (run-hook-with-args 'org-cycle-hook 'all))
6672 ;; Default action: go to overview
6673 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6674 (org-overview)
6675 (unless ga (message "OVERVIEW"))
6676 (setq org-cycle-global-status 'overview)
6677 (run-hook-with-args 'org-cycle-hook 'overview)))))
6679 (defun org-cycle-internal-local ()
6680 "Do the local cycling action."
6681 (let (message-log-max ; Don't populate the *Messages* buffer
6682 (goal-column 0) eoh eol eos has-children children-skipped struct)
6683 ;; First, determine end of headline (EOH), end of subtree or item
6684 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6685 (save-excursion
6686 (if (org-at-item-p)
6687 (progn
6688 (beginning-of-line)
6689 (setq struct (org-list-struct))
6690 (setq eoh (point-at-eol))
6691 (setq eos (org-list-get-item-end-before-blank (point) struct))
6692 (setq has-children (org-list-has-child-p (point) struct)))
6693 (org-back-to-heading)
6694 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6695 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6696 (setq has-children
6697 (or (save-excursion
6698 (let ((level (funcall outline-level)))
6699 (outline-next-heading)
6700 (and (org-at-heading-p t)
6701 (> (funcall outline-level) level))))
6702 (save-excursion
6703 (org-list-search-forward (org-item-beginning-re) eos t)))))
6704 ;; Determine end invisible part of buffer (EOL)
6705 (beginning-of-line 2)
6706 ;; XEmacs doesn't have `next-single-char-property-change'
6707 (if (featurep 'xemacs)
6708 (while (and (not (eobp)) ;; this is like `next-line'
6709 (get-char-property (1- (point)) 'invisible))
6710 (beginning-of-line 2))
6711 (while (and (not (eobp)) ;; this is like `next-line'
6712 (get-char-property (1- (point)) 'invisible))
6713 (goto-char (next-single-char-property-change (point) 'invisible))
6714 (and (eolp) (beginning-of-line 2))))
6715 (setq eol (point)))
6716 ;; Find out what to do next and set `this-command'
6717 (cond
6718 ((= eos eoh)
6719 ;; Nothing is hidden behind this heading
6720 (unless (org-before-first-heading-p)
6721 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6722 (message "EMPTY ENTRY")
6723 (setq org-cycle-subtree-status nil)
6724 (save-excursion
6725 (goto-char eos)
6726 (outline-next-heading)
6727 (if (outline-invisible-p) (org-flag-heading nil))))
6728 ((and (or (>= eol eos)
6729 (not (string-match "\\S-" (buffer-substring eol eos))))
6730 (or has-children
6731 (not (setq children-skipped
6732 org-cycle-skip-children-state-if-no-children))))
6733 ;; Entire subtree is hidden in one line: children view
6734 (unless (org-before-first-heading-p)
6735 (run-hook-with-args 'org-pre-cycle-hook 'children))
6736 (if (org-at-item-p)
6737 (org-list-set-item-visibility (point-at-bol) struct 'children)
6738 (org-show-entry)
6739 (org-with-limited-levels (show-children))
6740 ;; FIXME: This slows down the func way too much.
6741 ;; How keep drawers hidden in subtree anyway?
6742 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6743 ;; (org-cycle-hide-drawers 'subtree))
6745 ;; Fold every list in subtree to top-level items.
6746 (when (eq org-cycle-include-plain-lists 'integrate)
6747 (save-excursion
6748 (org-back-to-heading)
6749 (while (org-list-search-forward (org-item-beginning-re) eos t)
6750 (beginning-of-line 1)
6751 (let* ((struct (org-list-struct))
6752 (prevs (org-list-prevs-alist struct))
6753 (end (org-list-get-bottom-point struct)))
6754 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6755 (org-list-get-all-items (point) struct prevs))
6756 (goto-char (if (< end eos) end eos)))))))
6757 (message "CHILDREN")
6758 (save-excursion
6759 (goto-char eos)
6760 (outline-next-heading)
6761 (if (outline-invisible-p) (org-flag-heading nil)))
6762 (setq org-cycle-subtree-status 'children)
6763 (unless (org-before-first-heading-p)
6764 (run-hook-with-args 'org-cycle-hook 'children)))
6765 ((or children-skipped
6766 (and (eq last-command this-command)
6767 (eq org-cycle-subtree-status 'children)))
6768 ;; We just showed the children, or no children are there,
6769 ;; now show everything.
6770 (unless (org-before-first-heading-p)
6771 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6772 (outline-flag-region eoh eos nil)
6773 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6774 (setq org-cycle-subtree-status 'subtree)
6775 (unless (org-before-first-heading-p)
6776 (run-hook-with-args 'org-cycle-hook 'subtree)))
6778 ;; Default action: hide the subtree.
6779 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6780 (outline-flag-region eoh eos t)
6781 (message "FOLDED")
6782 (setq org-cycle-subtree-status 'folded)
6783 (unless (org-before-first-heading-p)
6784 (run-hook-with-args 'org-cycle-hook 'folded))))))
6786 ;;;###autoload
6787 (defun org-global-cycle (&optional arg)
6788 "Cycle the global visibility. For details see `org-cycle'.
6789 With \\[universal-argument] prefix arg, switch to startup visibility.
6790 With a numeric prefix, show all headlines up to that level."
6791 (interactive "P")
6792 (let ((org-cycle-include-plain-lists
6793 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6794 (cond
6795 ((integerp arg)
6796 (show-all)
6797 (hide-sublevels arg)
6798 (setq org-cycle-global-status 'contents))
6799 ((equal arg '(4))
6800 (org-set-startup-visibility)
6801 (message "Startup visibility, plus VISIBILITY properties."))
6803 (org-cycle '(4))))))
6805 (defun org-set-startup-visibility ()
6806 "Set the visibility required by startup options and properties."
6807 (cond
6808 ((eq org-startup-folded t)
6809 (org-cycle '(4)))
6810 ((eq org-startup-folded 'content)
6811 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6812 (org-cycle '(4)) (org-cycle '(4)))))
6813 (unless (eq org-startup-folded 'showeverything)
6814 (if org-hide-block-startup (org-hide-block-all))
6815 (org-set-visibility-according-to-property 'no-cleanup)
6816 (org-cycle-hide-archived-subtrees 'all)
6817 (org-cycle-hide-drawers 'all)
6818 (org-cycle-show-empty-lines t)))
6820 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6821 "Switch subtree visibilities according to :VISIBILITY: property."
6822 (interactive)
6823 (let (org-show-entry-below state)
6824 (save-excursion
6825 (goto-char (point-min))
6826 (while (re-search-forward
6827 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6828 nil t)
6829 (setq state (match-string 1))
6830 (save-excursion
6831 (org-back-to-heading t)
6832 (hide-subtree)
6833 (org-reveal)
6834 (cond
6835 ((equal state '("fold" "folded"))
6836 (hide-subtree))
6837 ((equal state "children")
6838 (org-show-hidden-entry)
6839 (show-children))
6840 ((equal state "content")
6841 (save-excursion
6842 (save-restriction
6843 (org-narrow-to-subtree)
6844 (org-content))))
6845 ((member state '("all" "showall"))
6846 (show-subtree)))))
6847 (unless no-cleanup
6848 (org-cycle-hide-archived-subtrees 'all)
6849 (org-cycle-hide-drawers 'all)
6850 (org-cycle-show-empty-lines 'all)))))
6852 ;; This function uses outline-regexp instead of the more fundamental
6853 ;; org-outline-regexp so that org-cycle-global works outside of Org
6854 ;; buffers, where outline-regexp is needed.
6855 (defun org-overview ()
6856 "Switch to overview mode, showing only top-level headlines.
6857 Really, this shows all headlines with level equal or greater than the level
6858 of the first headline in the buffer. This is important, because if the
6859 first headline is not level one, then (hide-sublevels 1) gives confusing
6860 results."
6861 (interactive)
6862 (let ((l (org-current-line))
6863 (level (save-excursion
6864 (goto-char (point-min))
6865 (if (re-search-forward (concat "^" outline-regexp) nil t)
6866 (progn
6867 (goto-char (match-beginning 0))
6868 (funcall outline-level))))))
6869 (and level (hide-sublevels level))
6870 (recenter '(4))
6871 (org-goto-line l)))
6873 (defun org-content (&optional arg)
6874 "Show all headlines in the buffer, like a table of contents.
6875 With numerical argument N, show content up to level N."
6876 (interactive "P")
6877 (save-excursion
6878 ;; Visit all headings and show their offspring
6879 (and (integerp arg) (org-overview))
6880 (goto-char (point-max))
6881 (catch 'exit
6882 (while (and (progn (condition-case nil
6883 (outline-previous-visible-heading 1)
6884 (error (goto-char (point-min))))
6886 (looking-at org-outline-regexp))
6887 (if (integerp arg)
6888 (show-children (1- arg))
6889 (show-branches))
6890 (if (bobp) (throw 'exit nil))))))
6893 (defun org-optimize-window-after-visibility-change (state)
6894 "Adjust the window after a change in outline visibility.
6895 This function is the default value of the hook `org-cycle-hook'."
6896 (when (get-buffer-window (current-buffer))
6897 (cond
6898 ((eq state 'content) nil)
6899 ((eq state 'all) nil)
6900 ((eq state 'folded) nil)
6901 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6902 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6904 (defun org-remove-empty-overlays-at (pos)
6905 "Remove outline overlays that do not contain non-white stuff."
6906 (mapc
6907 (lambda (o)
6908 (and (eq 'outline (overlay-get o 'invisible))
6909 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6910 (overlay-end o))))
6911 (delete-overlay o)))
6912 (overlays-at pos)))
6914 (defun org-clean-visibility-after-subtree-move ()
6915 "Fix visibility issues after moving a subtree."
6916 ;; First, find a reasonable region to look at:
6917 ;; Start two siblings above, end three below
6918 (let* ((beg (save-excursion
6919 (and (org-get-last-sibling)
6920 (org-get-last-sibling))
6921 (point)))
6922 (end (save-excursion
6923 (and (org-get-next-sibling)
6924 (org-get-next-sibling)
6925 (org-get-next-sibling))
6926 (if (org-at-heading-p)
6927 (point-at-eol)
6928 (point))))
6929 (level (looking-at "\\*+"))
6930 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6931 (save-excursion
6932 (save-restriction
6933 (narrow-to-region beg end)
6934 (when re
6935 ;; Properly fold already folded siblings
6936 (goto-char (point-min))
6937 (while (re-search-forward re nil t)
6938 (if (and (not (outline-invisible-p))
6939 (save-excursion
6940 (goto-char (point-at-eol)) (outline-invisible-p)))
6941 (hide-entry))))
6942 (org-cycle-show-empty-lines 'overview)
6943 (org-cycle-hide-drawers 'overview)))))
6945 (defun org-cycle-show-empty-lines (state)
6946 "Show empty lines above all visible headlines.
6947 The region to be covered depends on STATE when called through
6948 `org-cycle-hook'. Lisp program can use t for STATE to get the
6949 entire buffer covered. Note that an empty line is only shown if there
6950 are at least `org-cycle-separator-lines' empty lines before the headline."
6951 (when (not (= org-cycle-separator-lines 0))
6952 (save-excursion
6953 (let* ((n (abs org-cycle-separator-lines))
6954 (re (cond
6955 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6956 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6957 (t (let ((ns (number-to-string (- n 2))))
6958 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6959 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6960 beg end b e)
6961 (cond
6962 ((memq state '(overview contents t))
6963 (setq beg (point-min) end (point-max)))
6964 ((memq state '(children folded))
6965 (setq beg (point) end (progn (org-end-of-subtree t t)
6966 (beginning-of-line 2)
6967 (point)))))
6968 (when beg
6969 (goto-char beg)
6970 (while (re-search-forward re end t)
6971 (unless (get-char-property (match-end 1) 'invisible)
6972 (setq e (match-end 1))
6973 (if (< org-cycle-separator-lines 0)
6974 (setq b (save-excursion
6975 (goto-char (match-beginning 0))
6976 (org-back-over-empty-lines)
6977 (if (save-excursion
6978 (goto-char (max (point-min) (1- (point))))
6979 (org-at-heading-p))
6980 (1- (point))
6981 (point))))
6982 (setq b (match-beginning 1)))
6983 (outline-flag-region b e nil)))))))
6984 ;; Never hide empty lines at the end of the file.
6985 (save-excursion
6986 (goto-char (point-max))
6987 (outline-previous-heading)
6988 (outline-end-of-heading)
6989 (if (and (looking-at "[ \t\n]+")
6990 (= (match-end 0) (point-max)))
6991 (outline-flag-region (point) (match-end 0) nil))))
6993 (defun org-show-empty-lines-in-parent ()
6994 "Move to the parent and re-show empty lines before visible headlines."
6995 (save-excursion
6996 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6997 (org-cycle-show-empty-lines context))))
6999 (defun org-files-list ()
7000 "Return `org-agenda-files' list, plus all open org-mode files.
7001 This is useful for operations that need to scan all of a user's
7002 open and agenda-wise Org files."
7003 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7004 (dolist (buf (buffer-list))
7005 (with-current-buffer buf
7006 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7007 (let ((file (expand-file-name (buffer-file-name))))
7008 (unless (member file files)
7009 (push file files))))))
7010 files))
7012 (defsubst org-entry-beginning-position ()
7013 "Return the beginning position of the current entry."
7014 (save-excursion (outline-back-to-heading t) (point)))
7016 (defsubst org-entry-end-position ()
7017 "Return the end position of the current entry."
7018 (save-excursion (outline-next-heading) (point)))
7020 (defun org-cycle-hide-drawers (state)
7021 "Re-hide all drawers after a visibility state change."
7022 (when (and (derived-mode-p 'org-mode)
7023 (not (memq state '(overview folded contents))))
7024 (save-excursion
7025 (let* ((globalp (memq state '(contents all)))
7026 (beg (if globalp (point-min) (point)))
7027 (end (if globalp (point-max)
7028 (if (eq state 'children)
7029 (save-excursion (outline-next-heading) (point))
7030 (org-end-of-subtree t)))))
7031 (goto-char beg)
7032 (while (re-search-forward org-drawer-regexp end t)
7033 (org-flag-drawer t))))))
7035 (defun org-cycle-hide-inline-tasks (state)
7036 "Re-hide inline task when switching to 'contents visibility state."
7037 (when (and (eq state 'contents)
7038 (boundp 'org-inlinetask-min-level)
7039 org-inlinetask-min-level)
7040 (hide-sublevels (1- org-inlinetask-min-level))))
7042 (defun org-flag-drawer (flag)
7043 "When FLAG is non-nil, hide the drawer we are within.
7044 Otherwise make it visible."
7045 (save-excursion
7046 (beginning-of-line 1)
7047 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7048 (let ((b (match-end 0)))
7049 (if (re-search-forward
7050 "^[ \t]*:END:"
7051 (save-excursion (outline-next-heading) (point)) t)
7052 (outline-flag-region b (point-at-eol) flag)
7053 (error ":END: line missing at position %s" b))))))
7055 (defun org-subtree-end-visible-p ()
7056 "Is the end of the current subtree visible?"
7057 (pos-visible-in-window-p
7058 (save-excursion (org-end-of-subtree t) (point))))
7060 (defun org-first-headline-recenter (&optional N)
7061 "Move cursor to the first headline and recenter the headline.
7062 Optional argument N means put the headline into the Nth line of the window."
7063 (goto-char (point-min))
7064 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7065 (beginning-of-line)
7066 (recenter (prefix-numeric-value N))))
7068 ;;; Saving and restoring visibility
7070 (defun org-outline-overlay-data (&optional use-markers)
7071 "Return a list of the locations of all outline overlays.
7072 These are overlays with the `invisible' property value `outline'.
7073 The return value is a list of cons cells, with start and stop
7074 positions for each overlay.
7075 If USE-MARKERS is set, return the positions as markers."
7076 (let (beg end)
7077 (save-excursion
7078 (save-restriction
7079 (widen)
7080 (delq nil
7081 (mapcar (lambda (o)
7082 (when (eq (overlay-get o 'invisible) 'outline)
7083 (setq beg (overlay-start o)
7084 end (overlay-end o))
7085 (and beg end (> end beg)
7086 (if use-markers
7087 (cons (move-marker (make-marker) beg)
7088 (move-marker (make-marker) end))
7089 (cons beg end)))))
7090 (overlays-in (point-min) (point-max))))))))
7092 (defun org-set-outline-overlay-data (data)
7093 "Create visibility overlays for all positions in DATA.
7094 DATA should have been made by `org-outline-overlay-data'."
7095 (let (o)
7096 (save-excursion
7097 (save-restriction
7098 (widen)
7099 (show-all)
7100 (mapc (lambda (c)
7101 (outline-flag-region (car c) (cdr c) t))
7102 data)))))
7104 ;;; Folding of blocks
7106 (defvar org-hide-block-overlays nil
7107 "Overlays hiding blocks.")
7108 (make-variable-buffer-local 'org-hide-block-overlays)
7110 (defun org-block-map (function &optional start end)
7111 "Call FUNCTION at the head of all source blocks in the current buffer.
7112 Optional arguments START and END can be used to limit the range."
7113 (let ((start (or start (point-min)))
7114 (end (or end (point-max))))
7115 (save-excursion
7116 (goto-char start)
7117 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7118 (save-excursion
7119 (save-match-data
7120 (goto-char (match-beginning 0))
7121 (funcall function)))))))
7123 (defun org-hide-block-toggle-all ()
7124 "Toggle the visibility of all blocks in the current buffer."
7125 (org-block-map #'org-hide-block-toggle))
7127 (defun org-hide-block-all ()
7128 "Fold all blocks in the current buffer."
7129 (interactive)
7130 (org-show-block-all)
7131 (org-block-map #'org-hide-block-toggle-maybe))
7133 (defun org-show-block-all ()
7134 "Unfold all blocks in the current buffer."
7135 (interactive)
7136 (mapc 'delete-overlay org-hide-block-overlays)
7137 (setq org-hide-block-overlays nil))
7139 (defun org-hide-block-toggle-maybe ()
7140 "Toggle visibility of block at point."
7141 (interactive)
7142 (let ((case-fold-search t))
7143 (if (save-excursion
7144 (beginning-of-line 1)
7145 (looking-at org-block-regexp))
7146 (progn (org-hide-block-toggle)
7147 t) ;; to signal that we took action
7148 nil))) ;; to signal that we did not
7150 (defun org-hide-block-toggle (&optional force)
7151 "Toggle the visibility of the current block."
7152 (interactive)
7153 (save-excursion
7154 (beginning-of-line)
7155 (if (re-search-forward org-block-regexp nil t)
7156 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7157 (end (match-end 0)) ;; end of entire body
7159 (if (memq t (mapcar (lambda (overlay)
7160 (eq (overlay-get overlay 'invisible)
7161 'org-hide-block))
7162 (overlays-at start)))
7163 (if (or (not force) (eq force 'off))
7164 (mapc (lambda (ov)
7165 (when (member ov org-hide-block-overlays)
7166 (setq org-hide-block-overlays
7167 (delq ov org-hide-block-overlays)))
7168 (when (eq (overlay-get ov 'invisible)
7169 'org-hide-block)
7170 (delete-overlay ov)))
7171 (overlays-at start)))
7172 (setq ov (make-overlay start end))
7173 (overlay-put ov 'invisible 'org-hide-block)
7174 ;; make the block accessible to isearch
7175 (overlay-put
7176 ov 'isearch-open-invisible
7177 (lambda (ov)
7178 (when (member ov org-hide-block-overlays)
7179 (setq org-hide-block-overlays
7180 (delq ov org-hide-block-overlays)))
7181 (when (eq (overlay-get ov 'invisible)
7182 'org-hide-block)
7183 (delete-overlay ov))))
7184 (push ov org-hide-block-overlays)))
7185 (error "Not looking at a source block"))))
7187 ;; org-tab-after-check-for-cycling-hook
7188 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7189 ;; Remove overlays when changing major mode
7190 (add-hook 'org-mode-hook
7191 (lambda () (org-add-hook 'change-major-mode-hook
7192 'org-show-block-all 'append 'local)))
7194 ;;; Org-goto
7196 (defvar org-goto-window-configuration nil)
7197 (defvar org-goto-marker nil)
7198 (defvar org-goto-map)
7199 (defun org-goto-map ()
7200 "Set the keymap `org-goto'."
7201 (setq org-goto-map
7202 (let ((map (make-sparse-keymap)))
7203 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7204 mouse-drag-region universal-argument org-occur))
7205 cmd)
7206 (while (setq cmd (pop cmds))
7207 (substitute-key-definition cmd cmd map global-map)))
7208 (suppress-keymap map)
7209 (org-defkey map "\C-m" 'org-goto-ret)
7210 (org-defkey map [(return)] 'org-goto-ret)
7211 (org-defkey map [(left)] 'org-goto-left)
7212 (org-defkey map [(right)] 'org-goto-right)
7213 (org-defkey map [(control ?g)] 'org-goto-quit)
7214 (org-defkey map "\C-i" 'org-cycle)
7215 (org-defkey map [(tab)] 'org-cycle)
7216 (org-defkey map [(down)] 'outline-next-visible-heading)
7217 (org-defkey map [(up)] 'outline-previous-visible-heading)
7218 (if org-goto-auto-isearch
7219 (if (fboundp 'define-key-after)
7220 (define-key-after map [t] 'org-goto-local-auto-isearch)
7221 nil)
7222 (org-defkey map "q" 'org-goto-quit)
7223 (org-defkey map "n" 'outline-next-visible-heading)
7224 (org-defkey map "p" 'outline-previous-visible-heading)
7225 (org-defkey map "f" 'outline-forward-same-level)
7226 (org-defkey map "b" 'outline-backward-same-level)
7227 (org-defkey map "u" 'outline-up-heading))
7228 (org-defkey map "/" 'org-occur)
7229 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7230 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7231 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7232 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7233 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7234 map)))
7236 (defconst org-goto-help
7237 "Browse buffer copy, to find location or copy text.%s
7238 RET=jump to location C-g=quit and return to previous location
7239 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7241 (defvar org-goto-start-pos) ; dynamically scoped parameter
7243 (defun org-goto (&optional alternative-interface)
7244 "Look up a different location in the current file, keeping current visibility.
7246 When you want look-up or go to a different location in a
7247 document, the fastest way is often to fold the entire buffer and
7248 then dive into the tree. This method has the disadvantage, that
7249 the previous location will be folded, which may not be what you
7250 want.
7252 This command works around this by showing a copy of the current
7253 buffer in an indirect buffer, in overview mode. You can dive
7254 into the tree in that copy, use org-occur and incremental search
7255 to find a location. When pressing RET or `Q', the command
7256 returns to the original buffer in which the visibility is still
7257 unchanged. After RET it will also jump to the location selected
7258 in the indirect buffer and expose the headline hierarchy above.
7260 With a prefix argument, use the alternative interface: e.g. if
7261 `org-goto-interface' is 'outline use 'outline-path-completion."
7262 (interactive "P")
7263 (org-goto-map)
7264 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7265 (org-refile-use-outline-path t)
7266 (org-refile-target-verify-function nil)
7267 (interface
7268 (if (not alternative-interface)
7269 org-goto-interface
7270 (if (eq org-goto-interface 'outline)
7271 'outline-path-completion
7272 'outline)))
7273 (org-goto-start-pos (point))
7274 (selected-point
7275 (if (eq interface 'outline)
7276 (car (org-get-location (current-buffer) org-goto-help))
7277 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7278 (org-refile-check-position pa)
7279 (nth 3 pa)))))
7280 (if selected-point
7281 (progn
7282 (org-mark-ring-push org-goto-start-pos)
7283 (goto-char selected-point)
7284 (if (or (outline-invisible-p) (org-invisible-p2))
7285 (org-show-context 'org-goto)))
7286 (message "Quit"))))
7288 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7289 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7290 (defvar org-goto-local-auto-isearch-map) ; defined below
7292 (defun org-get-location (buf help)
7293 "Let the user select a location in the Org-mode buffer BUF.
7294 This function uses a recursive edit. It returns the selected position
7295 or nil."
7296 (org-no-popups
7297 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7298 (isearch-hide-immediately nil)
7299 (isearch-search-fun-function
7300 (lambda () 'org-goto-local-search-headings))
7301 (org-goto-selected-point org-goto-exit-command))
7302 (save-excursion
7303 (save-window-excursion
7304 (delete-other-windows)
7305 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7306 (org-pop-to-buffer-same-window
7307 (condition-case nil
7308 (make-indirect-buffer (current-buffer) "*org-goto*")
7309 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7310 (with-output-to-temp-buffer "*Org Help*"
7311 (princ (format help (if org-goto-auto-isearch
7312 " Just type for auto-isearch."
7313 " n/p/f/b/u to navigate, q to quit."))))
7314 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7315 (setq buffer-read-only nil)
7316 (let ((org-startup-truncated t)
7317 (org-startup-folded nil)
7318 (org-startup-align-all-tables nil))
7319 (org-mode)
7320 (org-overview))
7321 (setq buffer-read-only t)
7322 (if (and (boundp 'org-goto-start-pos)
7323 (integer-or-marker-p org-goto-start-pos))
7324 (let ((org-show-hierarchy-above t)
7325 (org-show-siblings t)
7326 (org-show-following-heading t))
7327 (goto-char org-goto-start-pos)
7328 (and (outline-invisible-p) (org-show-context)))
7329 (goto-char (point-min)))
7330 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7331 (message "Select location and press RET")
7332 (use-local-map org-goto-map)
7333 (recursive-edit)))
7334 (kill-buffer "*org-goto*")
7335 (cons org-goto-selected-point org-goto-exit-command))))
7337 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7338 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7339 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7340 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7342 (defun org-goto-local-search-headings (string bound noerror)
7343 "Search and make sure that any matches are in headlines."
7344 (catch 'return
7345 (while (if isearch-forward
7346 (search-forward string bound noerror)
7347 (search-backward string bound noerror))
7348 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7349 (and (member :headline context)
7350 (not (member :tags context))))
7351 (throw 'return (point))))))
7353 (defun org-goto-local-auto-isearch ()
7354 "Start isearch."
7355 (interactive)
7356 (goto-char (point-min))
7357 (let ((keys (this-command-keys)))
7358 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7359 (isearch-mode t)
7360 (isearch-process-search-char (string-to-char keys)))))
7362 (defun org-goto-ret (&optional arg)
7363 "Finish `org-goto' by going to the new location."
7364 (interactive "P")
7365 (setq org-goto-selected-point (point)
7366 org-goto-exit-command 'return)
7367 (throw 'exit nil))
7369 (defun org-goto-left ()
7370 "Finish `org-goto' by going to the new location."
7371 (interactive)
7372 (if (org-at-heading-p)
7373 (progn
7374 (beginning-of-line 1)
7375 (setq org-goto-selected-point (point)
7376 org-goto-exit-command 'left)
7377 (throw 'exit nil))
7378 (error "Not on a heading")))
7380 (defun org-goto-right ()
7381 "Finish `org-goto' by going to the new location."
7382 (interactive)
7383 (if (org-at-heading-p)
7384 (progn
7385 (setq org-goto-selected-point (point)
7386 org-goto-exit-command 'right)
7387 (throw 'exit nil))
7388 (error "Not on a heading")))
7390 (defun org-goto-quit ()
7391 "Finish `org-goto' without cursor motion."
7392 (interactive)
7393 (setq org-goto-selected-point nil)
7394 (setq org-goto-exit-command 'quit)
7395 (throw 'exit nil))
7397 ;;; Indirect buffer display of subtrees
7399 (defvar org-indirect-dedicated-frame nil
7400 "This is the frame being used for indirect tree display.")
7401 (defvar org-last-indirect-buffer nil)
7403 (defun org-tree-to-indirect-buffer (&optional arg)
7404 "Create indirect buffer and narrow it to current subtree.
7405 With a numerical prefix ARG, go up to this level and then take that tree.
7406 If ARG is negative, go up that many levels.
7408 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7409 indirect buffer previously made with this command, to avoid proliferation of
7410 indirect buffers. However, when you call the command with a \
7411 \\[universal-argument] prefix, or
7412 when `org-indirect-buffer-display' is `new-frame', the last buffer
7413 is kept so that you can work with several indirect buffers at the same time.
7414 If `org-indirect-buffer-display' is `dedicated-frame', the \
7415 \\[universal-argument] prefix also
7416 requests that a new frame be made for the new buffer, so that the dedicated
7417 frame is not changed."
7418 (interactive "P")
7419 (let ((cbuf (current-buffer))
7420 (cwin (selected-window))
7421 (pos (point))
7422 beg end level heading ibuf)
7423 (save-excursion
7424 (org-back-to-heading t)
7425 (when (numberp arg)
7426 (setq level (org-outline-level))
7427 (if (< arg 0) (setq arg (+ level arg)))
7428 (while (> (setq level (org-outline-level)) arg)
7429 (org-up-heading-safe)))
7430 (setq beg (point)
7431 heading (org-get-heading))
7432 (org-end-of-subtree t t)
7433 (if (org-at-heading-p) (backward-char 1))
7434 (setq end (point)))
7435 (if (and (buffer-live-p org-last-indirect-buffer)
7436 (not (eq org-indirect-buffer-display 'new-frame))
7437 (not arg))
7438 (kill-buffer org-last-indirect-buffer))
7439 (setq ibuf (org-get-indirect-buffer cbuf)
7440 org-last-indirect-buffer ibuf)
7441 (cond
7442 ((or (eq org-indirect-buffer-display 'new-frame)
7443 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7444 (select-frame (make-frame))
7445 (delete-other-windows)
7446 (org-pop-to-buffer-same-window ibuf)
7447 (org-set-frame-title heading))
7448 ((eq org-indirect-buffer-display 'dedicated-frame)
7449 (raise-frame
7450 (select-frame (or (and org-indirect-dedicated-frame
7451 (frame-live-p org-indirect-dedicated-frame)
7452 org-indirect-dedicated-frame)
7453 (setq org-indirect-dedicated-frame (make-frame)))))
7454 (delete-other-windows)
7455 (org-pop-to-buffer-same-window ibuf)
7456 (org-set-frame-title (concat "Indirect: " heading)))
7457 ((eq org-indirect-buffer-display 'current-window)
7458 (org-pop-to-buffer-same-window ibuf))
7459 ((eq org-indirect-buffer-display 'other-window)
7460 (pop-to-buffer ibuf))
7461 (t (error "Invalid value")))
7462 (if (featurep 'xemacs)
7463 (save-excursion (org-mode) (turn-on-font-lock)))
7464 (narrow-to-region beg end)
7465 (show-all)
7466 (goto-char pos)
7467 (run-hook-with-args 'org-cycle-hook 'all)
7468 (and (window-live-p cwin) (select-window cwin))))
7470 (defun org-get-indirect-buffer (&optional buffer)
7471 (setq buffer (or buffer (current-buffer)))
7472 (let ((n 1) (base (buffer-name buffer)) bname)
7473 (while (buffer-live-p
7474 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7475 (setq n (1+ n)))
7476 (condition-case nil
7477 (make-indirect-buffer buffer bname 'clone)
7478 (error (make-indirect-buffer buffer bname)))))
7480 (defun org-set-frame-title (title)
7481 "Set the title of the current frame to the string TITLE."
7482 ;; FIXME: how to name a single frame in XEmacs???
7483 (unless (featurep 'xemacs)
7484 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7486 ;;;; Structure editing
7488 ;;; Inserting headlines
7490 (defun org-previous-line-empty-p (&optional next)
7491 "Is the previous line a blank line?
7492 When NEXT is non-nil, check the next line instead."
7493 (save-excursion
7494 (and (not (bobp))
7495 (or (beginning-of-line (if next 2 0)) t)
7496 (save-match-data
7497 (looking-at "[ \t]*$")))))
7499 (defun org-insert-heading (&optional arg invisible-ok)
7500 "Insert a new heading or item with same depth at point.
7501 If point is in a plain list and ARG is nil, create a new list item.
7502 With one universal prefix argument, insert a heading even in lists.
7503 With two universal prefix arguments, insert the heading at the end
7504 of the parent subtree.
7506 If point is at the beginning of a headline, insert a sibling before
7507 the current headline. If point is not at the beginning, split the line
7508 and create a new headline with the text in the current line after point
7509 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7511 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7512 This is important for non-interactive uses of the command."
7513 (interactive "P")
7514 (cond
7515 ((or (= (buffer-size) 0)
7516 (and (not (save-excursion
7517 (and (ignore-errors (org-back-to-heading invisible-ok))
7518 (org-at-heading-p))))
7519 (or arg (not (org-in-item-p)))))
7520 (insert
7521 (if (org-previous-line-empty-p) "" "\n")
7522 (if (org-in-src-block-p) ",* " "* "))
7523 (run-hooks 'org-insert-heading-hook))
7524 ((or arg (not (org-insert-item
7525 (save-excursion
7526 (beginning-of-line)
7527 (looking-at org-list-full-item-re)
7528 (match-string 3)))))
7529 (let (begn endn)
7530 (when (org-buffer-narrowed-p)
7531 (setq begn (point-min) endn (point-max))
7532 (widen))
7533 (let* ((empty-line-p nil)
7534 (eops (equal arg '(16))) ; insert at end of parent subtree
7535 (org-insert-heading-respect-content
7536 (or (not (null arg)) org-insert-heading-respect-content))
7537 (level nil)
7538 (on-heading (org-at-heading-p))
7539 (head (save-excursion
7540 (condition-case nil
7541 (progn
7542 (org-back-to-heading invisible-ok)
7543 (when (and (not on-heading)
7544 (featurep 'org-inlinetask)
7545 (integerp org-inlinetask-min-level)
7546 (>= (length (match-string 0))
7547 org-inlinetask-min-level))
7548 ;; Find a heading level before the inline task
7549 (while (and (setq level (org-up-heading-safe))
7550 (>= level org-inlinetask-min-level)))
7551 (if (org-at-heading-p)
7552 (org-back-to-heading invisible-ok)
7553 (error "This should not happen")))
7554 (unless (and (save-excursion
7555 (save-match-data
7556 (org-backward-heading-same-level 1 invisible-ok))
7557 (= (point) (match-beginning 0)))
7558 (not (org-previous-line-empty-p t)))
7559 (setq empty-line-p (org-previous-line-empty-p)))
7560 (match-string 0))
7561 (error "* "))))
7562 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7563 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7564 pos hide-previous previous-pos)
7565 (if ;; At the beginning of a heading, open a new line for insertiong
7566 (and (bolp) (org-at-heading-p)
7567 (not eops)
7568 (or (bobp)
7569 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7570 (open-line (if blank 2 1))
7571 (save-excursion
7572 (setq previous-pos (point-at-bol))
7573 (end-of-line)
7574 (setq hide-previous (outline-invisible-p)))
7575 (and org-insert-heading-respect-content
7576 (save-excursion
7577 (while (outline-invisible-p)
7578 (org-show-subtree)
7579 (org-up-heading-safe))))
7580 (let ((split
7581 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7582 (save-excursion
7583 (let ((p (point)))
7584 (goto-char (point-at-bol))
7585 (and (looking-at org-complex-heading-regexp)
7586 (match-beginning 4)
7587 (> p (match-beginning 4)))))))
7588 tags pos)
7589 (cond
7590 ;; Insert a new line, possibly at end of parent subtree
7591 (org-insert-heading-respect-content
7592 (if (not eops)
7593 (progn
7594 (org-end-of-subtree nil t)
7595 (and (looking-at "^\\*") (backward-char 1))
7596 (while (and (not (bobp))
7597 ;; Don't delete spaces in empty headlines
7598 (not (looking-back org-outline-regexp))
7599 (member (char-before) '(?\ ?\t ?\n)))
7600 (backward-delete-char 1)))
7601 (let ((p (point)))
7602 (org-up-heading-safe)
7603 (if (= p (point))
7604 (goto-char (point-max))
7605 (org-end-of-subtree nil t))))
7606 (when (featurep 'org-inlinetask)
7607 (while (and (not (eobp))
7608 (looking-at "\\(\\*+\\)[ \t]+")
7609 (>= (length (match-string 1))
7610 org-inlinetask-min-level))
7611 (org-end-of-subtree nil t)))
7612 (or (bolp) (newline))
7613 (or (org-previous-line-empty-p)
7614 (and blank (newline)))
7615 (if (or empty-line-p eops) (open-line 1)))
7616 ;; Insert a headling containing text after point
7617 ((org-at-heading-p)
7618 (when hide-previous
7619 (show-children)
7620 (org-show-entry))
7621 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7622 (setq tags (and (match-end 2) (match-string 2)))
7623 (and (match-end 1)
7624 (delete-region (match-beginning 1) (match-end 1)))
7625 (setq pos (point-at-bol))
7626 (or split (end-of-line 1))
7627 (delete-horizontal-space)
7628 (if (string-match "\\`\\*+\\'"
7629 (buffer-substring (point-at-bol) (point)))
7630 (insert " "))
7631 (newline (if blank 2 1))
7632 (when tags
7633 (save-excursion
7634 (goto-char pos)
7635 (end-of-line 1)
7636 (insert " " tags)
7637 (org-set-tags nil 'align))))
7639 (or split (end-of-line 1))
7640 (newline (if blank 2 1))))))
7641 (insert head) (just-one-space)
7642 (setq pos (point))
7643 (end-of-line 1)
7644 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7645 (when (and org-insert-heading-respect-content hide-previous)
7646 (save-excursion
7647 (goto-char previous-pos)
7648 (hide-subtree)))
7649 (when (and begn endn)
7650 (narrow-to-region (min (point) begn) (max (point) endn)))
7651 (run-hooks 'org-insert-heading-hook))))))
7653 (defun org-get-heading (&optional no-tags no-todo)
7654 "Return the heading of the current entry, without the stars.
7655 When NO-TAGS is non-nil, don't include tags.
7656 When NO-TODO is non-nil, don't include TODO keywords."
7657 (save-excursion
7658 (org-back-to-heading t)
7659 (cond
7660 ((and no-tags no-todo)
7661 (looking-at org-complex-heading-regexp)
7662 (match-string 4))
7663 (no-tags
7664 (looking-at (concat org-outline-regexp
7665 "\\(.*?\\)"
7666 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7667 (match-string 1))
7668 (no-todo
7669 (looking-at org-todo-line-regexp)
7670 (match-string 3))
7671 (t (looking-at org-heading-regexp)
7672 (match-string 2)))))
7674 (defvar orgstruct-mode) ; defined below
7676 (defun org-heading-components ()
7677 "Return the components of the current heading.
7678 This is a list with the following elements:
7679 - the level as an integer
7680 - the reduced level, different if `org-odd-levels-only' is set.
7681 - the TODO keyword, or nil
7682 - the priority character, like ?A, or nil if no priority is given
7683 - the headline text itself, or the tags string if no headline text
7684 - the tags string, or nil."
7685 (save-excursion
7686 (org-back-to-heading t)
7687 (if (let (case-fold-search)
7688 (looking-at
7689 (if orgstruct-mode
7690 org-heading-regexp
7691 org-complex-heading-regexp)))
7692 (if orgstruct-mode
7693 (list (length (match-string 1))
7694 (org-reduced-level (length (match-string 1)))
7697 (match-string 2)
7698 nil)
7699 (list (length (match-string 1))
7700 (org-reduced-level (length (match-string 1)))
7701 (org-match-string-no-properties 2)
7702 (and (match-end 3) (aref (match-string 3) 2))
7703 (org-match-string-no-properties 4)
7704 (org-match-string-no-properties 5))))))
7706 (defun org-get-entry ()
7707 "Get the entry text, after heading, entire subtree."
7708 (save-excursion
7709 (org-back-to-heading t)
7710 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7712 (defun org-insert-heading-after-current ()
7713 "Insert a new heading with same level as current, after current subtree."
7714 (interactive)
7715 (org-back-to-heading)
7716 (org-insert-heading)
7717 (org-move-subtree-down)
7718 (end-of-line 1))
7720 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7721 "Insert heading with `org-insert-heading-respect-content' set to t."
7722 (interactive "P")
7723 (let ((org-insert-heading-respect-content t))
7724 (org-insert-heading arg invisible-ok)))
7726 (defun org-insert-todo-heading-respect-content (&optional force-state)
7727 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7728 (interactive "P")
7729 (let ((org-insert-heading-respect-content t))
7730 (org-insert-todo-heading force-state t)))
7732 (defun org-insert-todo-heading (arg &optional force-heading)
7733 "Insert a new heading with the same level and TODO state as current heading.
7734 If the heading has no TODO state, or if the state is DONE, use the first
7735 state (TODO by default). Also one prefix arg, force first state. With two
7736 prefix args, force inserting at the end of the parent subtree."
7737 (interactive "P")
7738 (when (or force-heading (not (org-insert-item 'checkbox)))
7739 (org-insert-heading (or (and (equal arg '(16)) '(16))
7740 force-heading))
7741 (save-excursion
7742 (org-back-to-heading)
7743 (outline-previous-heading)
7744 (looking-at org-todo-line-regexp))
7745 (let*
7746 ((new-mark-x
7747 (if (or arg
7748 (not (match-beginning 2))
7749 (member (match-string 2) org-done-keywords))
7750 (car org-todo-keywords-1)
7751 (match-string 2)))
7752 (new-mark
7754 (run-hook-with-args-until-success
7755 'org-todo-get-default-hook new-mark-x nil)
7756 new-mark-x)))
7757 (beginning-of-line 1)
7758 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7759 (if org-treat-insert-todo-heading-as-state-change
7760 (org-todo new-mark)
7761 (insert new-mark " "))))
7762 (when org-provide-todo-statistics
7763 (org-update-parent-todo-statistics))))
7765 (defun org-insert-subheading (arg)
7766 "Insert a new subheading and demote it.
7767 Works for outline headings and for plain lists alike."
7768 (interactive "P")
7769 (org-insert-heading arg)
7770 (cond
7771 ((org-at-heading-p) (org-do-demote))
7772 ((org-at-item-p) (org-indent-item))))
7774 (defun org-insert-todo-subheading (arg)
7775 "Insert a new subheading with TODO keyword or checkbox and demote it.
7776 Works for outline headings and for plain lists alike."
7777 (interactive "P")
7778 (org-insert-todo-heading arg)
7779 (cond
7780 ((org-at-heading-p) (org-do-demote))
7781 ((org-at-item-p) (org-indent-item))))
7783 ;;; Promotion and Demotion
7785 (defvar org-after-demote-entry-hook nil
7786 "Hook run after an entry has been demoted.
7787 The cursor will be at the beginning of the entry.
7788 When a subtree is being demoted, the hook will be called for each node.")
7790 (defvar org-after-promote-entry-hook nil
7791 "Hook run after an entry has been promoted.
7792 The cursor will be at the beginning of the entry.
7793 When a subtree is being promoted, the hook will be called for each node.")
7795 (defun org-promote-subtree ()
7796 "Promote the entire subtree.
7797 See also `org-promote'."
7798 (interactive)
7799 (save-excursion
7800 (org-with-limited-levels (org-map-tree 'org-promote)))
7801 (org-fix-position-after-promote))
7803 (defun org-demote-subtree ()
7804 "Demote the entire subtree. See `org-demote'.
7805 See also `org-promote'."
7806 (interactive)
7807 (save-excursion
7808 (org-with-limited-levels (org-map-tree 'org-demote)))
7809 (org-fix-position-after-promote))
7812 (defun org-do-promote ()
7813 "Promote the current heading higher up the tree.
7814 If the region is active in `transient-mark-mode', promote all headings
7815 in the region."
7816 (interactive)
7817 (save-excursion
7818 (if (org-region-active-p)
7819 (org-map-region 'org-promote (region-beginning) (region-end))
7820 (org-promote)))
7821 (org-fix-position-after-promote))
7823 (defun org-do-demote ()
7824 "Demote the current heading lower down the tree.
7825 If the region is active in `transient-mark-mode', demote all headings
7826 in the region."
7827 (interactive)
7828 (save-excursion
7829 (if (org-region-active-p)
7830 (org-map-region 'org-demote (region-beginning) (region-end))
7831 (org-demote)))
7832 (org-fix-position-after-promote))
7834 (defun org-fix-position-after-promote ()
7835 "Make sure that after pro/demotion cursor position is right."
7836 (let ((pos (point)))
7837 (when (save-excursion
7838 (beginning-of-line 1)
7839 (looking-at org-todo-line-regexp)
7840 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7841 (cond ((eobp) (insert " "))
7842 ((eolp) (insert " "))
7843 ((equal (char-after) ?\ ) (forward-char 1))))))
7845 (defun org-current-level ()
7846 "Return the level of the current entry, or nil if before the first headline.
7847 The level is the number of stars at the beginning of the headline."
7848 (save-excursion
7849 (org-with-limited-levels
7850 (if (ignore-errors (org-back-to-heading t))
7851 (funcall outline-level)))))
7853 (defun org-get-previous-line-level ()
7854 "Return the outline depth of the last headline before the current line.
7855 Returns 0 for the first headline in the buffer, and nil if before the
7856 first headline."
7857 (let ((current-level (org-current-level))
7858 (prev-level (when (> (line-number-at-pos) 1)
7859 (save-excursion
7860 (beginning-of-line 0)
7861 (org-current-level)))))
7862 (cond ((null current-level) nil) ; Before first headline
7863 ((null prev-level) 0) ; At first headline
7864 (prev-level))))
7866 (defun org-reduced-level (l)
7867 "Compute the effective level of a heading.
7868 This takes into account the setting of `org-odd-levels-only'."
7869 (cond
7870 ((zerop l) 0)
7871 (org-odd-levels-only (1+ (floor (/ l 2))))
7872 (t l)))
7874 (defun org-level-increment ()
7875 "Return the number of stars that will be added or removed at a
7876 time to headlines when structure editing, based on the value of
7877 `org-odd-levels-only'."
7878 (if org-odd-levels-only 2 1))
7880 (defun org-get-valid-level (level &optional change)
7881 "Rectify a level change under the influence of `org-odd-levels-only'
7882 LEVEL is a current level, CHANGE is by how much the level should be
7883 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7884 even level numbers will become the next higher odd number."
7885 (if org-odd-levels-only
7886 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7887 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7888 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7889 (max 1 (+ level (or change 0)))))
7891 (if (boundp 'define-obsolete-function-alias)
7892 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7893 (define-obsolete-function-alias 'org-get-legal-level
7894 'org-get-valid-level)
7895 (define-obsolete-function-alias 'org-get-legal-level
7896 'org-get-valid-level "23.1")))
7898 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7899 ;; ̀org-with-limited-levels'
7900 (defun org-promote ()
7901 "Promote the current heading higher up the tree.
7902 If the region is active in `transient-mark-mode', promote all headings
7903 in the region."
7904 (org-back-to-heading t)
7905 (let* ((level (save-match-data (funcall outline-level)))
7906 (after-change-functions (remove 'flyspell-after-change-function
7907 after-change-functions))
7908 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7909 (diff (abs (- level (length up-head) -1))))
7910 (cond ((and (= level 1) org-called-with-limited-levels
7911 org-allow-promoting-top-level-subtree)
7912 (replace-match "# " nil t))
7913 ((= level 1)
7914 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7915 (t (replace-match up-head nil t)))
7916 ;; Fixup tag positioning
7917 (unless (= level 1)
7918 (and org-auto-align-tags (org-set-tags nil t))
7919 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7920 (run-hooks 'org-after-promote-entry-hook)))
7922 (defun org-demote ()
7923 "Demote the current heading lower down the tree.
7924 If the region is active in `transient-mark-mode', demote all headings
7925 in the region."
7926 (org-back-to-heading t)
7927 (let* ((level (save-match-data (funcall outline-level)))
7928 (after-change-functions (remove 'flyspell-after-change-function
7929 after-change-functions))
7930 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7931 (diff (abs (- level (length down-head) -1))))
7932 (replace-match down-head nil t)
7933 ;; Fixup tag positioning
7934 (and org-auto-align-tags (org-set-tags nil t))
7935 (if org-adapt-indentation (org-fixup-indentation diff))
7936 (run-hooks 'org-after-demote-entry-hook)))
7938 (defun org-cycle-level ()
7939 "Cycle the level of an empty headline through possible states.
7940 This goes first to child, then to parent, level, then up the hierarchy.
7941 After top level, it switches back to sibling level."
7942 (interactive)
7943 (let ((org-adapt-indentation nil))
7944 (when (org-point-at-end-of-empty-headline)
7945 (setq this-command 'org-cycle-level) ; Only needed for caching
7946 (let ((cur-level (org-current-level))
7947 (prev-level (org-get-previous-line-level)))
7948 (cond
7949 ;; If first headline in file, promote to top-level.
7950 ((= prev-level 0)
7951 (loop repeat (/ (- cur-level 1) (org-level-increment))
7952 do (org-do-promote)))
7953 ;; If same level as prev, demote one.
7954 ((= prev-level cur-level)
7955 (org-do-demote))
7956 ;; If parent is top-level, promote to top level if not already.
7957 ((= prev-level 1)
7958 (loop repeat (/ (- cur-level 1) (org-level-increment))
7959 do (org-do-promote)))
7960 ;; If top-level, return to prev-level.
7961 ((= cur-level 1)
7962 (loop repeat (/ (- prev-level 1) (org-level-increment))
7963 do (org-do-demote)))
7964 ;; If less than prev-level, promote one.
7965 ((< cur-level prev-level)
7966 (org-do-promote))
7967 ;; If deeper than prev-level, promote until higher than
7968 ;; prev-level.
7969 ((> cur-level prev-level)
7970 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7971 do (org-do-promote))))
7972 t))))
7974 (defun org-map-tree (fun)
7975 "Call FUN for every heading underneath the current one."
7976 (org-back-to-heading)
7977 (let ((level (funcall outline-level)))
7978 (save-excursion
7979 (funcall fun)
7980 (while (and (progn
7981 (outline-next-heading)
7982 (> (funcall outline-level) level))
7983 (not (eobp)))
7984 (funcall fun)))))
7986 (defun org-map-region (fun beg end)
7987 "Call FUN for every heading between BEG and END."
7988 (let ((org-ignore-region t))
7989 (save-excursion
7990 (setq end (copy-marker end))
7991 (goto-char beg)
7992 (if (and (re-search-forward org-outline-regexp-bol nil t)
7993 (< (point) end))
7994 (funcall fun))
7995 (while (and (progn
7996 (outline-next-heading)
7997 (< (point) end))
7998 (not (eobp)))
7999 (funcall fun)))))
8001 (defvar org-property-end-re) ; silence byte-compiler
8002 (defun org-fixup-indentation (diff)
8003 "Change the indentation in the current entry by DIFF.
8004 However, if any line in the current entry has no indentation, or if it
8005 would end up with no indentation after the change, nothing at all is done."
8006 (save-excursion
8007 (let ((end (save-excursion (outline-next-heading)
8008 (point-marker)))
8009 (prohibit (if (> diff 0)
8010 "^\\S-"
8011 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8012 col)
8013 (unless (save-excursion (end-of-line 1)
8014 (re-search-forward prohibit end t))
8015 (while (and (< (point) end)
8016 (re-search-forward "^[ \t]+" end t))
8017 (goto-char (match-end 0))
8018 (setq col (current-column))
8019 (if (< diff 0) (replace-match ""))
8020 (org-indent-to-column (+ diff col))))
8021 (move-marker end nil))))
8023 (defun org-convert-to-odd-levels ()
8024 "Convert an org-mode file with all levels allowed to one with odd levels.
8025 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8026 level 5 etc."
8027 (interactive)
8028 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8029 (let ((outline-level 'org-outline-level)
8030 (org-odd-levels-only nil) n)
8031 (save-excursion
8032 (goto-char (point-min))
8033 (while (re-search-forward "^\\*\\*+ " nil t)
8034 (setq n (- (length (match-string 0)) 2))
8035 (while (>= (setq n (1- n)) 0)
8036 (org-demote))
8037 (end-of-line 1))))))
8039 (defun org-convert-to-oddeven-levels ()
8040 "Convert an org-mode file with only odd levels to one with odd/even levels.
8041 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8042 file contains a section with an even level, conversion would
8043 destroy the structure of the file. An error is signaled in this
8044 case."
8045 (interactive)
8046 (goto-char (point-min))
8047 ;; First check if there are no even levels
8048 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8049 (org-show-context t)
8050 (error "Not all levels are odd in this file. Conversion not possible"))
8051 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8052 (let ((outline-regexp org-outline-regexp)
8053 (outline-level 'org-outline-level)
8054 (org-odd-levels-only nil) n)
8055 (save-excursion
8056 (goto-char (point-min))
8057 (while (re-search-forward "^\\*\\*+ " nil t)
8058 (setq n (/ (1- (length (match-string 0))) 2))
8059 (while (>= (setq n (1- n)) 0)
8060 (org-promote))
8061 (end-of-line 1))))))
8063 (defun org-tr-level (n)
8064 "Make N odd if required."
8065 (if org-odd-levels-only (1+ (/ n 2)) n))
8067 ;;; Vertical tree motion, cutting and pasting of subtrees
8069 (defun org-move-subtree-up (&optional arg)
8070 "Move the current subtree up past ARG headlines of the same level."
8071 (interactive "p")
8072 (org-move-subtree-down (- (prefix-numeric-value arg))))
8074 (defun org-move-subtree-down (&optional arg)
8075 "Move the current subtree down past ARG headlines of the same level."
8076 (interactive "p")
8077 (setq arg (prefix-numeric-value arg))
8078 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8079 'org-get-last-sibling))
8080 (ins-point (make-marker))
8081 (cnt (abs arg))
8082 (col (current-column))
8083 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8084 ;; Select the tree
8085 (org-back-to-heading)
8086 (setq beg0 (point))
8087 (save-excursion
8088 (setq ne-beg (org-back-over-empty-lines))
8089 (setq beg (point)))
8090 (save-match-data
8091 (save-excursion (outline-end-of-heading)
8092 (setq folded (outline-invisible-p)))
8093 (outline-end-of-subtree))
8094 (outline-next-heading)
8095 (setq ne-end (org-back-over-empty-lines))
8096 (setq end (point))
8097 (goto-char beg0)
8098 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8099 ;; include less whitespace
8100 (save-excursion
8101 (goto-char beg)
8102 (forward-line (- ne-beg ne-end))
8103 (setq beg (point))))
8104 ;; Find insertion point, with error handling
8105 (while (> cnt 0)
8106 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8107 (progn (goto-char beg0)
8108 (user-error "Cannot move past superior level or buffer limit")))
8109 (setq cnt (1- cnt)))
8110 (if (> arg 0)
8111 ;; Moving forward - still need to move over subtree
8112 (progn (org-end-of-subtree t t)
8113 (save-excursion
8114 (org-back-over-empty-lines)
8115 (or (bolp) (newline)))))
8116 (setq ne-ins (org-back-over-empty-lines))
8117 (move-marker ins-point (point))
8118 (setq txt (buffer-substring beg end))
8119 (org-save-markers-in-region beg end)
8120 (delete-region beg end)
8121 (org-remove-empty-overlays-at beg)
8122 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8123 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8124 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8125 (let ((bbb (point)))
8126 (insert-before-markers txt)
8127 (org-reinstall-markers-in-region bbb)
8128 (move-marker ins-point bbb))
8129 (or (bolp) (insert "\n"))
8130 (setq ins-end (point))
8131 (goto-char ins-point)
8132 (org-skip-whitespace)
8133 (when (and (< arg 0)
8134 (org-first-sibling-p)
8135 (> ne-ins ne-beg))
8136 ;; Move whitespace back to beginning
8137 (save-excursion
8138 (goto-char ins-end)
8139 (let ((kill-whole-line t))
8140 (kill-line (- ne-ins ne-beg)) (point)))
8141 (insert (make-string (- ne-ins ne-beg) ?\n)))
8142 (move-marker ins-point nil)
8143 (if folded
8144 (hide-subtree)
8145 (org-show-entry)
8146 (show-children)
8147 (org-cycle-hide-drawers 'children))
8148 (org-clean-visibility-after-subtree-move)
8149 ;; move back to the initial column we were at
8150 (move-to-column col)))
8152 (defvar org-subtree-clip ""
8153 "Clipboard for cut and paste of subtrees.
8154 This is actually only a copy of the kill, because we use the normal kill
8155 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8157 (defvar org-subtree-clip-folded nil
8158 "Was the last copied subtree folded?
8159 This is used to fold the tree back after pasting.")
8161 (defun org-cut-subtree (&optional n)
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 cutting it."
8165 (interactive "p")
8166 (org-copy-subtree n 'cut))
8168 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8169 "Cut the current subtree into the clipboard.
8170 With prefix arg N, cut this many sequential subtrees.
8171 This is a short-hand for marking the subtree and then copying it.
8172 If CUT is non-nil, actually cut the subtree.
8173 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8174 of some markers in the region, even if CUT is non-nil. This is
8175 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8176 (interactive "p")
8177 (let (beg end folded (beg0 (point)))
8178 (if (org-called-interactively-p 'any)
8179 (org-back-to-heading nil) ; take what looks like a subtree
8180 (org-back-to-heading t)) ; take what is really there
8181 (setq beg (point))
8182 (skip-chars-forward " \t\r\n")
8183 (save-match-data
8184 (if nosubtrees
8185 (outline-next-heading)
8186 (save-excursion (outline-end-of-heading)
8187 (setq folded (outline-invisible-p)))
8188 (condition-case nil
8189 (org-forward-heading-same-level (1- n) t)
8190 (error nil))
8191 (org-end-of-subtree t t)))
8192 (setq end (point))
8193 (goto-char beg0)
8194 (when (> end beg)
8195 (setq org-subtree-clip-folded folded)
8196 (when (or cut force-store-markers)
8197 (org-save-markers-in-region beg end))
8198 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8199 (setq org-subtree-clip (current-kill 0))
8200 (message "%s: Subtree(s) with %d characters"
8201 (if cut "Cut" "Copied")
8202 (length org-subtree-clip)))))
8204 (defun org-paste-subtree (&optional level tree for-yank)
8205 "Paste the clipboard as a subtree, with modification of headline level.
8206 The entire subtree is promoted or demoted in order to match a new headline
8207 level.
8209 If the cursor is at the beginning of a headline, the same level as
8210 that headline is used to paste the tree.
8212 If not, the new level is derived from the *visible* headings
8213 before and after the insertion point, and taken to be the inferior headline
8214 level of the two. So if the previous visible heading is level 3 and the
8215 next is level 4 (or vice versa), level 4 will be used for insertion.
8216 This makes sure that the subtree remains an independent subtree and does
8217 not swallow low level entries.
8219 You can also force a different level, either by using a numeric prefix
8220 argument, or by inserting the heading marker by hand. For example, if the
8221 cursor is after \"*****\", then the tree will be shifted to level 5.
8223 If optional TREE is given, use this text instead of the kill ring.
8225 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8226 move back over whitespace before inserting, and move point to the end of
8227 the inserted text when done."
8228 (interactive "P")
8229 (setq tree (or tree (and kill-ring (current-kill 0))))
8230 (unless (org-kill-is-subtree-p tree)
8231 (error "%s"
8232 (substitute-command-keys
8233 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8234 (org-with-limited-levels
8235 (let* ((visp (not (outline-invisible-p)))
8236 (txt tree)
8237 (^re_ "\\(\\*+\\)[ \t]*")
8238 (old-level (if (string-match org-outline-regexp-bol txt)
8239 (- (match-end 0) (match-beginning 0) 1)
8240 -1))
8241 (force-level (cond (level (prefix-numeric-value level))
8242 ((and (looking-at "[ \t]*$")
8243 (string-match
8244 "^\\*+$" (buffer-substring
8245 (point-at-bol) (point))))
8246 (- (match-end 1) (match-beginning 1)))
8247 ((and (bolp)
8248 (looking-at org-outline-regexp))
8249 (- (match-end 0) (point) 1))))
8250 (previous-level (save-excursion
8251 (condition-case nil
8252 (progn
8253 (outline-previous-visible-heading 1)
8254 (if (looking-at ^re_)
8255 (- (match-end 0) (match-beginning 0) 1)
8257 (error 1))))
8258 (next-level (save-excursion
8259 (condition-case nil
8260 (progn
8261 (or (looking-at org-outline-regexp)
8262 (outline-next-visible-heading 1))
8263 (if (looking-at ^re_)
8264 (- (match-end 0) (match-beginning 0) 1)
8266 (error 1))))
8267 (new-level (or force-level (max previous-level next-level)))
8268 (shift (if (or (= old-level -1)
8269 (= new-level -1)
8270 (= old-level new-level))
8272 (- new-level old-level)))
8273 (delta (if (> shift 0) -1 1))
8274 (func (if (> shift 0) 'org-demote 'org-promote))
8275 (org-odd-levels-only nil)
8276 beg end newend)
8277 ;; Remove the forced level indicator
8278 (if force-level
8279 (delete-region (point-at-bol) (point)))
8280 ;; Paste
8281 (beginning-of-line (if (bolp) 1 2))
8282 (setq beg (point))
8283 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8284 (insert-before-markers txt)
8285 (unless (string-match "\n\\'" txt) (insert "\n"))
8286 (setq newend (point))
8287 (org-reinstall-markers-in-region beg)
8288 (setq end (point))
8289 (goto-char beg)
8290 (skip-chars-forward " \t\n\r")
8291 (setq beg (point))
8292 (if (and (outline-invisible-p) visp)
8293 (save-excursion (outline-show-heading)))
8294 ;; Shift if necessary
8295 (unless (= shift 0)
8296 (save-restriction
8297 (narrow-to-region beg end)
8298 (while (not (= shift 0))
8299 (org-map-region func (point-min) (point-max))
8300 (setq shift (+ delta shift)))
8301 (goto-char (point-min))
8302 (setq newend (point-max))))
8303 (when (or (org-called-interactively-p 'interactive) for-yank)
8304 (message "Clipboard pasted as level %d subtree" new-level))
8305 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8306 kill-ring
8307 (eq org-subtree-clip (current-kill 0))
8308 org-subtree-clip-folded)
8309 ;; The tree was folded before it was killed/copied
8310 (hide-subtree))
8311 (and for-yank (goto-char newend)))))
8313 (defun org-kill-is-subtree-p (&optional txt)
8314 "Check if the current kill is an outline subtree, or a set of trees.
8315 Returns nil if kill does not start with a headline, or if the first
8316 headline level is not the largest headline level in the tree.
8317 So this will actually accept several entries of equal levels as well,
8318 which is OK for `org-paste-subtree'.
8319 If optional TXT is given, check this string instead of the current kill."
8320 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8321 (re (org-get-limited-outline-regexp))
8322 (^re (concat "^" re))
8323 (start-level (and kill
8324 (string-match
8325 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8326 kill)
8327 (- (match-end 2) (match-beginning 2) 1)))
8328 (start (1+ (or (match-beginning 2) -1))))
8329 (if (not start-level)
8330 (progn
8331 nil) ;; does not even start with a heading
8332 (catch 'exit
8333 (while (setq start (string-match ^re kill (1+ start)))
8334 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8335 (throw 'exit nil)))
8336 t))))
8338 (defvar org-markers-to-move nil
8339 "Markers that should be moved with a cut-and-paste operation.
8340 Those markers are stored together with their positions relative to
8341 the start of the region.")
8343 (defun org-save-markers-in-region (beg end)
8344 "Check markers in region.
8345 If these markers are between BEG and END, record their position relative
8346 to BEG, so that after moving the block of text, we can put the markers back
8347 into place.
8348 This function gets called just before an entry or tree gets cut from the
8349 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8350 called immediately, to move the markers with the entries."
8351 (setq org-markers-to-move nil)
8352 (when (featurep 'org-clock)
8353 (org-clock-save-markers-for-cut-and-paste beg end))
8354 (when (featurep 'org-agenda)
8355 (org-agenda-save-markers-for-cut-and-paste beg end)))
8357 (defun org-check-and-save-marker (marker beg end)
8358 "Check if MARKER is between BEG and END.
8359 If yes, remember the marker and the distance to BEG."
8360 (when (and (marker-buffer marker)
8361 (equal (marker-buffer marker) (current-buffer)))
8362 (if (and (>= marker beg) (< marker end))
8363 (push (cons marker (- marker beg)) org-markers-to-move))))
8365 (defun org-reinstall-markers-in-region (beg)
8366 "Move all remembered markers to their position relative to BEG."
8367 (mapc (lambda (x)
8368 (move-marker (car x) (+ beg (cdr x))))
8369 org-markers-to-move)
8370 (setq org-markers-to-move nil))
8372 (defun org-narrow-to-subtree ()
8373 "Narrow buffer to the current subtree."
8374 (interactive)
8375 (save-excursion
8376 (save-match-data
8377 (org-with-limited-levels
8378 (narrow-to-region
8379 (progn (org-back-to-heading t) (point))
8380 (progn (org-end-of-subtree t t)
8381 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8382 (point)))))))
8384 (defun org-narrow-to-block ()
8385 "Narrow buffer to the current block."
8386 (interactive)
8387 (let* ((case-fold-search t)
8388 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8389 "^[ \t]*#\\+end_.*")))
8390 (if blockp
8391 (narrow-to-region (car blockp) (cdr blockp))
8392 (error "Not in a block"))))
8394 (eval-when-compile
8395 (defvar org-property-drawer-re))
8397 (defvar org-property-start-re) ;; defined below
8398 (defun org-clone-subtree-with-time-shift (n &optional shift)
8399 "Clone the task (subtree) at point N times.
8400 The clones will be inserted as siblings.
8402 In interactive use, the user will be prompted for the number of
8403 clones to be produced. When called with a universal prefix argument
8404 and if the entry has a timestamp, the user will also be prompted for
8405 a time shift, which may be a repeater as used in time stamps, for
8406 example `+3d'.
8408 When a valid repeater is given and the entry contains any time
8409 stamps, the clones will become a sequence in time, with time
8410 stamps in the subtree shifted for each clone produced. If SHIFT
8411 is nil or the empty string, time stamps will be left alone. The
8412 ID property of the original subtree is removed.
8414 If the original subtree did contain time stamps with a repeater,
8415 the following will happen:
8416 - the repeater will be removed in each clone
8417 - an additional clone will be produced, with the current, unshifted
8418 date(s) in the entry.
8419 - the original entry will be placed *after* all the clones, with
8420 repeater intact.
8421 - the start days in the repeater in the original entry will be shifted
8422 to past the last clone.
8423 In this way you can spell out a number of instances of a repeating task,
8424 and still retain the repeater to cover future instances of the task."
8425 (interactive "nNumber of clones to produce: ")
8426 (let ((shift
8427 (or shift
8428 (if (and (equal current-prefix-arg '(4))
8429 (save-excursion
8430 (re-search-forward org-ts-regexp-both
8431 (save-excursion
8432 (org-end-of-subtree t)
8433 (point)) t)))
8434 (read-from-minibuffer
8435 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8436 ""))) ;; No time shift
8437 (n-no-remove -1)
8438 (drawer-re org-drawer-regexp)
8439 beg end template task idprop
8440 shift-n shift-what doshift nmin nmax)
8441 (if (not (and (integerp n) (> n 0)))
8442 (error "Invalid number of replications %s" n))
8443 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8444 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8445 shift)))
8446 (error "Invalid shift specification %s" shift))
8447 (when doshift
8448 (setq shift-n (string-to-number (match-string 1 shift))
8449 shift-what (cdr (assoc (match-string 2 shift)
8450 '(("d" . day) ("w" . week)
8451 ("m" . month) ("y" . year))))))
8452 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8453 (setq nmin 1 nmax n)
8454 (org-back-to-heading t)
8455 (setq beg (point))
8456 (setq idprop (org-entry-get nil "ID"))
8457 (org-end-of-subtree t t)
8458 (or (bolp) (insert "\n"))
8459 (setq end (point))
8460 (setq template (buffer-substring beg end))
8461 (when (and doshift
8462 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8463 (delete-region beg end)
8464 (setq end beg)
8465 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8466 (goto-char end)
8467 (loop for n from nmin to nmax do
8468 ;; prepare clone
8469 (with-temp-buffer
8470 (insert template)
8471 (org-mode)
8472 (goto-char (point-min))
8473 (org-show-subtree)
8474 (and idprop (if org-clone-delete-id
8475 (org-entry-delete nil "ID")
8476 (org-id-get-create t)))
8477 (unless (= n 0)
8478 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8479 (kill-whole-line))
8480 (goto-char (point-min))
8481 (while (re-search-forward drawer-re nil t)
8482 (mapc (lambda (d)
8483 (org-remove-empty-drawer-at d (point))) org-drawers)))
8484 (goto-char (point-min))
8485 (when doshift
8486 (while (re-search-forward org-ts-regexp-both nil t)
8487 (org-timestamp-change (* n shift-n) shift-what))
8488 (unless (= n n-no-remove)
8489 (goto-char (point-min))
8490 (while (re-search-forward org-ts-regexp nil t)
8491 (save-excursion
8492 (goto-char (match-beginning 0))
8493 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8494 (delete-region (match-beginning 1) (match-end 1)))))))
8495 (setq task (buffer-string)))
8496 (insert task))
8497 (goto-char beg)))
8499 ;;; Outline Sorting
8501 (defun org-sort (with-case)
8502 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8503 Optional argument WITH-CASE means sort case-sensitively."
8504 (interactive "P")
8505 (cond
8506 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8507 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8509 (org-call-with-arg 'org-sort-entries with-case))))
8511 (defun org-sort-remove-invisible (s)
8512 "Remove invisible links from string S."
8513 (remove-text-properties 0 (length s) org-rm-props s)
8514 (while (string-match org-bracket-link-regexp s)
8515 (setq s (replace-match (if (match-end 2)
8516 (match-string 3 s)
8517 (match-string 1 s)) t t s)))
8518 (let ((st (format " %s " s)))
8519 (while (string-match org-emph-re st)
8520 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8521 (setq s (substring st 1 -1)))
8524 (defvar org-priority-regexp) ; defined later in the file
8526 (defvar org-after-sorting-entries-or-items-hook nil
8527 "Hook that is run after a bunch of entries or items have been sorted.
8528 When children are sorted, the cursor is in the parent line when this
8529 hook gets called. When a region or a plain list is sorted, the cursor
8530 will be in the first entry of the sorted region/list.")
8532 (defun org-sort-entries
8533 (&optional with-case sorting-type getkey-func compare-func property)
8534 "Sort entries on a certain level of an outline tree.
8535 If there is an active region, the entries in the region are sorted.
8536 Else, if the cursor is before the first entry, sort the top-level items.
8537 Else, the children of the entry at point are sorted.
8539 Sorting can be alphabetically, numerically, by date/time as given by
8540 a time stamp, by a property, by priority order, or by a custom function.
8542 The command prompts for the sorting type unless it has been given to the
8543 function through the SORTING-TYPE argument, which needs to be a character,
8544 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8545 precise meaning of each character:
8547 n Numerically, by converting the beginning of the entry/item to a number.
8548 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8549 o By order of TODO keywords.
8550 t By date/time, either the first active time stamp in the entry, or, if
8551 none exist, by the first inactive one.
8552 s By the scheduled date/time.
8553 d By deadline date/time.
8554 c By creation time, which is assumed to be the first inactive time stamp
8555 at the beginning of a line.
8556 p By priority according to the cookie.
8557 r By the value of a property.
8559 Capital letters will reverse the sort order.
8561 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8562 called with point at the beginning of the record. It must return either
8563 a string or a number that should serve as the sorting key for that record.
8565 Comparing entries ignores case by default. However, with an optional argument
8566 WITH-CASE, the sorting considers case as well.
8568 Sorting is done against the visible part of the headlines, it ignores hidden
8569 links."
8570 (interactive "P")
8571 (let ((case-func (if with-case 'identity 'downcase))
8572 (cmstr
8573 ;; The clock marker is lost when using `sort-subr', let's
8574 ;; store the clocking string.
8575 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8576 (save-excursion
8577 (goto-char org-clock-marker)
8578 (looking-back "^.*") (match-string-no-properties 0))))
8579 start beg end stars re re2
8580 txt what tmp)
8581 ;; Find beginning and end of region to sort
8582 (cond
8583 ((org-region-active-p)
8584 ;; we will sort the region
8585 (setq end (region-end)
8586 what "region")
8587 (goto-char (region-beginning))
8588 (if (not (org-at-heading-p)) (outline-next-heading))
8589 (setq start (point)))
8590 ((or (org-at-heading-p)
8591 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8592 ;; we will sort the children of the current headline
8593 (org-back-to-heading)
8594 (setq start (point)
8595 end (progn (org-end-of-subtree t t)
8596 (or (bolp) (insert "\n"))
8597 (org-back-over-empty-lines)
8598 (point))
8599 what "children")
8600 (goto-char start)
8601 (show-subtree)
8602 (outline-next-heading))
8604 ;; we will sort the top-level entries in this file
8605 (goto-char (point-min))
8606 (or (org-at-heading-p) (outline-next-heading))
8607 (setq start (point))
8608 (goto-char (point-max))
8609 (beginning-of-line 1)
8610 (when (looking-at ".*?\\S-")
8611 ;; File ends in a non-white line
8612 (end-of-line 1)
8613 (insert "\n"))
8614 (setq end (point-max))
8615 (setq what "top-level")
8616 (goto-char start)
8617 (show-all)))
8619 (setq beg (point))
8620 (if (>= beg end) (error "Nothing to sort"))
8622 (looking-at "\\(\\*+\\)")
8623 (setq stars (match-string 1)
8624 re (concat "^" (regexp-quote stars) " +")
8625 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8626 txt (buffer-substring beg end))
8627 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8628 (if (and (not (equal stars "*")) (string-match re2 txt))
8629 (error "Region to sort contains a level above the first entry"))
8631 (unless sorting-type
8632 (message
8633 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8634 [t]ime [s]cheduled [d]eadline [c]reated
8635 A/N/P/R/O/F/T/S/D/C means reversed:"
8636 what)
8637 (setq sorting-type (read-char-exclusive))
8639 (unless getkey-func
8640 (and (= (downcase sorting-type) ?f)
8641 (setq getkey-func
8642 (org-icompleting-read "Sort using function: "
8643 obarray 'fboundp t nil nil))
8644 (setq getkey-func (intern getkey-func))))
8646 (and (= (downcase sorting-type) ?r)
8647 (not property)
8648 (setq property
8649 (org-icompleting-read "Property: "
8650 (mapcar 'list (org-buffer-property-keys t))
8651 nil t))))
8653 (message "Sorting entries...")
8655 (save-restriction
8656 (narrow-to-region start end)
8657 (let ((dcst (downcase sorting-type))
8658 (case-fold-search nil)
8659 (now (current-time)))
8660 (sort-subr
8661 (/= dcst sorting-type)
8662 ;; This function moves to the beginning character of the "record" to
8663 ;; be sorted.
8664 (lambda nil
8665 (if (re-search-forward re nil t)
8666 (goto-char (match-beginning 0))
8667 (goto-char (point-max))))
8668 ;; This function moves to the last character of the "record" being
8669 ;; sorted.
8670 (lambda nil
8671 (save-match-data
8672 (condition-case nil
8673 (outline-forward-same-level 1)
8674 (error
8675 (goto-char (point-max))))))
8676 ;; This function returns the value that gets sorted against.
8677 (lambda nil
8678 (cond
8679 ((= dcst ?n)
8680 (if (looking-at org-complex-heading-regexp)
8681 (string-to-number (org-sort-remove-invisible (match-string 4)))
8682 nil))
8683 ((= dcst ?a)
8684 (if (looking-at org-complex-heading-regexp)
8685 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8686 nil))
8687 ((= dcst ?t)
8688 (let ((end (save-excursion (outline-next-heading) (point))))
8689 (if (or (re-search-forward org-ts-regexp end t)
8690 (re-search-forward org-ts-regexp-both end t))
8691 (org-time-string-to-seconds (match-string 0))
8692 (org-float-time now))))
8693 ((= dcst ?c)
8694 (let ((end (save-excursion (outline-next-heading) (point))))
8695 (if (re-search-forward
8696 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8697 end t)
8698 (org-time-string-to-seconds (match-string 0))
8699 (org-float-time now))))
8700 ((= dcst ?s)
8701 (let ((end (save-excursion (outline-next-heading) (point))))
8702 (if (re-search-forward org-scheduled-time-regexp end t)
8703 (org-time-string-to-seconds (match-string 1))
8704 (org-float-time now))))
8705 ((= dcst ?d)
8706 (let ((end (save-excursion (outline-next-heading) (point))))
8707 (if (re-search-forward org-deadline-time-regexp end t)
8708 (org-time-string-to-seconds (match-string 1))
8709 (org-float-time now))))
8710 ((= dcst ?p)
8711 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8712 (string-to-char (match-string 2))
8713 org-default-priority))
8714 ((= dcst ?r)
8715 (or (org-entry-get nil property) ""))
8716 ((= dcst ?o)
8717 (if (looking-at org-complex-heading-regexp)
8718 (- 9999 (length (member (match-string 2)
8719 org-todo-keywords-1)))))
8720 ((= dcst ?f)
8721 (if getkey-func
8722 (progn
8723 (setq tmp (funcall getkey-func))
8724 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8725 tmp)
8726 (error "Invalid key function `%s'" getkey-func)))
8727 (t (error "Invalid sorting type `%c'" sorting-type))))
8729 (cond
8730 ((= dcst ?a) 'string<)
8731 ((= dcst ?f) compare-func)
8732 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8733 (run-hooks 'org-after-sorting-entries-or-items-hook)
8734 ;; Reset the clock marker if needed
8735 (when cmstr
8736 (save-excursion
8737 (goto-char start)
8738 (search-forward cmstr nil t)
8739 (move-marker org-clock-marker (point))))
8740 (message "Sorting entries...done")))
8742 (defun org-do-sort (table what &optional with-case sorting-type)
8743 "Sort TABLE of WHAT according to SORTING-TYPE.
8744 The user will be prompted for the SORTING-TYPE if the call to this
8745 function does not specify it. WHAT is only for the prompt, to indicate
8746 what is being sorted. The sorting key will be extracted from
8747 the car of the elements of the table.
8748 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8749 (unless sorting-type
8750 (message
8751 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8752 what)
8753 (setq sorting-type (read-char-exclusive)))
8754 (let ((dcst (downcase sorting-type))
8755 extractfun comparefun)
8756 ;; Define the appropriate functions
8757 (cond
8758 ((= dcst ?n)
8759 (setq extractfun 'string-to-number
8760 comparefun (if (= dcst sorting-type) '< '>)))
8761 ((= dcst ?a)
8762 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8763 (lambda(x) (downcase (org-sort-remove-invisible x))))
8764 comparefun (if (= dcst sorting-type)
8765 'string<
8766 (lambda (a b) (and (not (string< a b))
8767 (not (string= a b)))))))
8768 ((= dcst ?t)
8769 (setq extractfun
8770 (lambda (x)
8771 (if (or (string-match org-ts-regexp x)
8772 (string-match org-ts-regexp-both x))
8773 (org-float-time
8774 (org-time-string-to-time (match-string 0 x)))
8776 comparefun (if (= dcst sorting-type) '< '>)))
8777 (t (error "Invalid sorting type `%c'" sorting-type)))
8779 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8780 table)
8781 (lambda (a b) (funcall comparefun (car a) (car b))))))
8784 ;;; The orgstruct minor mode
8786 ;; Define a minor mode which can be used in other modes in order to
8787 ;; integrate the org-mode structure editing commands.
8789 ;; This is really a hack, because the org-mode structure commands use
8790 ;; keys which normally belong to the major mode. Here is how it
8791 ;; works: The minor mode defines all the keys necessary to operate the
8792 ;; structure commands, but wraps the commands into a function which
8793 ;; tests if the cursor is currently at a headline or a plain list
8794 ;; item. If that is the case, the structure command is used,
8795 ;; temporarily setting many Org-mode variables like regular
8796 ;; expressions for filling etc. However, when any of those keys is
8797 ;; used at a different location, function uses `key-binding' to look
8798 ;; up if the key has an associated command in another currently active
8799 ;; keymap (minor modes, major mode, global), and executes that
8800 ;; command. There might be problems if any of the keys is otherwise
8801 ;; used as a prefix key.
8803 (defcustom orgstruct-heading-prefix-regexp nil
8804 "Regexp that matches the custom prefix of Org headlines in
8805 orgstruct(++)-mode."
8806 :group 'org
8807 :version "24.4"
8808 :package-version '(Org . "8.0")
8809 :type 'string)
8810 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8812 (defcustom orgstruct-setup-hook nil
8813 "Hook run after orgstruct-mode-map is filled."
8814 :group 'org
8815 :version "24.4"
8816 :package-version '(Org . "8.0")
8817 :type 'hook)
8819 (defvar orgstruct-initialized nil)
8821 (defvar org-local-vars nil
8822 "List of local variables, for use by `orgstruct-mode'.")
8824 ;;;###autoload
8825 (define-minor-mode orgstruct-mode
8826 "Toggle the minor mode `orgstruct-mode'.
8827 This mode is for using Org-mode structure commands in other
8828 modes. The following keys behave as if Org-mode were active, if
8829 the cursor is on a headline, or on a plain list item (both as
8830 defined by Org-mode)."
8831 nil " OrgStruct" (make-sparse-keymap)
8832 (funcall (if orgstruct-mode
8833 'add-to-invisibility-spec
8834 'remove-from-invisibility-spec)
8835 '(outline . t))
8836 (when orgstruct-mode
8837 (org-load-modules-maybe)
8838 (unless orgstruct-initialized
8839 (orgstruct-setup)
8840 (setq orgstruct-initialized t))))
8842 ;;;###autoload
8843 (defun turn-on-orgstruct ()
8844 "Unconditionally turn on `orgstruct-mode'."
8845 (orgstruct-mode 1))
8847 (defvar org-fb-vars nil)
8848 (make-variable-buffer-local 'org-fb-vars)
8849 (defun orgstruct++-mode (&optional arg)
8850 "Toggle `orgstruct-mode', the enhanced version of it.
8851 In addition to setting orgstruct-mode, this also exports all
8852 indentation and autofilling variables from org-mode into the
8853 buffer. It will also recognize item context in multiline items."
8854 (interactive "P")
8855 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8856 (if (< arg 1)
8857 (progn (orgstruct-mode -1)
8858 (mapc (lambda(v)
8859 (org-set-local (car v)
8860 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8861 org-fb-vars))
8862 (orgstruct-mode 1)
8863 (setq org-fb-vars nil)
8864 (let (var val)
8865 (mapc
8866 (lambda (x)
8867 (when (string-match
8868 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8869 (symbol-name (car x)))
8870 (setq var (car x) val (nth 1 x))
8871 (push (list var `(quote ,(eval var))) org-fb-vars)
8872 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8873 org-local-vars)
8874 (org-set-local 'orgstruct-is-++ t))))
8876 (defvar orgstruct-is-++ nil
8877 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8878 (make-variable-buffer-local 'orgstruct-is-++)
8880 ;;;###autoload
8881 (defun turn-on-orgstruct++ ()
8882 "Unconditionally turn on `orgstruct++-mode'."
8883 (orgstruct++-mode 1))
8885 (defun orgstruct-error ()
8886 "Error when there is no default binding for a structure key."
8887 (interactive)
8888 (funcall (if (fboundp 'user-error)
8889 'user-error
8890 'error)
8891 "This key has no function outside structure elements"))
8893 (defun orgstruct-setup ()
8894 "Setup orgstruct keymap."
8895 (dolist (cell '((org-demote . t)
8896 (org-metaleft . t)
8897 (org-metaright . t)
8898 (org-promote . t)
8899 (org-shiftmetaleft . t)
8900 (org-shiftmetaright . t)
8901 org-backward-element
8902 org-backward-heading-same-level
8903 org-ctrl-c-ret
8904 org-ctrl-c-minus
8905 org-ctrl-c-star
8906 org-cycle
8907 org-forward-heading-same-level
8908 org-insert-heading
8909 org-insert-heading-respect-content
8910 org-kill-note-or-show-branches
8911 org-mark-subtree
8912 org-meta-return
8913 org-metadown
8914 org-metaup
8915 org-narrow-to-subtree
8916 org-promote-subtree
8917 org-reveal
8918 org-shiftdown
8919 org-shiftleft
8920 org-shiftmetadown
8921 org-shiftmetaup
8922 org-shiftright
8923 org-shifttab
8924 org-shifttab
8925 org-shiftup
8926 org-show-subtree
8927 org-sort
8928 org-up-element
8929 outline-demote
8930 outline-next-visible-heading
8931 outline-previous-visible-heading
8932 outline-promote
8933 outline-up-heading
8934 show-children))
8935 (let ((f (or (car-safe cell) cell))
8936 (disable-when-heading-prefix (cdr-safe cell)))
8937 (when (fboundp f)
8938 (dolist (binding (nconc (where-is-internal f org-mode-map)
8939 (where-is-internal f outline-mode-map)))
8940 ;; TODO use local-function-key-map
8941 (dolist (rep '(("<tab>" . "TAB")
8942 ("<return>" . "RET")
8943 ("<escape>" . "ESC")
8944 ("<delete>" . "DEL")))
8945 (setq binding (read-kbd-macro
8946 (let ((case-fold-search))
8947 (replace-regexp-in-string
8948 (regexp-quote (cdr rep))
8949 (car rep)
8950 (key-description binding))))))
8951 (let ((key (lookup-key orgstruct-mode-map binding)))
8952 (when (or (not key) (numberp key))
8953 (condition-case nil
8954 (org-defkey orgstruct-mode-map
8955 binding
8956 (orgstruct-make-binding f binding disable-when-heading-prefix))
8957 (error nil))))))))
8958 (run-hooks 'orgstruct-setup-hook))
8960 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8961 "Create a function for binding in the structure minor mode.
8962 FUN is the command to call inside a table. KEY is the key that
8963 should be checked in for a command to execute outside of tables.
8964 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8965 if `orgstruct-heading-prefix-regexp' is non-nil."
8966 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8967 (let ((nname name)
8968 (i 0))
8969 (while (fboundp (intern nname))
8970 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8971 (setq name (intern nname)))
8972 (eval
8973 (let ((bindings '((org-heading-regexp
8974 (concat "^"
8975 orgstruct-heading-prefix-regexp
8976 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8977 (org-outline-regexp
8978 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8979 (org-outline-regexp-bol
8980 (concat "^" org-outline-regexp))
8981 (outline-regexp org-outline-regexp)
8982 (outline-heading-end-regexp "\n")
8983 (outline-level 'org-outline-level)
8984 (outline-heading-alist))))
8985 `(defun ,name (arg)
8986 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8987 "Outside of structure, run the binding of `"
8988 (key-description key) "'."
8989 (when disable-when-heading-prefix
8990 (concat
8991 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8992 "back to the default binding due to limitations of Org's implementation of\n"
8993 "`" (symbol-name fun) "'.")))
8994 (interactive "p")
8995 (let* ((disable
8996 ,(when disable-when-heading-prefix
8997 '(and orgstruct-heading-prefix-regexp
8998 (not (string= orgstruct-heading-prefix-regexp "")))))
8999 (fallback
9000 (or disable
9001 (not
9002 (let* ,bindings
9003 (org-context-p 'headline 'item
9004 ,(when (memq fun '(org-insert-heading))
9005 '(when orgstruct-is-++
9006 'item-body))))))))
9007 (if fallback
9008 (let* ((orgstruct-mode)
9009 (binding
9010 (loop with key = ,key
9011 for rep in
9012 '(nil
9013 ("<\\([^>]*\\)tab>" . "\\1TAB")
9014 ("<\\([^>]*\\)return>" . "\\1RET")
9015 ("<\\([^>]*\\)escape>" . "\\1ESC")
9016 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9018 (when rep
9019 (setq key (read-kbd-macro
9020 (let ((case-fold-search))
9021 (replace-regexp-in-string
9022 (car rep)
9023 (cdr rep)
9024 (key-description key))))))
9025 thereis (key-binding key))))
9026 (if (keymapp binding)
9027 (set-temporary-overlay-map binding)
9028 (let ((func (or binding
9029 (unless disable
9030 'orgstruct-error))))
9031 (when func
9032 (call-interactively func)))))
9033 (org-run-like-in-org-mode
9034 (lambda ()
9035 (interactive)
9036 (let* ,bindings
9037 (call-interactively ',fun)))))))))
9038 name))
9040 (defun org-contextualize-keys (alist contexts)
9041 "Return valid elements in ALIST depending on CONTEXTS.
9043 `org-agenda-custom-commands' or `org-capture-templates' are the
9044 values used for ALIST, and `org-agenda-custom-commands-contexts'
9045 or `org-capture-templates-contexts' are the associated contexts
9046 definitions."
9047 (let ((contexts
9048 ;; normalize contexts
9049 (mapcar
9050 (lambda(c) (cond ((listp (cadr c))
9051 (list (car c) (car c) (cadr c)))
9052 ((string= "" (cadr c))
9053 (list (car c) (car c) (caddr c)))
9054 (t c))) contexts))
9055 (a alist) c r s)
9056 ;; loop over all commands or templates
9057 (while (setq c (pop a))
9058 (let (vrules repl)
9059 (cond
9060 ((not (assoc (car c) contexts))
9061 (push c r))
9062 ((and (assoc (car c) contexts)
9063 (setq vrules (org-contextualize-validate-key
9064 (car c) contexts)))
9065 (mapc (lambda (vr)
9066 (when (not (equal (car vr) (cadr vr)))
9067 (setq repl vr))) vrules)
9068 (if (not repl) (push c r)
9069 (push (cadr repl) s)
9070 (push
9071 (cons (car c)
9072 (cdr (or (assoc (cadr repl) alist)
9073 (error "Undefined key `%s' as contextual replacement for `%s'"
9074 (cadr repl) (car c)))))
9075 r))))))
9076 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9077 (delq
9079 (delete-dups
9080 (mapcar (lambda (x)
9081 (let ((tpl (car x)))
9082 (when (not (delq
9084 (mapcar (lambda(y)
9085 (equal y tpl)) s))) x)))
9086 (reverse r))))))
9088 (defun org-contextualize-validate-key (key contexts)
9089 "Check CONTEXTS for agenda or capture KEY."
9090 (let (r rr res)
9091 (while (setq r (pop contexts))
9092 (mapc
9093 (lambda (rr)
9094 (when
9095 (and (equal key (car r))
9096 (if (functionp rr) (funcall rr)
9097 (or (and (eq (car rr) 'in-file)
9098 (buffer-file-name)
9099 (string-match (cdr rr) (buffer-file-name)))
9100 (and (eq (car rr) 'in-mode)
9101 (string-match (cdr rr) (symbol-name major-mode)))
9102 (and (eq (car rr) 'in-buffer)
9103 (string-match (cdr rr) (buffer-name)))
9104 (when (and (eq (car rr) 'not-in-file)
9105 (buffer-file-name))
9106 (not (string-match (cdr rr) (buffer-file-name))))
9107 (when (eq (car rr) 'not-in-mode)
9108 (not (string-match (cdr rr) (symbol-name major-mode))))
9109 (when (eq (car rr) 'not-in-buffer)
9110 (not (string-match (cdr rr) (buffer-name)))))))
9111 (push r res)))
9112 (car (last r))))
9113 (delete-dups (delq nil res))))
9115 (defun org-context-p (&rest contexts)
9116 "Check if local context is any of CONTEXTS.
9117 Possible values in the list of contexts are `table', `headline', and `item'."
9118 (let ((pos (point)))
9119 (goto-char (point-at-bol))
9120 (prog1 (or (and (memq 'table contexts)
9121 (looking-at "[ \t]*|"))
9122 (and (memq 'headline contexts)
9123 (looking-at org-outline-regexp))
9124 (and (memq 'item contexts)
9125 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9126 (and (memq 'item-body contexts)
9127 (org-in-item-p)))
9128 (goto-char pos))))
9130 (defun org-get-local-variables ()
9131 "Return a list of all local variables in an Org mode buffer."
9132 (let (varlist)
9133 (with-current-buffer (get-buffer-create "*Org tmp*")
9134 (erase-buffer)
9135 (org-mode)
9136 (setq varlist (buffer-local-variables)))
9137 (kill-buffer "*Org tmp*")
9138 (delq nil
9139 (mapcar
9140 (lambda (x)
9141 (setq x
9142 (if (symbolp x)
9143 (list x)
9144 (list (car x) (cdr x))))
9145 (if (and (not (get (car x) 'org-state))
9146 (string-match
9147 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9148 (symbol-name (car x))))
9149 x nil))
9150 varlist))))
9152 (defun org-clone-local-variables (from-buffer &optional regexp)
9153 "Clone local variables from FROM-BUFFER.
9154 Optional argument REGEXP selects variables to clone."
9155 (mapc
9156 (lambda (pair)
9157 (and (symbolp (car pair))
9158 (or (null regexp)
9159 (string-match regexp (symbol-name (car pair))))
9160 (set (make-local-variable (car pair))
9161 (cdr pair))))
9162 (buffer-local-variables from-buffer)))
9164 ;;;###autoload
9165 (defun org-run-like-in-org-mode (cmd)
9166 "Run a command, pretending that the current buffer is in Org-mode.
9167 This will temporarily bind local variables that are typically bound in
9168 Org-mode to the values they have in Org-mode, and then interactively
9169 call CMD."
9170 (org-load-modules-maybe)
9171 (unless org-local-vars
9172 (setq org-local-vars (org-get-local-variables)))
9173 (let (binds)
9174 (dolist (var org-local-vars)
9175 (when (or (not (boundp (car var)))
9176 (eq (symbol-value (car var))
9177 (default-value (car var))))
9178 (push (list (car var) `(quote ,(cadr var))) binds)))
9179 (eval `(let ,binds
9180 (call-interactively (quote ,cmd))))))
9182 ;;;; Archiving
9184 (defun org-get-category (&optional pos force-refresh)
9185 "Get the category applying to position POS."
9186 (save-match-data
9187 (if force-refresh (org-refresh-category-properties))
9188 (let ((pos (or pos (point))))
9189 (or (get-text-property pos 'org-category)
9190 (progn (org-refresh-category-properties)
9191 (get-text-property pos 'org-category))))))
9193 (defun org-refresh-category-properties ()
9194 "Refresh category text properties in the buffer."
9195 (let ((case-fold-search t)
9196 (inhibit-read-only t)
9197 (def-cat (cond
9198 ((null org-category)
9199 (if buffer-file-name
9200 (file-name-sans-extension
9201 (file-name-nondirectory buffer-file-name))
9202 "???"))
9203 ((symbolp org-category) (symbol-name org-category))
9204 (t org-category)))
9205 beg end cat pos optionp)
9206 (org-with-silent-modifications
9207 (save-excursion
9208 (save-restriction
9209 (widen)
9210 (goto-char (point-min))
9211 (put-text-property (point) (point-max) 'org-category def-cat)
9212 (while (re-search-forward
9213 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9214 (setq pos (match-end 0)
9215 optionp (equal (char-after (match-beginning 0)) ?#)
9216 cat (org-trim (match-string 2)))
9217 (if optionp
9218 (setq beg (point-at-bol) end (point-max))
9219 (org-back-to-heading t)
9220 (setq beg (point) end (org-end-of-subtree t t)))
9221 (put-text-property beg end 'org-category cat)
9222 (put-text-property beg end 'org-category-position beg)
9223 (goto-char pos)))))))
9225 (defun org-refresh-properties (dprop tprop)
9226 "Refresh buffer text properties.
9227 DPROP is the drawer property and TPROP is the corresponding text
9228 property to set."
9229 (let ((case-fold-search t)
9230 (inhibit-read-only t) p)
9231 (org-with-silent-modifications
9232 (save-excursion
9233 (save-restriction
9234 (widen)
9235 (goto-char (point-min))
9236 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9237 (setq p (org-match-string-no-properties 1))
9238 (save-excursion
9239 (org-back-to-heading t)
9240 (put-text-property
9241 (point-at-bol) (point-at-eol) tprop p))))))))
9244 ;;;; Link Stuff
9246 ;;; Link abbreviations
9248 (defun org-link-expand-abbrev (link)
9249 "Apply replacements as defined in `org-link-abbrev-alist'."
9250 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9251 (let* ((key (match-string 1 link))
9252 (as (or (assoc key org-link-abbrev-alist-local)
9253 (assoc key org-link-abbrev-alist)))
9254 (tag (and (match-end 2) (match-string 3 link)))
9255 rpl)
9256 (if (not as)
9257 link
9258 (setq rpl (cdr as))
9259 (cond
9260 ((symbolp rpl) (funcall rpl tag))
9261 ((string-match "%(\\([^)]+\\))" rpl)
9262 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9263 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9264 ((string-match "%h" rpl)
9265 (replace-match (url-hexify-string (or tag "")) t t rpl))
9266 (t (concat rpl tag)))))
9267 link))
9269 ;;; Storing and inserting links
9271 (defvar org-insert-link-history nil
9272 "Minibuffer history for links inserted with `org-insert-link'.")
9274 (defvar org-stored-links nil
9275 "Contains the links stored with `org-store-link'.")
9277 (defvar org-store-link-plist nil
9278 "Plist with info about the most recently link created with `org-store-link'.")
9280 (defvar org-link-protocols nil
9281 "Link protocols added to Org-mode using `org-add-link-type'.")
9283 (defvar org-store-link-functions nil
9284 "List of functions that are called to create and store a link.
9285 Each function will be called in turn until one returns a non-nil
9286 value. Each function should check if it is responsible for creating
9287 this link (for example by looking at the major mode).
9288 If not, it must exit and return nil.
9289 If yes, it should return a non-nil value after a calling
9290 `org-store-link-props' with a list of properties and values.
9291 Special properties are:
9293 :type The link prefix, like \"http\". This must be given.
9294 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9295 This is obligatory as well.
9296 :description Optional default description for the second pair
9297 of brackets in an Org-mode link. The user can still change
9298 this when inserting this link into an Org-mode buffer.
9300 In addition to these, any additional properties can be specified
9301 and then used in capture templates.")
9303 (defun org-add-link-type (type &optional follow export)
9304 "Add TYPE to the list of `org-link-types'.
9305 Re-compute all regular expressions depending on `org-link-types'
9307 FOLLOW and EXPORT are two functions.
9309 FOLLOW should take the link path as the single argument and do whatever
9310 is necessary to follow the link, for example find a file or display
9311 a mail message.
9313 EXPORT should format the link path for export to one of the export formats.
9314 It should be a function accepting three arguments:
9316 path the path of the link, the text after the prefix (like \"http:\")
9317 desc the description of the link, if any, or a description added by
9318 org-export-normalize-links if there is none
9319 format the export format, a symbol like `html' or `latex' or `ascii'..
9321 The function may use the FORMAT information to return different values
9322 depending on the format. The return value will be put literally into
9323 the exported file. If the return value is nil, this means Org should
9324 do what it normally does with links which do not have EXPORT defined.
9326 Org-mode has a built-in default for exporting links. If you are happy with
9327 this default, there is no need to define an export function for the link
9328 type. For a simple example of an export function, see `org-bbdb.el'."
9329 (add-to-list 'org-link-types type t)
9330 (org-make-link-regexps)
9331 (if (assoc type org-link-protocols)
9332 (setcdr (assoc type org-link-protocols) (list follow export))
9333 (push (list type follow export) org-link-protocols)))
9335 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9336 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9338 ;;;###autoload
9339 (defun org-store-link (arg)
9340 "\\<org-mode-map>Store an org-link to the current location.
9341 This link is added to `org-stored-links' and can later be inserted
9342 into an org-buffer with \\[org-insert-link].
9344 For some link types, a prefix arg is interpreted.
9345 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9346 For file links, arg negates `org-context-in-file-links'.
9348 A double prefix arg force skipping storing functions that are not
9349 part of Org's core.
9351 A triple prefix arg force storing a link for each line in the
9352 active region."
9353 (interactive "P")
9354 (org-load-modules-maybe)
9355 (if (and (equal arg '(64)) (org-region-active-p))
9356 (save-excursion
9357 (let ((end (region-end)))
9358 (goto-char (region-beginning))
9359 (set-mark (point))
9360 (while (< (point-at-eol) end)
9361 (move-end-of-line 1) (activate-mark)
9362 (let (current-prefix-arg)
9363 (call-interactively 'org-store-link))
9364 (move-beginning-of-line 2)
9365 (set-mark (point)))))
9366 (org-with-limited-levels
9367 (setq org-store-link-plist nil)
9368 (let (link cpltxt desc description search
9369 txt custom-id agenda-link sfuns sfunsn)
9370 (cond
9372 ;; Store a link using an external link type
9373 ((and (not (equal arg '(16)))
9374 (setq sfuns
9375 (delq
9376 nil (mapcar (lambda (f)
9377 (let (fs) (if (funcall f) (push f fs))))
9378 org-store-link-functions))
9379 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9380 (or (and (cdr sfuns)
9381 (funcall (intern
9382 (completing-read
9383 "Which function for creating the link? "
9384 sfunsn t (car sfunsn)))))
9385 (funcall (caar sfuns)))
9386 (setq link (plist-get org-store-link-plist :link)
9387 desc (or (plist-get org-store-link-plist
9388 :description) link))))
9390 ;; Store a link from a source code buffer
9391 ((org-src-edit-buffer-p)
9392 (let (label gc)
9393 (while (or (not label)
9394 (save-excursion
9395 (save-restriction
9396 (widen)
9397 (goto-char (point-min))
9398 (re-search-forward
9399 (regexp-quote (format org-coderef-label-format label))
9400 nil t))))
9401 (when label (message "Label exists already") (sit-for 2))
9402 (setq label (read-string "Code line label: " label)))
9403 (end-of-line 1)
9404 (setq link (format org-coderef-label-format label))
9405 (setq gc (- 79 (length link)))
9406 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9407 (insert link)
9408 (setq link (concat "(" label ")") desc nil)))
9410 ;; We are in the agenda, link to referenced location
9411 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9412 (let ((m (or (get-text-property (point) 'org-hd-marker)
9413 (get-text-property (point) 'org-marker))))
9414 (when m
9415 (org-with-point-at m
9416 (setq agenda-link
9417 (if (org-called-interactively-p 'any)
9418 (call-interactively 'org-store-link)
9419 (org-store-link nil)))))))
9421 ((eq major-mode 'calendar-mode)
9422 (let ((cd (calendar-cursor-to-date)))
9423 (setq link
9424 (format-time-string
9425 (car org-time-stamp-formats)
9426 (apply 'encode-time
9427 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9428 nil nil nil))))
9429 (org-store-link-props :type "calendar" :date cd)))
9431 ((eq major-mode 'help-mode)
9432 (setq link (concat "help:" (save-excursion
9433 (goto-char (point-min))
9434 (looking-at "^[^ ]+")
9435 (match-string 0))))
9436 (org-store-link-props :type "help"))
9438 ((eq major-mode 'w3-mode)
9439 (setq cpltxt (if (and (buffer-name)
9440 (not (string-match "Untitled" (buffer-name))))
9441 (buffer-name)
9442 (url-view-url t))
9443 link (url-view-url t))
9444 (org-store-link-props :type "w3" :url (url-view-url t)))
9446 ((eq major-mode 'image-mode)
9447 (setq cpltxt (concat "file:"
9448 (abbreviate-file-name buffer-file-name))
9449 link cpltxt)
9450 (org-store-link-props :type "image" :file buffer-file-name))
9452 ;; In dired, store a link to the file of the current line
9453 ((eq major-mode 'dired-mode)
9454 (let ((file (dired-get-filename nil t)))
9455 (setq file (if file
9456 (abbreviate-file-name
9457 (expand-file-name (dired-get-filename nil t)))
9458 ;; otherwise, no file so use current directory.
9459 default-directory))
9460 (setq cpltxt (concat "file:" file)
9461 link cpltxt)))
9463 ((setq search (run-hook-with-args-until-success
9464 'org-create-file-search-functions))
9465 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9466 "::" search))
9467 (setq cpltxt (or description link)))
9469 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9470 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9471 (cond
9472 ;; Store a link using the radio target at point
9473 ((org-in-regexp "<<\\(.*?\\)>>")
9474 (setq cpltxt
9475 (concat "file:"
9476 (abbreviate-file-name
9477 (buffer-file-name (buffer-base-buffer)))
9478 "::" (match-string 1))
9479 link cpltxt))
9480 ((and (featurep 'org-id)
9481 (or (eq org-id-link-to-org-use-id t)
9482 (and (org-called-interactively-p 'any)
9483 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9484 (and (eq org-id-link-to-org-use-id
9485 'create-if-interactive-and-no-custom-id)
9486 (not custom-id))))
9487 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9488 ;; Store a link using the ID at point
9489 (setq link (condition-case nil
9490 (prog1 (org-id-store-link)
9491 (setq desc (plist-get org-store-link-plist
9492 :description)))
9493 (error
9494 ;; Probably before first headline, link only to file
9495 (concat "file:"
9496 (abbreviate-file-name
9497 (buffer-file-name (buffer-base-buffer))))))))
9499 ;; Just link to current headline
9500 (setq cpltxt (concat "file:"
9501 (abbreviate-file-name
9502 (buffer-file-name (buffer-base-buffer)))))
9503 ;; Add a context search string
9504 (when (org-xor org-context-in-file-links arg)
9505 (let* ((ee (org-element-at-point))
9506 (et (org-element-type ee))
9507 (ev (plist-get (cadr ee) :value))
9508 (ek (plist-get (cadr ee) :key))
9509 (eok (and (stringp ek) (string-match "name" ek))))
9510 (setq txt (cond
9511 ((org-at-heading-p) nil)
9512 ((and (eq et 'keyword) eok) ev)
9513 ((org-region-active-p)
9514 (buffer-substring (region-beginning) (region-end)))))
9515 (when (or (null txt) (string-match "\\S-" txt))
9516 (setq cpltxt
9517 (concat cpltxt "::"
9518 (condition-case nil
9519 (org-make-org-heading-search-string txt)
9520 (error "")))
9521 desc (or (and (eq et 'keyword) eok ev)
9522 (nth 4 (ignore-errors (org-heading-components)))
9523 "NONE")))))
9524 (if (string-match "::\\'" cpltxt)
9525 (setq cpltxt (substring cpltxt 0 -2)))
9526 (setq link cpltxt))))
9528 ((buffer-file-name (buffer-base-buffer))
9529 ;; Just link to this file here.
9530 (setq cpltxt (concat "file:"
9531 (abbreviate-file-name
9532 (buffer-file-name (buffer-base-buffer)))))
9533 ;; Add a context string.
9534 (when (org-xor org-context-in-file-links arg)
9535 (setq txt (if (org-region-active-p)
9536 (buffer-substring (region-beginning) (region-end))
9537 (buffer-substring (point-at-bol) (point-at-eol))))
9538 ;; Only use search option if there is some text.
9539 (when (string-match "\\S-" txt)
9540 (setq cpltxt
9541 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9542 desc "NONE")))
9543 (setq link cpltxt))
9545 ((org-called-interactively-p 'interactive)
9546 (user-error "No method for storing a link from this buffer"))
9548 (t (setq link nil)))
9550 ;; We're done setting link and desc, clean up
9551 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9552 (setq link (or link cpltxt)
9553 desc (or desc cpltxt))
9554 (cond ((equal desc "NONE") (setq desc nil))
9555 ((string-match org-bracket-link-regexp desc)
9556 (setq desc
9557 (replace-regexp-in-string
9558 org-bracket-link-regexp
9559 (concat "\\3" (if (equal (length (match-string 0 desc))
9560 (length desc)) "*" "")) desc))))
9562 ;; Return the link
9563 (if (not (and (or (org-called-interactively-p 'any)
9564 executing-kbd-macro) link))
9565 (or agenda-link (and link (org-make-link-string link desc)))
9566 (push (list link desc) org-stored-links)
9567 (message "Stored: %s" (or desc link))
9568 (when custom-id
9569 (setq link (concat "file:" (abbreviate-file-name
9570 (buffer-file-name)) "::#" custom-id))
9571 (push (list link desc) org-stored-links)))))))
9573 (defun org-store-link-props (&rest plist)
9574 "Store link properties, extract names and addresses."
9575 (let (x adr)
9576 (when (setq x (plist-get plist :from))
9577 (setq adr (mail-extract-address-components x))
9578 (setq plist (plist-put plist :fromname (car adr)))
9579 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9580 (when (setq x (plist-get plist :to))
9581 (setq adr (mail-extract-address-components x))
9582 (setq plist (plist-put plist :toname (car adr)))
9583 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9584 (let ((from (plist-get plist :from))
9585 (to (plist-get plist :to)))
9586 (when (and from to org-from-is-user-regexp)
9587 (setq plist
9588 (plist-put plist :fromto
9589 (if (string-match org-from-is-user-regexp from)
9590 (concat "to %t")
9591 (concat "from %f"))))))
9592 (setq org-store-link-plist plist))
9594 (defun org-add-link-props (&rest plist)
9595 "Add these properties to the link property list."
9596 (let (key value)
9597 (while plist
9598 (setq key (pop plist) value (pop plist))
9599 (setq org-store-link-plist
9600 (plist-put org-store-link-plist key value)))))
9602 (defun org-email-link-description (&optional fmt)
9603 "Return the description part of an email link.
9604 This takes information from `org-store-link-plist' and formats it
9605 according to FMT (default from `org-email-link-description-format')."
9606 (setq fmt (or fmt org-email-link-description-format))
9607 (let* ((p org-store-link-plist)
9608 (to (plist-get p :toaddress))
9609 (from (plist-get p :fromaddress))
9610 (table
9611 (list
9612 (cons "%c" (plist-get p :fromto))
9613 (cons "%F" (plist-get p :from))
9614 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9615 (cons "%T" (plist-get p :to))
9616 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9617 (cons "%s" (plist-get p :subject))
9618 (cons "%d" (plist-get p :date))
9619 (cons "%m" (plist-get p :message-id)))))
9620 (when (string-match "%c" fmt)
9621 ;; Check if the user wrote this message
9622 (if (and org-from-is-user-regexp from to
9623 (save-match-data (string-match org-from-is-user-regexp from)))
9624 (setq fmt (replace-match "to %t" t t fmt))
9625 (setq fmt (replace-match "from %f" t t fmt))))
9626 (org-replace-escapes fmt table)))
9628 (defun org-make-org-heading-search-string (&optional string)
9629 "Make search string for the current headline or STRING."
9630 (let ((s (or string
9631 (and (derived-mode-p 'org-mode)
9632 (save-excursion
9633 (org-back-to-heading t)
9634 (org-element-property :raw-value (org-element-at-point))))))
9635 (lines org-context-in-file-links))
9636 (or string (setq s (concat "*" s))) ; Add * for headlines
9637 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9638 (when (and string (integerp lines) (> lines 0))
9639 (let ((slines (org-split-string s "\n")))
9640 (when (< lines (length slines))
9641 (setq s (mapconcat
9642 'identity
9643 (reverse (nthcdr (- (length slines) lines)
9644 (reverse slines))) "\n")))))
9645 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9647 (defun org-make-link-string (link &optional description)
9648 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9649 (unless (string-match "\\S-" link)
9650 (error "Empty link"))
9651 (when (and description
9652 (stringp description)
9653 (not (string-match "\\S-" description)))
9654 (setq description nil))
9655 (when (stringp description)
9656 ;; Remove brackets from the description, they are fatal.
9657 (while (string-match "\\[" description)
9658 (setq description (replace-match "{" t t description)))
9659 (while (string-match "\\]" description)
9660 (setq description (replace-match "}" t t description))))
9661 (when (equal link description)
9662 ;; No description needed, it is identical
9663 (setq description nil))
9664 (when (and (not description)
9665 (not (string-match (org-image-file-name-regexp) link))
9666 (not (equal link (org-link-escape link))))
9667 (setq description (org-extract-attributes link)))
9668 (setq link
9669 (cond ((string-match (org-image-file-name-regexp) link) link)
9670 ((string-match org-link-types-re link)
9671 (concat (match-string 1 link)
9672 (org-link-escape (substring link (match-end 1)))))
9673 (t (org-link-escape link))))
9674 (concat "[[" link "]"
9675 (if description (concat "[" description "]") "")
9676 "]"))
9678 (defconst org-link-escape-chars
9679 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9680 "List of characters that should be escaped in link.
9681 This is the list that is used for internal purposes.")
9683 (defconst org-link-escape-chars-browser
9684 '(?\ )
9685 "List of escapes for characters that are problematic in links.
9686 This is the list that is used before handing over to the browser.")
9688 (defun org-link-escape (text &optional table merge)
9689 "Return percent escaped representation of TEXT.
9690 TEXT is a string with the text to escape.
9691 Optional argument TABLE is a list with characters that should be
9692 escaped. When nil, `org-link-escape-chars' is used.
9693 If optional argument MERGE is set, merge TABLE into
9694 `org-link-escape-chars'."
9695 (cond
9696 ((and table merge)
9697 (mapc (lambda (defchr)
9698 (unless (member defchr table)
9699 (setq table (cons defchr table)))) org-link-escape-chars))
9700 ((null table)
9701 (setq table org-link-escape-chars)))
9702 (mapconcat
9703 (lambda (char)
9704 (if (or (member char table)
9705 (and (or (< char 32) (= char 37) (> char 126))
9706 org-url-hexify-p))
9707 (mapconcat (lambda (sequence-element)
9708 (format "%%%.2X" sequence-element))
9709 (or (encode-coding-char char 'utf-8)
9710 (error "Unable to percent escape character: %s"
9711 (char-to-string char))) "")
9712 (char-to-string char))) text ""))
9714 (defun org-link-unescape (str)
9715 "Unhex hexified Unicode strings as returned from the JavaScript function
9716 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9717 (unless (and (null str) (string= "" str))
9718 (let ((pos 0) (case-fold-search t) unhexed)
9719 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9720 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9721 (setq str (replace-match unhexed t t str))
9722 (setq pos (+ pos (length unhexed))))))
9723 str)
9725 (defun org-link-unescape-compound (hex)
9726 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9727 Note: this function also decodes single byte encodings like
9728 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9729 (save-match-data
9730 (let* ((bytes (cdr (split-string hex "%")))
9731 (ret "")
9732 (eat 0)
9733 (sum 0))
9734 (while bytes
9735 (let* ((val (string-to-number (pop bytes) 16))
9736 (shift-xor
9737 (if (= 0 eat)
9738 (cond
9739 ((>= val 252) (cons 6 252))
9740 ((>= val 248) (cons 5 248))
9741 ((>= val 240) (cons 4 240))
9742 ((>= val 224) (cons 3 224))
9743 ((>= val 192) (cons 2 192))
9744 (t (cons 0 0)))
9745 (cons 6 128))))
9746 (if (>= val 192) (setq eat (car shift-xor)))
9747 (setq val (logxor val (cdr shift-xor)))
9748 (setq sum (+ (lsh sum (car shift-xor)) val))
9749 (if (> eat 0) (setq eat (- eat 1)))
9750 (cond
9751 ((= 0 eat) ;multi byte
9752 (setq ret (concat ret (org-char-to-string sum)))
9753 (setq sum 0))
9754 ((not bytes) ; single byte(s)
9755 (setq ret (org-link-unescape-single-byte-sequence hex))))
9756 )) ;; end (while bytes
9757 ret )))
9759 (defun org-link-unescape-single-byte-sequence (hex)
9760 "Unhexify hex-encoded single byte character sequences."
9761 (mapconcat (lambda (byte)
9762 (char-to-string (string-to-number byte 16)))
9763 (cdr (split-string hex "%")) ""))
9765 (defun org-xor (a b)
9766 "Exclusive or."
9767 (if a (not b) b))
9769 (defun org-fixup-message-id-for-http (s)
9770 "Replace special characters in a message id, so it can be used in an http query."
9771 (when (string-match "%" s)
9772 (setq s (mapconcat (lambda (c)
9773 (if (eq c ?%)
9774 "%25"
9775 (char-to-string c)))
9776 s "")))
9777 (while (string-match "<" s)
9778 (setq s (replace-match "%3C" t t s)))
9779 (while (string-match ">" s)
9780 (setq s (replace-match "%3E" t t s)))
9781 (while (string-match "@" s)
9782 (setq s (replace-match "%40" t t s)))
9785 (defun org-link-prettify (link)
9786 "Return a human-readable representation of LINK.
9787 The car of LINK must be a raw link the cdr of LINK must be either
9788 a link description or nil."
9789 (let ((desc (or (cadr link) "<no description>")))
9790 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9791 "<" (car link) ">")))
9793 ;;;###autoload
9794 (defun org-insert-link-global ()
9795 "Insert a link like Org-mode does.
9796 This command can be called in any mode to insert a link in Org-mode syntax."
9797 (interactive)
9798 (org-load-modules-maybe)
9799 (org-run-like-in-org-mode 'org-insert-link))
9801 (defun org-insert-all-links (&optional keep)
9802 "Insert all links in `org-stored-links'."
9803 (interactive "P")
9804 (let ((links (copy-sequence org-stored-links)) l)
9805 (while (setq l (if keep (pop links) (pop org-stored-links)))
9806 (insert "- ")
9807 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9808 (insert "\n"))))
9810 (defun org-link-fontify-links-to-this-file ()
9811 "Fontify links to the current file in `org-stored-links'."
9812 (let ((f (buffer-file-name)) a b)
9813 (setq a (mapcar (lambda(l)
9814 (let ((ll (car l)))
9815 (when (and (string-match "^file:\\(.+\\)::" ll)
9816 (equal f (expand-file-name (match-string 1 ll))))
9817 ll)))
9818 org-stored-links))
9819 (when (featurep 'org-id)
9820 (setq b (mapcar (lambda(l)
9821 (let ((ll (car l)))
9822 (when (and (string-match "^id:\\(.+\\)$" ll)
9823 (equal f (expand-file-name
9824 (or (org-id-find-id-file
9825 (match-string 1 ll)) ""))))
9826 ll)))
9827 org-stored-links)))
9828 (mapcar (lambda(l)
9829 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9830 (delq nil (append a b)))))
9832 (defvar org-link-links-in-this-file nil)
9833 (defun org-insert-link (&optional complete-file link-location default-description)
9834 "Insert a link. At the prompt, enter the link.
9836 Completion can be used to insert any of the link protocol prefixes like
9837 http or ftp in use.
9839 The history can be used to select a link previously stored with
9840 `org-store-link'. When the empty string is entered (i.e. if you just
9841 press RET at the prompt), the link defaults to the most recently
9842 stored link. As SPC triggers completion in the minibuffer, you need to
9843 use M-SPC or C-q SPC to force the insertion of a space character.
9845 You will also be prompted for a description, and if one is given, it will
9846 be displayed in the buffer instead of the link.
9848 If there is already a link at point, this command will allow you to edit link
9849 and description parts.
9851 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9852 be selected using completion. The path to the file will be relative to the
9853 current directory if the file is in the current directory or a subdirectory.
9854 Otherwise, the link will be the absolute path as completed in the minibuffer
9855 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9856 option `org-link-file-path-type'.
9858 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9859 the current directory or below.
9861 With three \\[universal-argument] prefixes, negate the meaning of
9862 `org-keep-stored-link-after-insertion'.
9864 If `org-make-link-description-function' is non-nil, this function will be
9865 called with the link target, and the result will be the default
9866 link description.
9868 If the LINK-LOCATION parameter is non-nil, this value will be
9869 used as the link location instead of reading one interactively.
9871 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9872 be used as the default description."
9873 (interactive "P")
9874 (let* ((wcf (current-window-configuration))
9875 (origbuf (current-buffer))
9876 (region (if (org-region-active-p)
9877 (buffer-substring (region-beginning) (region-end))))
9878 (remove (and region (list (region-beginning) (region-end))))
9879 (desc region)
9880 tmphist ; byte-compile incorrectly complains about this
9881 (link link-location)
9882 (abbrevs org-link-abbrev-alist-local)
9883 entry file all-prefixes auto-desc)
9884 (cond
9885 (link-location) ; specified by arg, just use it.
9886 ((org-in-regexp org-bracket-link-regexp 1)
9887 ;; We do have a link at point, and we are going to edit it.
9888 (setq remove (list (match-beginning 0) (match-end 0)))
9889 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9890 (setq link (read-string "Link: "
9891 (org-link-unescape
9892 (org-match-string-no-properties 1)))))
9893 ((or (org-in-regexp org-angle-link-re)
9894 (org-in-regexp org-plain-link-re))
9895 ;; Convert to bracket link
9896 (setq remove (list (match-beginning 0) (match-end 0))
9897 link (read-string "Link: "
9898 (org-remove-angle-brackets (match-string 0)))))
9899 ((member complete-file '((4) (16)))
9900 ;; Completing read for file names.
9901 (setq link (org-file-complete-link complete-file)))
9903 ;; Read link, with completion for stored links.
9904 (org-link-fontify-links-to-this-file)
9905 (org-switch-to-buffer-other-window "*Org Links*")
9906 (with-current-buffer "*Org Links*"
9907 (erase-buffer)
9908 (insert "Insert a link.
9909 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9910 (when org-stored-links
9911 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9912 (insert (mapconcat 'org-link-prettify
9913 (reverse org-stored-links) "\n")))
9914 (goto-char (point-min)))
9915 (let ((cw (selected-window)))
9916 (select-window (get-buffer-window "*Org Links*" 'visible))
9917 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9918 (unless (pos-visible-in-window-p (point-max))
9919 (org-fit-window-to-buffer))
9920 (and (window-live-p cw) (select-window cw)))
9921 ;; Fake a link history, containing the stored links.
9922 (setq tmphist (append (mapcar 'car org-stored-links)
9923 org-insert-link-history))
9924 (setq all-prefixes (append (mapcar 'car abbrevs)
9925 (mapcar 'car org-link-abbrev-alist)
9926 org-link-types))
9927 (unwind-protect
9928 (progn
9929 (setq link
9930 (org-completing-read
9931 "Link: "
9932 (append
9933 (mapcar (lambda (x) (concat x ":"))
9934 all-prefixes)
9935 (mapcar 'car org-stored-links))
9936 nil nil nil
9937 'tmphist
9938 (caar org-stored-links)))
9939 (if (not (string-match "\\S-" link))
9940 (error "No link selected"))
9941 (mapc (lambda(l)
9942 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9943 org-stored-links)
9944 (if (or (member link all-prefixes)
9945 (and (equal ":" (substring link -1))
9946 (member (substring link 0 -1) all-prefixes)
9947 (setq link (substring link 0 -1))))
9948 (setq link (with-current-buffer origbuf
9949 (org-link-try-special-completion link)))))
9950 (set-window-configuration wcf)
9951 (kill-buffer "*Org Links*"))
9952 (setq entry (assoc link org-stored-links))
9953 (or entry (push link org-insert-link-history))
9954 (setq desc (or desc (nth 1 entry)))))
9956 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9957 (not org-keep-stored-link-after-insertion))
9958 (setq org-stored-links (delq (assoc link org-stored-links)
9959 org-stored-links)))
9961 (if (string-match org-plain-link-re link)
9962 ;; URL-like link, normalize the use of angular brackets.
9963 (setq link (org-remove-angle-brackets link)))
9965 ;; Check if we are linking to the current file with a search
9966 ;; option If yes, simplify the link by using only the search
9967 ;; option.
9968 (when (and buffer-file-name
9969 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9970 (let* ((path (match-string 1 link))
9971 (case-fold-search nil)
9972 (search (match-string 2 link)))
9973 (save-match-data
9974 (if (equal (file-truename buffer-file-name) (file-truename path))
9975 ;; We are linking to this same file, with a search option
9976 (setq link search)))))
9978 ;; Check if we can/should use a relative path. If yes, simplify the link
9979 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9980 (let* ((type (match-string 1 link))
9981 (path (match-string 2 link))
9982 (origpath path)
9983 (case-fold-search nil))
9984 (cond
9985 ((or (eq org-link-file-path-type 'absolute)
9986 (equal complete-file '(16)))
9987 (setq path (abbreviate-file-name (expand-file-name path))))
9988 ((eq org-link-file-path-type 'noabbrev)
9989 (setq path (expand-file-name path)))
9990 ((eq org-link-file-path-type 'relative)
9991 (setq path (file-relative-name path)))
9993 (save-match-data
9994 (if (string-match (concat "^" (regexp-quote
9995 (expand-file-name
9996 (file-name-as-directory
9997 default-directory))))
9998 (expand-file-name path))
9999 ;; We are linking a file with relative path name.
10000 (setq path (substring (expand-file-name path)
10001 (match-end 0)))
10002 (setq path (abbreviate-file-name (expand-file-name path)))))))
10003 (setq link (concat type path))
10004 (if (equal desc origpath)
10005 (setq desc path))))
10007 (if org-make-link-description-function
10008 (setq desc
10009 (or (condition-case nil
10010 (funcall org-make-link-description-function link desc)
10011 (error (progn (message "Can't get link description from `%s'"
10012 (symbol-name org-make-link-description-function))
10013 (sit-for 2) nil)))
10014 (read-string "Description: " default-description)))
10015 (if default-description (setq desc default-description)
10016 (setq desc (or (and auto-desc desc)
10017 (read-string "Description: " desc)))))
10019 (unless (string-match "\\S-" desc) (setq desc nil))
10020 (if remove (apply 'delete-region remove))
10021 (insert (org-make-link-string link desc))))
10023 (defun org-link-try-special-completion (type)
10024 "If there is completion support for link type TYPE, offer it."
10025 (let ((fun (intern (concat "org-" type "-complete-link"))))
10026 (if (functionp fun)
10027 (funcall fun)
10028 (read-string "Link (no completion support): " (concat type ":")))))
10030 (defun org-file-complete-link (&optional arg)
10031 "Create a file link using completion."
10032 (let (file link)
10033 (setq file (org-iread-file-name "File: "))
10034 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10035 (pwd1 (file-name-as-directory (abbreviate-file-name
10036 (expand-file-name ".")))))
10037 (cond
10038 ((equal arg '(16))
10039 (setq link (concat
10040 "file:"
10041 (abbreviate-file-name (expand-file-name file)))))
10042 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10043 (setq link (concat "file:" (match-string 1 file))))
10044 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10045 (expand-file-name file))
10046 (setq link (concat
10047 "file:" (match-string 1 (expand-file-name file)))))
10048 (t (setq link (concat "file:" file)))))
10049 link))
10051 (defun org-iread-file-name (&rest args)
10052 "Read-file-name using `ido-mode' speedup if available.
10053 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10054 See `read-file-name' for a description of parameters."
10055 (org-without-partial-completion
10056 (if (and org-completion-use-ido
10057 (fboundp 'ido-read-file-name)
10058 (boundp 'ido-mode) ido-mode
10059 (listp (second args)))
10060 (let ((ido-enter-matching-directory nil))
10061 (apply 'ido-read-file-name args))
10062 (apply 'read-file-name args))))
10064 (defun org-completing-read (&rest args)
10065 "Completing-read with SPACE being a normal character."
10066 (let ((enable-recursive-minibuffers t)
10067 (minibuffer-local-completion-map
10068 (copy-keymap minibuffer-local-completion-map)))
10069 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10070 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10071 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10072 (apply 'org-icompleting-read args)))
10074 (defun org-completing-read-no-i (&rest args)
10075 (let (org-completion-use-ido org-completion-use-iswitchb)
10076 (apply 'org-completing-read args)))
10078 (defun org-iswitchb-completing-read (prompt choices &rest args)
10079 "Use iswitch as a completing-read replacement to choose from choices.
10080 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10081 from."
10082 (let* ((iswitchb-use-virtual-buffers nil)
10083 (iswitchb-make-buflist-hook
10084 (lambda ()
10085 (setq iswitchb-temp-buflist choices))))
10086 (iswitchb-read-buffer prompt)))
10088 (defun org-icompleting-read (&rest args)
10089 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10090 (org-without-partial-completion
10091 (if (and org-completion-use-ido
10092 (fboundp 'ido-completing-read)
10093 (boundp 'ido-mode) ido-mode
10094 (listp (second args)))
10095 (let ((ido-enter-matching-directory nil))
10096 (apply 'ido-completing-read (concat (car args))
10097 (if (consp (car (nth 1 args)))
10098 (mapcar 'car (nth 1 args))
10099 (nth 1 args))
10100 (cddr args)))
10101 (if (and org-completion-use-iswitchb
10102 (boundp 'iswitchb-mode) iswitchb-mode
10103 (listp (second args)))
10104 (apply 'org-iswitchb-completing-read (concat (car args))
10105 (if (consp (car (nth 1 args)))
10106 (mapcar 'car (nth 1 args))
10107 (nth 1 args))
10108 (cddr args))
10109 (apply 'completing-read args)))))
10111 (defun org-extract-attributes (s)
10112 "Extract the attributes cookie from a string and set as text property."
10113 (let (a attr (start 0) key value)
10114 (save-match-data
10115 (when (string-match "{{\\([^}]+\\)}}$" s)
10116 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10117 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10118 (setq key (match-string 1 a) value (match-string 2 a)
10119 start (match-end 0)
10120 attr (plist-put attr (intern key) value))))
10121 (org-add-props s nil 'org-attr attr))
10124 ;;; Opening/following a link
10126 (defvar org-link-search-failed nil)
10128 (defvar org-open-link-functions nil
10129 "Hook for functions finding a plain text link.
10130 These functions must take a single argument, the link content.
10131 They will be called for links that look like [[link text][description]]
10132 when LINK TEXT does not have a protocol like \"http:\" and does not look
10133 like a filename (e.g. \"./blue.png\").
10135 These functions will be called *before* Org attempts to resolve the
10136 link by doing text searches in the current buffer - so if you want a
10137 link \"[[target]]\" to still find \"<<target>>\", your function should
10138 handle this as a special case.
10140 When the function does handle the link, it must return a non-nil value.
10141 If it decides that it is not responsible for this link, it must return
10142 nil to indicate that that Org-mode can continue with other options
10143 like exact and fuzzy text search.")
10145 (defun org-next-link (&optional search-backward)
10146 "Move forward to the next link.
10147 If the link is in hidden text, expose it."
10148 (interactive "P")
10149 (when (and org-link-search-failed (eq this-command last-command))
10150 (goto-char (point-min))
10151 (message "Link search wrapped back to beginning of buffer"))
10152 (setq org-link-search-failed nil)
10153 (let* ((pos (point))
10154 (ct (org-context))
10155 (a (assoc :link ct))
10156 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10157 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10158 ((looking-at org-any-link-re)
10159 ;; Don't stay stuck at link without an org-link face
10160 (forward-char (if search-backward -1 1))))
10161 (if (funcall srch-fun org-any-link-re nil t)
10162 (progn
10163 (goto-char (match-beginning 0))
10164 (if (outline-invisible-p) (org-show-context)))
10165 (goto-char pos)
10166 (setq org-link-search-failed t)
10167 (message "No further link found"))))
10169 (defun org-previous-link ()
10170 "Move backward to the previous link.
10171 If the link is in hidden text, expose it."
10172 (interactive)
10173 (funcall 'org-next-link t))
10175 (defun org-translate-link (s)
10176 "Translate a link string if a translation function has been defined."
10177 (if (and org-link-translation-function
10178 (fboundp org-link-translation-function)
10179 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10180 (progn
10181 (setq s (funcall org-link-translation-function
10182 (match-string 1 s) (match-string 2 s)))
10183 (concat (car s) ":" (cdr s)))
10186 (defun org-translate-link-from-planner (type path)
10187 "Translate a link from Emacs Planner syntax so that Org can follow it.
10188 This is still an experimental function, your mileage may vary."
10189 (cond
10190 ((member type '("http" "https" "news" "ftp"))
10191 ;; standard Internet links are the same.
10192 nil)
10193 ((and (equal type "irc") (string-match "^//" path))
10194 ;; Planner has two / at the beginning of an irc link, we have 1.
10195 ;; We should have zero, actually....
10196 (setq path (substring path 1)))
10197 ((and (equal type "lisp") (string-match "^/" path))
10198 ;; Planner has a slash, we do not.
10199 (setq type "elisp" path (substring path 1)))
10200 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10201 ;; A typical message link. Planner has the id after the final slash,
10202 ;; we separate it with a hash mark
10203 (setq path (concat (match-string 1 path) "#"
10204 (org-remove-angle-brackets (match-string 2 path)))))
10206 (cons type path))
10208 (defun org-find-file-at-mouse (ev)
10209 "Open file link or URL at mouse."
10210 (interactive "e")
10211 (mouse-set-point ev)
10212 (org-open-at-point 'in-emacs))
10214 (defun org-open-at-mouse (ev)
10215 "Open file link or URL at mouse.
10216 See the docstring of `org-open-file' for details."
10217 (interactive "e")
10218 (mouse-set-point ev)
10219 (if (eq major-mode 'org-agenda-mode)
10220 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10221 (org-open-at-point))
10223 (defvar org-window-config-before-follow-link nil
10224 "The window configuration before following a link.
10225 This is saved in case the need arises to restore it.")
10227 (defvar org-open-link-marker (make-marker)
10228 "Marker pointing to the location where `org-open-at-point; was called.")
10230 ;;;###autoload
10231 (defun org-open-at-point-global ()
10232 "Follow a link like Org-mode does.
10233 This command can be called in any mode to follow a link that has
10234 Org-mode syntax."
10235 (interactive)
10236 (org-run-like-in-org-mode 'org-open-at-point))
10238 ;;;###autoload
10239 (defun org-open-link-from-string (s &optional arg reference-buffer)
10240 "Open a link in the string S, as if it was in Org-mode."
10241 (interactive "sLink: \nP")
10242 (let ((reference-buffer (or reference-buffer (current-buffer))))
10243 (with-temp-buffer
10244 (let ((org-inhibit-startup (not reference-buffer)))
10245 (org-mode)
10246 (insert s)
10247 (goto-char (point-min))
10248 (when reference-buffer
10249 (setq org-link-abbrev-alist-local
10250 (with-current-buffer reference-buffer
10251 org-link-abbrev-alist-local)))
10252 (org-open-at-point arg reference-buffer)))))
10254 (defvar org-open-at-point-functions nil
10255 "Hook that is run when following a link at point.
10257 Functions in this hook must return t if they identify and follow
10258 a link at point. If they don't find anything interesting at point,
10259 they must return nil.")
10261 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10262 (defun org-open-at-point (&optional arg reference-buffer)
10263 "Open link at or after point.
10264 If there is no link at point, this function will search forward up to
10265 the end of the current line.
10266 Normally, files will be opened by an appropriate application. If the
10267 optional prefix argument ARG is non-nil, Emacs will visit the file.
10268 With a double prefix argument, try to open outside of Emacs, in the
10269 application the system uses for this file type."
10270 (interactive "P")
10271 ;; if in a code block, then open the block's results
10272 (unless (call-interactively #'org-babel-open-src-block-result)
10273 (org-load-modules-maybe)
10274 (move-marker org-open-link-marker (point))
10275 (setq org-window-config-before-follow-link (current-window-configuration))
10276 (org-remove-occur-highlights nil nil t)
10277 (cond
10278 ((and (org-at-heading-p)
10279 (not (org-at-timestamp-p t))
10280 (not (org-in-regexp
10281 (concat org-plain-link-re "\\|"
10282 org-bracket-link-regexp "\\|"
10283 org-angle-link-re "\\|"
10284 "[ \t]:[^ \t\n]+:[ \t]*$")))
10285 (not (get-text-property (point) 'org-linked-text)))
10286 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10287 (lk0 (car lkall))
10288 (lk (if (stringp lk0) (list lk0) lk0))
10289 (lkend (cdr lkall)))
10290 (mapcar (lambda(l)
10291 (search-forward l nil lkend)
10292 (goto-char (match-beginning 0))
10293 (org-open-at-point))
10294 lk))
10295 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10296 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10297 ((and (org-at-timestamp-p t)
10298 (not (org-in-regexp org-bracket-link-regexp)))
10299 (org-follow-timestamp-link))
10300 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10301 (not (org-in-regexp org-any-link-re)))
10302 (org-footnote-action))
10304 (let (type path link line search (pos (point)))
10305 (catch 'match
10306 (save-excursion
10307 (skip-chars-forward "^]\n\r")
10308 (when (org-in-regexp org-bracket-link-regexp 1)
10309 (setq link (org-extract-attributes
10310 (org-link-unescape (org-match-string-no-properties 1))))
10311 (while (string-match " *\n *" link)
10312 (setq link (replace-match " " t t link)))
10313 (setq link (org-link-expand-abbrev link))
10314 (cond
10315 ((or (file-name-absolute-p link)
10316 (string-match "^\\.\\.?/" link))
10317 (setq type "file" path link))
10318 ((string-match org-link-re-with-space3 link)
10319 (setq type (match-string 1 link) path (match-string 2 link)))
10320 ((string-match "^help:+\\(.+\\)" link)
10321 (setq type "help" path (match-string 1 link)))
10322 (t (setq type "thisfile" path link)))
10323 (throw 'match t)))
10325 (when (get-text-property (point) 'org-linked-text)
10326 (setq type "thisfile"
10327 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10328 (1+ (point)) (point))
10329 path (buffer-substring
10330 (or (previous-single-property-change pos 'org-linked-text)
10331 (point-min))
10332 (or (next-single-property-change pos 'org-linked-text)
10333 (point-max))))
10334 (throw 'match t))
10336 (save-excursion
10337 (when (or (org-in-regexp org-angle-link-re)
10338 (let ((match (org-in-regexp org-plain-link-re)))
10339 ;; Check a plain link is not within a bracket link
10340 (and match
10341 (save-excursion
10342 (progn
10343 (goto-char (car match))
10344 (not (org-in-regexp org-bracket-link-regexp))))))
10345 (let ((line_ending (save-excursion (end-of-line) (point))))
10346 ;; We are in a line before a plain or bracket link
10347 (or (re-search-forward org-plain-link-re line_ending t)
10348 (re-search-forward org-bracket-link-regexp line_ending t))))
10349 (setq type (match-string 1)
10350 path (org-link-unescape (match-string 2)))
10351 (throw 'match t)))
10352 (save-excursion
10353 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10354 (setq type "tags"
10355 path (match-string 1))
10356 (while (string-match ":" path)
10357 (setq path (replace-match "+" t t path)))
10358 (throw 'match t)))
10359 (when (org-in-regexp "<\\([^><\n]+\\)>")
10360 (setq type "tree-match"
10361 path (match-string 1))
10362 (throw 'match t)))
10363 (unless path
10364 (user-error "No link found"))
10366 ;; switch back to reference buffer
10367 ;; needed when if called in a temporary buffer through
10368 ;; org-open-link-from-string
10369 (with-current-buffer (or reference-buffer (current-buffer))
10371 ;; Remove any trailing spaces in path
10372 (if (string-match " +\\'" path)
10373 (setq path (replace-match "" t t path)))
10374 (if (and org-link-translation-function
10375 (fboundp org-link-translation-function))
10376 ;; Check if we need to translate the link
10377 (let ((tmp (funcall org-link-translation-function type path)))
10378 (setq type (car tmp) path (cdr tmp))))
10380 (cond
10382 ((assoc type org-link-protocols)
10383 (funcall (nth 1 (assoc type org-link-protocols)) path))
10385 ((equal type "help")
10386 (let ((f-or-v (intern path)))
10387 (cond ((fboundp f-or-v)
10388 (describe-function f-or-v))
10389 ((boundp f-or-v)
10390 (describe-variable f-or-v))
10391 (t (error "Not a known function or variable")))))
10393 ((equal type "mailto")
10394 (let ((cmd (car org-link-mailto-program))
10395 (args (cdr org-link-mailto-program)) args1
10396 (address path) (subject "") a)
10397 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10398 (setq address (match-string 1 path)
10399 subject (org-link-escape (match-string 2 path))))
10400 (while args
10401 (cond
10402 ((not (stringp (car args))) (push (pop args) args1))
10403 (t (setq a (pop args))
10404 (if (string-match "%a" a)
10405 (setq a (replace-match address t t a)))
10406 (if (string-match "%s" a)
10407 (setq a (replace-match subject t t a)))
10408 (push a args1))))
10409 (apply cmd (nreverse args1))))
10411 ((member type '("http" "https" "ftp" "news"))
10412 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10413 (org-link-escape
10414 path org-link-escape-chars-browser)
10415 path))))
10417 ((string= type "doi")
10418 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10419 (org-link-escape
10420 path org-link-escape-chars-browser)
10421 path))))
10423 ((member type '("message"))
10424 (browse-url (concat type ":" path)))
10426 ((string= type "tags")
10427 (org-tags-view arg path))
10429 ((string= type "tree-match")
10430 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10432 ((string= type "file")
10433 (if (string-match "::\\([0-9]+\\)\\'" path)
10434 (setq line (string-to-number (match-string 1 path))
10435 path (substring path 0 (match-beginning 0)))
10436 (if (string-match "::\\(.+\\)\\'" path)
10437 (setq search (match-string 1 path)
10438 path (substring path 0 (match-beginning 0)))))
10439 (if (string-match "[*?{]" (file-name-nondirectory path))
10440 (dired path)
10441 (org-open-file path arg line search)))
10443 ((string= type "shell")
10444 (let ((buf (generate-new-buffer "*Org Shell Output"))
10445 (cmd path))
10446 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10447 (string-match org-confirm-shell-link-not-regexp cmd))
10448 (not org-confirm-shell-link-function)
10449 (funcall org-confirm-shell-link-function
10450 (format "Execute \"%s\" in shell? "
10451 (org-add-props cmd nil
10452 'face 'org-warning))))
10453 (progn
10454 (message "Executing %s" cmd)
10455 (shell-command cmd buf)
10456 (if (featurep 'midnight)
10457 (setq clean-buffer-list-kill-buffer-names
10458 (cons buf clean-buffer-list-kill-buffer-names))))
10459 (error "Abort"))))
10461 ((string= type "elisp")
10462 (let ((cmd path))
10463 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10464 (string-match org-confirm-elisp-link-not-regexp cmd))
10465 (not org-confirm-elisp-link-function)
10466 (funcall org-confirm-elisp-link-function
10467 (format "Execute \"%s\" as elisp? "
10468 (org-add-props cmd nil
10469 'face 'org-warning))))
10470 (message "%s => %s" cmd
10471 (if (equal (string-to-char cmd) ?\()
10472 (eval (read cmd))
10473 (call-interactively (read cmd))))
10474 (error "Abort"))))
10476 ((and (string= type "thisfile")
10477 (run-hook-with-args-until-success
10478 'org-open-link-functions path)))
10480 ((string= type "thisfile")
10481 (if arg
10482 (switch-to-buffer-other-window
10483 (org-get-buffer-for-internal-link (current-buffer)))
10484 (org-mark-ring-push))
10485 (let ((cmd `(org-link-search
10486 ,path
10487 ,(cond ((equal arg '(4)) ''occur)
10488 ((equal arg '(16)) ''org-occur))
10489 ,pos)))
10490 (condition-case nil (let ((org-link-search-inhibit-query t))
10491 (eval cmd))
10492 (error (progn (widen) (eval cmd))))))
10494 (t (browse-url-at-point)))))))
10495 (move-marker org-open-link-marker nil)
10496 (run-hook-with-args 'org-follow-link-hook)))
10498 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10499 "Offer links in the current entry and return the selected link.
10500 If there is only one link, return it.
10501 If NTH is an integer, return the NTH link found.
10502 If ZERO is a string, check also this string for a link, and if
10503 there is one, return it."
10504 (with-current-buffer buffer
10505 (save-excursion
10506 (save-restriction
10507 (widen)
10508 (goto-char marker)
10509 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10510 "\\(" org-angle-link-re "\\)\\|"
10511 "\\(" org-plain-link-re "\\)"))
10512 (cnt ?0)
10513 (in-emacs (if (integerp nth) nil nth))
10514 have-zero end links link c)
10515 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10516 (push (match-string 0 zero) links)
10517 (setq cnt (1- cnt) have-zero t))
10518 (save-excursion
10519 (org-back-to-heading t)
10520 (setq end (save-excursion (outline-next-heading) (point)))
10521 (while (re-search-forward re end t)
10522 (push (match-string 0) links))
10523 (setq links (org-uniquify (reverse links))))
10524 (cond
10525 ((null links)
10526 (message "No links"))
10527 ((equal (length links) 1)
10528 (setq link (car links)))
10529 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10530 (setq link (nth (if have-zero nth (1- nth)) links)))
10531 (t ; we have to select a link
10532 (save-excursion
10533 (save-window-excursion
10534 (delete-other-windows)
10535 (with-output-to-temp-buffer "*Select Link*"
10536 (mapc (lambda (l)
10537 (if (not (string-match org-bracket-link-regexp l))
10538 (princ (format "[%c] %s\n" (incf cnt)
10539 (org-remove-angle-brackets l)))
10540 (if (match-end 3)
10541 (princ (format "[%c] %s (%s)\n" (incf cnt)
10542 (match-string 3 l) (match-string 1 l)))
10543 (princ (format "[%c] %s\n" (incf cnt)
10544 (match-string 1 l))))))
10545 links))
10546 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10547 (message "Select link to open, RET to open all:")
10548 (setq c (read-char-exclusive))
10549 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10550 (when (equal c ?q) (error "Abort"))
10551 (if (equal c ?\C-m)
10552 (setq link links)
10553 (setq nth (- c ?0))
10554 (if have-zero (setq nth (1+ nth)))
10555 (unless (and (integerp nth) (>= (length links) nth))
10556 (error "Invalid link selection"))
10557 (setq link (nth (1- nth) links)))))
10558 (cons link end))))))
10560 ;; Add special file links that specify the way of opening
10562 (org-add-link-type "file+sys" 'org-open-file-with-system)
10563 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10564 (defun org-open-file-with-system (path)
10565 "Open file at PATH using the system way of opening it."
10566 (org-open-file path 'system))
10567 (defun org-open-file-with-emacs (path)
10568 "Open file at PATH in Emacs."
10569 (org-open-file path 'emacs))
10572 ;;; File search
10574 (defvar org-create-file-search-functions nil
10575 "List of functions to construct the right search string for a file link.
10576 These functions are called in turn with point at the location to
10577 which the link should point.
10579 A function in the hook should first test if it would like to
10580 handle this file type, for example by checking the `major-mode'
10581 or the file extension. If it decides not to handle this file, it
10582 should just return nil to give other functions a chance. If it
10583 does handle the file, it must return the search string to be used
10584 when following the link. The search string will be part of the
10585 file link, given after a double colon, and `org-open-at-point'
10586 will automatically search for it. If special measures must be
10587 taken to make the search successful, another function should be
10588 added to the companion hook `org-execute-file-search-functions',
10589 which see.
10591 A function in this hook may also use `setq' to set the variable
10592 `description' to provide a suggestion for the descriptive text to
10593 be used for this link when it gets inserted into an Org-mode
10594 buffer with \\[org-insert-link].")
10596 (defvar org-execute-file-search-functions nil
10597 "List of functions to execute a file search triggered by a link.
10599 Functions added to this hook must accept a single argument, the
10600 search string that was part of the file link, the part after the
10601 double colon. The function must first check if it would like to
10602 handle this search, for example by checking the `major-mode' or
10603 the file extension. If it decides not to handle this search, it
10604 should just return nil to give other functions a chance. If it
10605 does handle the search, it must return a non-nil value to keep
10606 other functions from trying.
10608 Each function can access the current prefix argument through the
10609 variable `current-prefix-arg'. Note that a single prefix is used
10610 to force opening a link in Emacs, so it may be good to only use a
10611 numeric or double prefix to guide the search function.
10613 In case this is needed, a function in this hook can also restore
10614 the window configuration before `org-open-at-point' was called using:
10616 (set-window-configuration org-window-config-before-follow-link)")
10618 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10619 (defun org-link-search (s &optional type avoid-pos stealth)
10620 "Search for a link search option.
10621 If S is surrounded by forward slashes, it is interpreted as a
10622 regular expression. In org-mode files, this will create an `org-occur'
10623 sparse tree. In ordinary files, `occur' will be used to list matches.
10624 If the current buffer is in `dired-mode', grep will be used to search
10625 in all files. If AVOID-POS is given, ignore matches near that position.
10627 When optional argument STEALTH is non-nil, do not modify
10628 visibility around point, thus ignoring
10629 `org-show-hierarchy-above', `org-show-following-heading' and
10630 `org-show-siblings' variables."
10631 (let ((case-fold-search t)
10632 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10633 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10634 (append '(("") (" ") ("\t") ("\n"))
10635 org-emphasis-alist)
10636 "\\|") "\\)"))
10637 (pos (point))
10638 (pre nil) (post nil)
10639 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10640 (cond
10641 ;; First check if there are any special search functions
10642 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10643 ;; Now try the builtin stuff
10644 ((and (equal (string-to-char s0) ?#)
10645 (> (length s0) 1)
10646 (save-excursion
10647 (goto-char (point-min))
10648 (and
10649 (re-search-forward
10650 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10651 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10652 (setq type 'dedicated
10653 pos (match-beginning 0))))
10654 ;; There is an exact target for this
10655 (goto-char pos)
10656 (org-back-to-heading t)))
10657 ((save-excursion
10658 (goto-char (point-min))
10659 (and
10660 (re-search-forward
10661 (concat "<<" (regexp-quote s0) ">>") nil t)
10662 (setq type 'dedicated
10663 pos (match-beginning 0))))
10664 ;; There is an exact target for this
10665 (goto-char pos))
10666 ((save-excursion
10667 (goto-char (point-min))
10668 (and
10669 (re-search-forward
10670 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10671 (setq type 'dedicated pos (match-beginning 0))))
10672 ;; Found an element with a matching #+name affiliated keyword.
10673 (goto-char pos))
10674 ((and (string-match "^(\\(.*\\))$" s0)
10675 (save-excursion
10676 (goto-char (point-min))
10677 (and
10678 (re-search-forward
10679 (concat "[^[]" (regexp-quote
10680 (format org-coderef-label-format
10681 (match-string 1 s0))))
10682 nil t)
10683 (setq type 'dedicated
10684 pos (1+ (match-beginning 0))))))
10685 ;; There is a coderef target for this
10686 (goto-char pos))
10687 ((string-match "^/\\(.*\\)/$" s)
10688 ;; A regular expression
10689 (cond
10690 ((derived-mode-p 'org-mode)
10691 (org-occur (match-string 1 s)))
10692 (t (org-do-occur (match-string 1 s)))))
10693 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10694 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10695 (goto-char (point-min))
10696 (cond
10697 ((let (case-fold-search)
10698 (re-search-forward (format org-complex-heading-regexp-format
10699 (regexp-quote s))
10700 nil t))
10701 ;; OK, found a match
10702 (setq type 'dedicated)
10703 (goto-char (match-beginning 0)))
10704 ((and (not org-link-search-inhibit-query)
10705 (eq org-link-search-must-match-exact-headline 'query-to-create)
10706 (y-or-n-p "No match - create this as a new heading? "))
10707 (goto-char (point-max))
10708 (or (bolp) (newline))
10709 (insert "* " s "\n")
10710 (beginning-of-line 0))
10712 (goto-char pos)
10713 (error "No match"))))
10715 ;; A normal search string
10716 (when (equal (string-to-char s) ?*)
10717 ;; Anchor on headlines, post may include tags.
10718 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10719 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10720 s (substring s 1)))
10721 (remove-text-properties
10722 0 (length s)
10723 '(face nil mouse-face nil keymap nil fontified nil) s)
10724 ;; Make a series of regular expressions to find a match
10725 (setq words (org-split-string s "[ \n\r\t]+")
10727 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10728 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10729 "\\)" markers)
10730 re2a_ (concat "\\(" (mapconcat 'downcase words
10731 "[ \t\r\n]+") "\\)[ \t\r\n]")
10732 re2a (concat "[ \t\r\n]" re2a_)
10733 re4_ (concat "\\(" (mapconcat 'downcase words
10734 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10735 re4 (concat "[^a-zA-Z_]" re4_)
10737 re1 (concat pre re2 post)
10738 re3 (concat pre (if pre re4_ re4) post)
10739 re5 (concat pre ".*" re4)
10740 re2 (concat pre re2)
10741 re2a (concat pre (if pre re2a_ re2a))
10742 re4 (concat pre (if pre re4_ re4))
10743 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10744 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10745 re5 "\\)"
10747 (cond
10748 ((eq type 'org-occur) (org-occur reall))
10749 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10750 (t (goto-char (point-min))
10751 (setq type 'fuzzy)
10752 (if (or (and (org-search-not-self 1 re0 nil t)
10753 (setq type 'dedicated))
10754 (org-search-not-self 1 re1 nil t)
10755 (org-search-not-self 1 re2 nil t)
10756 (org-search-not-self 1 re2a nil t)
10757 (org-search-not-self 1 re3 nil t)
10758 (org-search-not-self 1 re4 nil t)
10759 (org-search-not-self 1 re5 nil t))
10760 (goto-char (match-beginning 1))
10761 (goto-char pos)
10762 (error "No match"))))))
10763 (and (derived-mode-p 'org-mode)
10764 (not stealth)
10765 (org-show-context 'link-search))
10766 type))
10768 (defun org-search-not-self (group &rest args)
10769 "Execute `re-search-forward', but only accept matches that do not
10770 enclose the position of `org-open-link-marker'."
10771 (let ((m org-open-link-marker))
10772 (catch 'exit
10773 (while (apply 're-search-forward args)
10774 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10775 (goto-char (match-end group))
10776 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10777 (> (match-beginning 0) (marker-position m))
10778 (< (match-end 0) (marker-position m)))
10779 (save-match-data
10780 (or (not (org-in-regexp
10781 org-bracket-link-analytic-regexp 1))
10782 (not (match-end 4)) ; no description
10783 (and (<= (match-beginning 4) (point))
10784 (>= (match-end 4) (point))))))
10785 (throw 'exit (point))))))))
10787 (defun org-get-buffer-for-internal-link (buffer)
10788 "Return a buffer to be used for displaying the link target of internal links."
10789 (cond
10790 ((not org-display-internal-link-with-indirect-buffer)
10791 buffer)
10792 ((string-match "(Clone)$" (buffer-name buffer))
10793 (message "Buffer is already a clone, not making another one")
10794 ;; we also do not modify visibility in this case
10795 buffer)
10796 (t ; make a new indirect buffer for displaying the link
10797 (let* ((bn (buffer-name buffer))
10798 (ibn (concat bn "(Clone)"))
10799 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10800 (with-current-buffer ib (org-overview))
10801 ib))))
10803 (defun org-do-occur (regexp &optional cleanup)
10804 "Call the Emacs command `occur'.
10805 If CLEANUP is non-nil, remove the printout of the regular expression
10806 in the *Occur* buffer. This is useful if the regex is long and not useful
10807 to read."
10808 (occur regexp)
10809 (when cleanup
10810 (let ((cwin (selected-window)) win beg end)
10811 (when (setq win (get-buffer-window "*Occur*"))
10812 (select-window win))
10813 (goto-char (point-min))
10814 (when (re-search-forward "match[a-z]+" nil t)
10815 (setq beg (match-end 0))
10816 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10817 (setq end (1- (match-beginning 0)))))
10818 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10819 (goto-char (point-min))
10820 (select-window cwin))))
10822 ;;; The mark ring for links jumps
10824 (defvar org-mark-ring nil
10825 "Mark ring for positions before jumps in Org-mode.")
10826 (defvar org-mark-ring-last-goto nil
10827 "Last position in the mark ring used to go back.")
10828 ;; Fill and close the ring
10829 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10830 (loop for i from 1 to org-mark-ring-length do
10831 (push (make-marker) org-mark-ring))
10832 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10833 org-mark-ring)
10835 (defun org-mark-ring-push (&optional pos buffer)
10836 "Put the current position or POS into the mark ring and rotate it."
10837 (interactive)
10838 (setq pos (or pos (point)))
10839 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10840 (move-marker (car org-mark-ring)
10841 (or pos (point))
10842 (or buffer (current-buffer)))
10843 (message "%s"
10844 (substitute-command-keys
10845 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10847 (defun org-mark-ring-goto (&optional n)
10848 "Jump to the previous position in the mark ring.
10849 With prefix arg N, jump back that many stored positions. When
10850 called several times in succession, walk through the entire ring.
10851 Org-mode commands jumping to a different position in the current file,
10852 or to another Org-mode file, automatically push the old position
10853 onto the ring."
10854 (interactive "p")
10855 (let (p m)
10856 (if (eq last-command this-command)
10857 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10858 (setq p org-mark-ring))
10859 (setq org-mark-ring-last-goto p)
10860 (setq m (car p))
10861 (org-pop-to-buffer-same-window (marker-buffer m))
10862 (goto-char m)
10863 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10865 (defun org-remove-angle-brackets (s)
10866 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10867 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10869 (defun org-add-angle-brackets (s)
10870 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10871 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10873 (defun org-remove-double-quotes (s)
10874 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10875 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10878 ;;; Following specific links
10880 (defun org-follow-timestamp-link ()
10881 "Open an agenda view for the time-stamp date/range at point."
10882 (cond
10883 ((org-at-date-range-p t)
10884 (let ((org-agenda-start-on-weekday)
10885 (t1 (match-string 1))
10886 (t2 (match-string 2)) tt1 tt2)
10887 (setq tt1 (time-to-days (org-time-string-to-time t1))
10888 tt2 (time-to-days (org-time-string-to-time t2)))
10889 (let ((org-agenda-buffer-tmp-name
10890 (format "*Org Agenda(a:%s)"
10891 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10892 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10893 ((org-at-timestamp-p t)
10894 (let ((org-agenda-buffer-tmp-name
10895 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10896 (org-agenda-list nil (time-to-days (org-time-string-to-time
10897 (substring (match-string 1) 0 10)))
10898 1)))
10899 (t (error "This should not happen"))))
10902 ;;; Following file links
10903 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10904 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10905 (declare-function mailcap-mime-info
10906 "mailcap" (string &optional request no-decode))
10907 (defvar org-wait nil)
10908 (defun org-open-file (path &optional in-emacs line search)
10909 "Open the file at PATH.
10910 First, this expands any special file name abbreviations. Then the
10911 configuration variable `org-file-apps' is checked if it contains an
10912 entry for this file type, and if yes, the corresponding command is launched.
10914 If no application is found, Emacs simply visits the file.
10916 With optional prefix argument IN-EMACS, Emacs will visit the file.
10917 With a double \\[universal-argument] \\[universal-argument] \
10918 prefix arg, Org tries to avoid opening in Emacs
10919 and to use an external application to visit the file.
10921 Optional LINE specifies a line to go to, optional SEARCH a string
10922 to search for. If LINE or SEARCH is given, the file will be
10923 opened in Emacs, unless an entry from org-file-apps that makes
10924 use of groups in a regexp matches.
10926 If you want to change the way frames are used when following a
10927 link, please customize `org-link-frame-setup'.
10929 If the file does not exist, an error is thrown."
10930 (let* ((file (if (equal path "")
10931 buffer-file-name
10932 (substitute-in-file-name (expand-file-name path))))
10933 (file-apps (append org-file-apps (org-default-apps)))
10934 (apps (org-remove-if
10935 'org-file-apps-entry-match-against-dlink-p file-apps))
10936 (apps-dlink (org-remove-if-not
10937 'org-file-apps-entry-match-against-dlink-p file-apps))
10938 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10939 (dirp (if remp nil (file-directory-p file)))
10940 (file (if (and dirp org-open-directory-means-index-dot-org)
10941 (concat (file-name-as-directory file) "index.org")
10942 file))
10943 (a-m-a-p (assq 'auto-mode apps))
10944 (dfile (downcase file))
10945 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10946 (link (cond ((and (eq line nil)
10947 (eq search nil))
10948 file)
10949 (line
10950 (concat file "::" (number-to-string line)))
10951 (search
10952 (concat file "::" search))))
10953 (dlink (downcase link))
10954 (old-buffer (current-buffer))
10955 (old-pos (point))
10956 (old-mode major-mode)
10957 ext cmd link-match-data)
10958 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10959 (setq ext (match-string 1 dfile))
10960 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10961 (setq ext (match-string 1 dfile))))
10962 (cond
10963 ((member in-emacs '((16) system))
10964 (setq cmd (cdr (assoc 'system apps))))
10965 (in-emacs (setq cmd 'emacs))
10967 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10968 (and dirp (cdr (assoc 'directory apps)))
10969 ; first, try matching against apps-dlink
10970 ; if we get a match here, store the match data for later
10971 (let ((match (assoc-default dlink apps-dlink
10972 'string-match)))
10973 (if match
10974 (progn (setq link-match-data (match-data))
10975 match)
10976 (progn (setq in-emacs (or in-emacs line search))
10977 nil))) ; if we have no match in apps-dlink,
10978 ; always open the file in emacs if line or search
10979 ; is given (for backwards compatibility)
10980 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10981 'string-match)
10982 (cdr (assoc ext apps))
10983 (cdr (assoc t apps))))))
10984 (when (eq cmd 'system)
10985 (setq cmd (cdr (assoc 'system apps))))
10986 (when (eq cmd 'default)
10987 (setq cmd (cdr (assoc t apps))))
10988 (when (eq cmd 'mailcap)
10989 (require 'mailcap)
10990 (mailcap-parse-mailcaps)
10991 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10992 (command (mailcap-mime-info mime-type)))
10993 (if (stringp command)
10994 (setq cmd command)
10995 (setq cmd 'emacs))))
10996 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10997 (not (file-exists-p file))
10998 (not org-open-non-existing-files))
10999 (error "No such file: %s" file))
11000 (cond
11001 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11002 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11003 (while (string-match "['\"]%s['\"]" cmd)
11004 (setq cmd (replace-match "%s" t t cmd)))
11005 (while (string-match "%s" cmd)
11006 (setq cmd (replace-match
11007 (save-match-data
11008 (shell-quote-argument
11009 (convert-standard-filename file)))
11010 t t cmd)))
11012 ;; Replace "%1", "%2" etc. in command with group matches from regex
11013 (save-match-data
11014 (let ((match-index 1)
11015 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11016 (set-match-data link-match-data)
11017 (while (<= match-index number-of-groups)
11018 (let ((regex (concat "%" (number-to-string match-index)))
11019 (replace-with (match-string match-index dlink)))
11020 (while (string-match regex cmd)
11021 (setq cmd (replace-match replace-with t t cmd))))
11022 (setq match-index (+ match-index 1)))))
11024 (save-window-excursion
11025 (message "Running %s...done" cmd)
11026 (start-process-shell-command cmd nil cmd)
11027 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11028 ((or (stringp cmd)
11029 (eq cmd 'emacs))
11030 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11031 (widen)
11032 (if line (org-goto-line line)
11033 (if search (org-link-search search))))
11034 ((consp cmd)
11035 (let ((file (convert-standard-filename file)))
11036 (save-match-data
11037 (set-match-data link-match-data)
11038 (eval cmd))))
11039 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11040 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11041 (or (not (equal old-buffer (current-buffer)))
11042 (not (equal old-pos (point))))
11043 (org-mark-ring-push old-pos old-buffer))))
11045 (defun org-file-apps-entry-match-against-dlink-p (entry)
11046 "This function returns non-nil if `entry' uses a regular
11047 expression which should be matched against the whole link by
11048 org-open-file.
11050 It assumes that is the case when the entry uses a regular
11051 expression which has at least one grouping construct and the
11052 action is either a lisp form or a command string containing
11053 '%1', i.e. using at least one subexpression match as a
11054 parameter."
11055 (let ((selector (car entry))
11056 (action (cdr entry)))
11057 (if (stringp selector)
11058 (and (> (regexp-opt-depth selector) 0)
11059 (or (and (stringp action)
11060 (string-match "%[0-9]" action))
11061 (consp action)))
11062 nil)))
11064 (defun org-default-apps ()
11065 "Return the default applications for this operating system."
11066 (cond
11067 ((eq system-type 'darwin)
11068 org-file-apps-defaults-macosx)
11069 ((eq system-type 'windows-nt)
11070 org-file-apps-defaults-windowsnt)
11071 (t org-file-apps-defaults-gnu)))
11073 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11074 "Convert extensions to regular expressions in the cars of LIST.
11075 Also, weed out any non-string entries, because the return value is used
11076 only for regexp matching.
11077 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11078 point to the symbol `emacs', indicating that the file should
11079 be opened in Emacs."
11080 (append
11081 (delq nil
11082 (mapcar (lambda (x)
11083 (if (not (stringp (car x)))
11085 (if (string-match "\\W" (car x))
11087 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11088 list))
11089 (if add-auto-mode
11090 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11092 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11093 (defun org-file-remote-p (file)
11094 "Test whether FILE specifies a location on a remote system.
11095 Return non-nil if the location is indeed remote.
11097 For example, the filename \"/user@host:/foo\" specifies a location
11098 on the system \"/user@host:\"."
11099 (cond ((fboundp 'file-remote-p)
11100 (file-remote-p file))
11101 ((fboundp 'tramp-handle-file-remote-p)
11102 (tramp-handle-file-remote-p file))
11103 ((and (boundp 'ange-ftp-name-format)
11104 (string-match (car ange-ftp-name-format) file))
11105 t)))
11108 ;;;; Refiling
11110 (defun org-get-org-file ()
11111 "Read a filename, with default directory `org-directory'."
11112 (let ((default (or org-default-notes-file remember-data-file)))
11113 (read-file-name (format "File name [%s]: " default)
11114 (file-name-as-directory org-directory)
11115 default)))
11117 (defun org-notes-order-reversed-p ()
11118 "Check if the current file should receive notes in reversed order."
11119 (cond
11120 ((not org-reverse-note-order) nil)
11121 ((eq t org-reverse-note-order) t)
11122 ((not (listp org-reverse-note-order)) nil)
11123 (t (catch 'exit
11124 (let ((all org-reverse-note-order)
11125 entry)
11126 (while (setq entry (pop all))
11127 (if (string-match (car entry) buffer-file-name)
11128 (throw 'exit (cdr entry))))
11129 nil)))))
11131 (defvar org-refile-target-table nil
11132 "The list of refile targets, created by `org-refile'.")
11134 (defvar org-agenda-new-buffers nil
11135 "Buffers created to visit agenda files.")
11137 (defvar org-refile-cache nil
11138 "Cache for refile targets.")
11140 (defvar org-refile-markers nil
11141 "All the markers used for caching refile locations.")
11143 (defun org-refile-marker (pos)
11144 "Get a new refile marker, but only if caching is in use."
11145 (if (not org-refile-use-cache)
11147 (let ((m (make-marker)))
11148 (move-marker m pos)
11149 (push m org-refile-markers)
11150 m)))
11152 (defun org-refile-cache-clear ()
11153 "Clear the refile cache and disable all the markers."
11154 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11155 (setq org-refile-markers nil)
11156 (setq org-refile-cache nil)
11157 (message "Refile cache has been cleared"))
11159 (defun org-refile-cache-check-set (set)
11160 "Check if all the markers in the cache still have live buffers."
11161 (let (marker)
11162 (catch 'exit
11163 (while (and set (setq marker (nth 3 (pop set))))
11164 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11165 (when (and marker (null (marker-buffer marker)))
11166 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11167 (sit-for 3)
11168 (throw 'exit nil)))
11169 t)))
11171 (defun org-refile-cache-put (set &rest identifiers)
11172 "Push the refile targets SET into the cache, under IDENTIFIERS."
11173 (let* ((key (sha1 (prin1-to-string identifiers)))
11174 (entry (assoc key org-refile-cache)))
11175 (if entry
11176 (setcdr entry set)
11177 (push (cons key set) org-refile-cache))))
11179 (defun org-refile-cache-get (&rest identifiers)
11180 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11181 (cond
11182 ((not org-refile-cache) nil)
11183 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11185 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11186 org-refile-cache))))
11187 (and set (org-refile-cache-check-set set) set)))))
11189 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11190 "Produce a table with refile targets."
11191 (let ((case-fold-search nil)
11192 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11193 (entries (or org-refile-targets '((nil . (:level . 1)))))
11194 targets tgs txt re files f desc descre fast-path-p level pos0)
11195 (message "Getting targets...")
11196 (with-current-buffer (or default-buffer (current-buffer))
11197 (while (setq entry (pop entries))
11198 (setq files (car entry) desc (cdr entry))
11199 (setq fast-path-p nil)
11200 (cond
11201 ((null files) (setq files (list (current-buffer))))
11202 ((eq files 'org-agenda-files)
11203 (setq files (org-agenda-files 'unrestricted)))
11204 ((and (symbolp files) (fboundp files))
11205 (setq files (funcall files)))
11206 ((and (symbolp files) (boundp files))
11207 (setq files (symbol-value files))))
11208 (if (stringp files) (setq files (list files)))
11209 (cond
11210 ((eq (car desc) :tag)
11211 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11212 ((eq (car desc) :todo)
11213 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11214 ((eq (car desc) :regexp)
11215 (setq descre (cdr desc)))
11216 ((eq (car desc) :level)
11217 (setq descre (concat "^\\*\\{" (number-to-string
11218 (if org-odd-levels-only
11219 (1- (* 2 (cdr desc)))
11220 (cdr desc)))
11221 "\\}[ \t]")))
11222 ((eq (car desc) :maxlevel)
11223 (setq fast-path-p t)
11224 (setq descre (concat "^\\*\\{1," (number-to-string
11225 (if org-odd-levels-only
11226 (1- (* 2 (cdr desc)))
11227 (cdr desc)))
11228 "\\}[ \t]")))
11229 (t (error "Bad refiling target description %s" desc)))
11230 (while (setq f (pop files))
11231 (with-current-buffer
11232 (if (bufferp f) f (org-get-agenda-file-buffer f))
11234 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11235 (progn
11236 (if (bufferp f) (setq f (buffer-file-name
11237 (buffer-base-buffer f))))
11238 (setq f (and f (expand-file-name f)))
11239 (if (eq org-refile-use-outline-path 'file)
11240 (push (list (file-name-nondirectory f) f nil nil) tgs))
11241 (save-excursion
11242 (save-restriction
11243 (widen)
11244 (goto-char (point-min))
11245 (while (re-search-forward descre nil t)
11246 (goto-char (setq pos0 (point-at-bol)))
11247 (catch 'next
11248 (when org-refile-target-verify-function
11249 (save-match-data
11250 (or (funcall org-refile-target-verify-function)
11251 (throw 'next t))))
11252 (when (and (looking-at org-complex-heading-regexp)
11253 (not (member (match-string 4) excluded-entries))
11254 (match-string 4))
11255 (setq level (org-reduced-level
11256 (- (match-end 1) (match-beginning 1)))
11257 txt (org-link-display-format (match-string 4))
11258 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11259 re (format org-complex-heading-regexp-format
11260 (regexp-quote (match-string 4))))
11261 (when org-refile-use-outline-path
11262 (setq txt (mapconcat
11263 'org-protect-slash
11264 (append
11265 (if (eq org-refile-use-outline-path
11266 'file)
11267 (list (file-name-nondirectory
11268 (buffer-file-name
11269 (buffer-base-buffer))))
11270 (if (eq org-refile-use-outline-path
11271 'full-file-path)
11272 (list (buffer-file-name
11273 (buffer-base-buffer)))))
11274 (org-get-outline-path fast-path-p
11275 level txt)
11276 (list txt))
11277 "/")))
11278 (push (list txt f re (org-refile-marker (point)))
11279 tgs)))
11280 (when (= (point) pos0)
11281 ;; verification function has not moved point
11282 (goto-char (point-at-eol))))))))
11283 (when org-refile-use-cache
11284 (org-refile-cache-put tgs (buffer-file-name) descre))
11285 (setq targets (append tgs targets))
11286 ))))
11287 (message "Getting targets...done")
11288 (nreverse targets)))
11290 (defun org-protect-slash (s)
11291 (while (string-match "/" s)
11292 (setq s (replace-match "\\" t t s)))
11295 (defvar org-olpa (make-vector 20 nil))
11297 (defun org-get-outline-path (&optional fastp level heading)
11298 "Return the outline path to the current entry, as a list.
11300 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11301 routine which makes outline path derivations for an entire file,
11302 avoiding backtracing. Refile target collection makes use of that."
11303 (if fastp
11304 (progn
11305 (if (> level 19)
11306 (error "Outline path failure, more than 19 levels"))
11307 (loop for i from level upto 19 do
11308 (aset org-olpa i nil))
11309 (prog1
11310 (delq nil (append org-olpa nil))
11311 (aset org-olpa level heading)))
11312 (let (rtn case-fold-search)
11313 (save-excursion
11314 (save-restriction
11315 (widen)
11316 (while (org-up-heading-safe)
11317 (when (looking-at org-complex-heading-regexp)
11318 (push (org-match-string-no-properties 4) rtn)))
11319 rtn)))))
11321 (defun org-format-outline-path (path &optional width prefix separator)
11322 "Format the outline path PATH for display.
11323 WIDTH is the maximum number of characters that is available.
11324 PREFIX is a prefix to be included in the returned string,
11325 such as the file name.
11326 SEPARATOR is inserted between the different parts of the path,
11327 the default is \"/\"."
11328 (setq width (or width 79))
11329 (if prefix (setq width (- width (length prefix))))
11330 (if (not path)
11331 (or prefix "")
11332 (let* ((nsteps (length path))
11333 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11334 (maxwidth (if (<= total-width width)
11335 10000 ;; everything fits
11336 ;; we need to shorten the level headings
11337 (/ (- width nsteps) nsteps)))
11338 (org-odd-levels-only nil)
11339 (n 0)
11340 (total (1+ (length prefix))))
11341 (setq maxwidth (max maxwidth 10))
11342 (concat prefix
11343 (if prefix (or separator "/"))
11344 (mapconcat
11345 (lambda (h)
11346 (setq n (1+ n))
11347 (if (and (= n nsteps) (< maxwidth 10000))
11348 (setq maxwidth (- total-width total)))
11349 (if (< (length h) maxwidth)
11350 (progn (setq total (+ total (length h) 1)) h)
11351 (setq h (substring h 0 (- maxwidth 2))
11352 total (+ total maxwidth 1))
11353 (if (string-match "[ \t]+\\'" h)
11354 (setq h (substring h 0 (match-beginning 0))))
11355 (setq h (concat h "..")))
11356 (org-add-props h nil 'face
11357 (nth (% (1- n) org-n-level-faces)
11358 org-level-faces))
11360 path (or separator "/"))))))
11362 (defun org-display-outline-path (&optional file current separator just-return-string)
11363 "Display the current outline path in the echo area.
11365 If FILE is non-nil, prepend the output with the file name.
11366 If CURRENT is non-nil, append the current heading to the output.
11367 SEPARATOR is passed through to `org-format-outline-path'. It separates
11368 the different parts of the path and defaults to \"/\".
11369 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11370 (interactive "P")
11371 (let* (case-fold-search
11372 message-log-max ; Don't populate the *Messages* buffer
11373 (bfn (buffer-file-name (buffer-base-buffer)))
11374 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11375 res)
11376 (if current (setq path (append path
11377 (save-excursion
11378 (org-back-to-heading t)
11379 (if (looking-at org-complex-heading-regexp)
11380 (list (match-string 4)))))))
11381 (setq res
11382 (org-format-outline-path
11383 path
11384 (1- (frame-width))
11385 (and file bfn (concat (file-name-nondirectory bfn) separator))
11386 separator))
11387 (if just-return-string
11388 (org-no-properties res)
11389 (message "%s" res))))
11391 (defvar org-refile-history nil
11392 "History for refiling operations.")
11394 (defvar org-after-refile-insert-hook nil
11395 "Hook run after `org-refile' has inserted its stuff at the new location.
11396 Note that this is still *before* the stuff will be removed from
11397 the *old* location.")
11399 (defvar org-capture-last-stored-marker)
11400 (defvar org-refile-keep nil
11401 "Non-nil means `org-refile' will copy instead of refile.")
11403 (defun org-copy ()
11404 "Like `org-refile', but copy."
11405 (interactive)
11406 (let ((org-refile-keep t))
11407 (funcall 'org-refile nil nil nil "Copy")))
11409 (defun org-refile (&optional goto default-buffer rfloc msg)
11410 "Move the entry or entries at point to another heading.
11411 The list of target headings is compiled using the information in
11412 `org-refile-targets', which see.
11414 At the target location, the entry is filed as a subitem of the target
11415 heading. Depending on `org-reverse-note-order', the new subitem will
11416 either be the first or the last subitem.
11418 If there is an active region, all entries in that region will be moved.
11419 However, the region must fulfill the requirement that the first heading
11420 is the first one sets the top-level of the moved text - at most siblings
11421 below it are allowed.
11423 With prefix arg GOTO, the command will only visit the target location
11424 and not actually move anything.
11426 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11427 go to the location where the last refiling operation has put the subtree.
11428 With a prefix argument of `2', refile to the running clock.
11430 RFLOC can be a refile location obtained in a different way.
11432 MSG is a string to replace \"Refile\" in the default prompt with
11433 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11435 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11437 If you are using target caching (see `org-refile-use-cache'),
11438 you have to clear the target cache in order to find new targets.
11439 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11440 prefix argument (`C-u C-u C-u C-c C-w')."
11442 (interactive "P")
11443 (if (member goto '(0 (64)))
11444 (org-refile-cache-clear)
11445 (let* ((actionmsg (or msg "Refile"))
11446 (cbuf (current-buffer))
11447 (regionp (org-region-active-p))
11448 (region-start (and regionp (region-beginning)))
11449 (region-end (and regionp (region-end)))
11450 (region-length (and regionp (- region-end region-start)))
11451 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11452 pos it nbuf file re level reversed)
11453 (setq last-command nil)
11454 (when regionp
11455 (goto-char region-start)
11456 (or (bolp) (goto-char (point-at-bol)))
11457 (setq region-start (point))
11458 (unless (or (org-kill-is-subtree-p
11459 (buffer-substring region-start region-end))
11460 (prog1 org-refile-active-region-within-subtree
11461 (org-toggle-heading)))
11462 (error "The region is not a (sequence of) subtree(s)")))
11463 (if (equal goto '(16))
11464 (org-refile-goto-last-stored)
11465 (when (or
11466 (and (equal goto 2)
11467 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11468 (prog1
11469 (setq it (list (or org-clock-heading "running clock")
11470 (buffer-file-name
11471 (marker-buffer org-clock-hd-marker))
11473 (marker-position org-clock-hd-marker)))
11474 (setq goto nil)))
11475 (setq it (or rfloc
11476 (let (heading-text)
11477 (save-excursion
11478 (unless goto
11479 (org-back-to-heading t)
11480 (setq heading-text
11481 (nth 4 (org-heading-components))))
11483 (org-refile-get-location
11484 (cond (goto "Goto")
11485 (regionp (concat actionmsg " region to"))
11486 (t (concat actionmsg " subtree \""
11487 heading-text "\" to")))
11488 default-buffer
11489 (and (not (equal '(4) goto))
11490 org-refile-allow-creating-parent-nodes)
11491 goto))))))
11492 (setq file (nth 1 it)
11493 re (nth 2 it)
11494 pos (nth 3 it))
11495 (if (and (not goto)
11497 (equal (buffer-file-name) file)
11498 (if regionp
11499 (and (>= pos region-start)
11500 (<= pos region-end))
11501 (and (>= pos (point))
11502 (< pos (save-excursion
11503 (org-end-of-subtree t t))))))
11504 (error "Cannot refile to position inside the tree or region"))
11506 (setq nbuf (or (find-buffer-visiting file)
11507 (find-file-noselect file)))
11508 (if goto
11509 (progn
11510 (org-pop-to-buffer-same-window nbuf)
11511 (goto-char pos)
11512 (org-show-context 'org-goto))
11513 (if regionp
11514 (progn
11515 (org-kill-new (buffer-substring region-start region-end))
11516 (org-save-markers-in-region region-start region-end))
11517 (org-copy-subtree 1 nil t))
11518 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11519 (find-file-noselect file)))
11520 (setq reversed (org-notes-order-reversed-p))
11521 (save-excursion
11522 (save-restriction
11523 (widen)
11524 (if pos
11525 (progn
11526 (goto-char pos)
11527 (looking-at org-outline-regexp)
11528 (setq level (org-get-valid-level (funcall outline-level) 1))
11529 (goto-char
11530 (if reversed
11531 (or (outline-next-heading) (point-max))
11532 (or (save-excursion (org-get-next-sibling))
11533 (org-end-of-subtree t t)
11534 (point-max)))))
11535 (setq level 1)
11536 (if (not reversed)
11537 (goto-char (point-max))
11538 (goto-char (point-min))
11539 (or (outline-next-heading) (goto-char (point-max)))))
11540 (if (not (bolp)) (newline))
11541 (org-paste-subtree level)
11542 (when org-log-refile
11543 (org-add-log-setup 'refile nil nil 'findpos
11544 org-log-refile)
11545 (unless (eq org-log-refile 'note)
11546 (save-excursion (org-add-log-note))))
11547 (and org-auto-align-tags
11548 (let ((org-loop-over-headlines-in-active-region nil))
11549 (org-set-tags nil t)))
11550 (with-demoted-errors
11551 (bookmark-set "org-refile-last-stored"))
11552 ;; If we are refiling for capture, make sure that the
11553 ;; last-capture pointers point here
11554 (when (org-bound-and-true-p org-refile-for-capture)
11555 (with-demoted-errors
11556 (bookmark-set "org-capture-last-stored-marker"))
11557 (move-marker org-capture-last-stored-marker (point)))
11558 (if (fboundp 'deactivate-mark) (deactivate-mark))
11559 (run-hooks 'org-after-refile-insert-hook))))
11560 (unless org-refile-keep
11561 (if regionp
11562 (delete-region (point) (+ (point) region-length))
11563 (org-cut-subtree)))
11564 (when (featurep 'org-inlinetask)
11565 (org-inlinetask-remove-END-maybe))
11566 (setq org-markers-to-move nil)
11567 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11569 (defun org-refile-goto-last-stored ()
11570 "Go to the location where the last refile was stored."
11571 (interactive)
11572 (bookmark-jump "org-refile-last-stored")
11573 (message "This is the location of the last refile"))
11575 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11576 no-exclude)
11577 "Prompt the user for a refile location, using PROMPT.
11578 PROMPT should not be suffixed with a colon and a space, because
11579 this function appends the default value from
11580 `org-refile-history' automatically, if that is not empty.
11581 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11582 this is used for the GOTO interface."
11583 (let ((org-refile-targets org-refile-targets)
11584 (org-refile-use-outline-path org-refile-use-outline-path)
11585 excluded-entries)
11586 (when (and (derived-mode-p 'org-mode)
11587 (not org-refile-use-cache)
11588 (not no-exclude))
11589 (org-map-tree
11590 (lambda()
11591 (setq excluded-entries
11592 (append excluded-entries (list (org-get-heading t t)))))))
11593 (setq org-refile-target-table
11594 (org-refile-get-targets default-buffer excluded-entries)))
11595 (unless org-refile-target-table
11596 (error "No refile targets"))
11597 (let* ((cbuf (current-buffer))
11598 (partial-completion-mode nil)
11599 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11600 (cfunc (if (and org-refile-use-outline-path
11601 org-outline-path-complete-in-steps)
11602 'org-olpath-completing-read
11603 'org-icompleting-read))
11604 (extra (if org-refile-use-outline-path "/" ""))
11605 (cbnex (concat (buffer-name) extra))
11606 (filename (and cfn (expand-file-name cfn)))
11607 (tbl (mapcar
11608 (lambda (x)
11609 (if (and (not (member org-refile-use-outline-path
11610 '(file full-file-path)))
11611 (not (equal filename (nth 1 x))))
11612 (cons (concat (car x) extra " ("
11613 (file-name-nondirectory (nth 1 x)) ")")
11614 (cdr x))
11615 (cons (concat (car x) extra) (cdr x))))
11616 org-refile-target-table))
11617 (completion-ignore-case t)
11618 cdef
11619 (prompt (concat prompt
11620 (or (and (car org-refile-history)
11621 (concat " (default " (car org-refile-history) ")"))
11622 (and (assoc cbnex tbl) (setq cdef cbnex)
11623 (concat " (default " cbnex ")"))) ": "))
11624 pa answ parent-target child parent old-hist)
11625 (setq old-hist org-refile-history)
11626 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11627 nil 'org-refile-history (or cdef (car org-refile-history))))
11628 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11629 (org-refile-check-position pa)
11630 (if pa
11631 (progn
11632 (when (or (not org-refile-history)
11633 (not (eq old-hist org-refile-history))
11634 (not (equal (car pa) (car org-refile-history))))
11635 (setq org-refile-history
11636 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11637 org-refile-history
11638 (cdr org-refile-history))))
11639 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11640 (pop org-refile-history)))
11642 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11643 (progn
11644 (setq parent (match-string 1 answ)
11645 child (match-string 2 answ))
11646 (setq parent-target (or (assoc parent tbl)
11647 (assoc (concat parent "/") tbl)))
11648 (when (and parent-target
11649 (or (eq new-nodes t)
11650 (and (eq new-nodes 'confirm)
11651 (y-or-n-p (format "Create new node \"%s\"? "
11652 child)))))
11653 (org-refile-new-child parent-target child)))
11654 (error "Invalid target location")))))
11656 (declare-function org-string-nw-p "org-macs" (s))
11657 (defun org-refile-check-position (refile-pointer)
11658 "Check if the refile pointer matches the headline to which it points."
11659 (let* ((file (nth 1 refile-pointer))
11660 (re (nth 2 refile-pointer))
11661 (pos (nth 3 refile-pointer))
11662 buffer)
11663 (if (and (not (markerp pos)) (not file))
11664 (error "Please save the buffer to a file before refiling")
11665 (when (org-string-nw-p re)
11666 (setq buffer (if (markerp pos)
11667 (marker-buffer pos)
11668 (or (find-buffer-visiting file)
11669 (find-file-noselect file))))
11670 (with-current-buffer buffer
11671 (save-excursion
11672 (save-restriction
11673 (widen)
11674 (goto-char pos)
11675 (beginning-of-line 1)
11676 (unless (org-looking-at-p re)
11677 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11679 (defun org-refile-new-child (parent-target child)
11680 "Use refile target PARENT-TARGET to add new CHILD below it."
11681 (unless parent-target
11682 (error "Cannot find parent for new node"))
11683 (let ((file (nth 1 parent-target))
11684 (pos (nth 3 parent-target))
11685 level)
11686 (with-current-buffer (or (find-buffer-visiting file)
11687 (find-file-noselect file))
11688 (save-excursion
11689 (save-restriction
11690 (widen)
11691 (if pos
11692 (goto-char pos)
11693 (goto-char (point-max))
11694 (if (not (bolp)) (newline)))
11695 (when (looking-at org-outline-regexp)
11696 (setq level (funcall outline-level))
11697 (org-end-of-subtree t t))
11698 (org-back-over-empty-lines)
11699 (insert "\n" (make-string
11700 (if pos (org-get-valid-level level 1) 1) ?*)
11701 " " child "\n")
11702 (beginning-of-line 0)
11703 (list (concat (car parent-target) "/" child) file "" (point)))))))
11705 (defun org-olpath-completing-read (prompt collection &rest args)
11706 "Read an outline path like a file name."
11707 (let ((thetable collection)
11708 (org-completion-use-ido nil) ; does not work with ido.
11709 (org-completion-use-iswitchb nil)) ; or iswitchb
11710 (apply
11711 'org-icompleting-read prompt
11712 (lambda (string predicate &optional flag)
11713 (let (rtn r f (l (length string)))
11714 (cond
11715 ((eq flag nil)
11716 ;; try completion
11717 (try-completion string thetable))
11718 ((eq flag t)
11719 ;; all-completions
11720 (setq rtn (all-completions string thetable predicate))
11721 (mapcar
11722 (lambda (x)
11723 (setq r (substring x l))
11724 (if (string-match " ([^)]*)$" x)
11725 (setq f (match-string 0 x))
11726 (setq f ""))
11727 (if (string-match "/" r)
11728 (concat string (substring r 0 (match-end 0)) f)
11730 rtn))
11731 ((eq flag 'lambda)
11732 ;; exact match?
11733 (assoc string thetable)))))
11734 args)))
11736 ;;;; Dynamic blocks
11738 (defun org-find-dblock (name)
11739 "Find the first dynamic block with name NAME in the buffer.
11740 If not found, stay at current position and return nil."
11741 (let ((case-fold-search t) pos)
11742 (save-excursion
11743 (goto-char (point-min))
11744 (setq pos (and (re-search-forward
11745 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11746 (match-beginning 0))))
11747 (if pos (goto-char pos))
11748 pos))
11750 (defconst org-dblock-start-re
11751 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11752 "Matches the start line of a dynamic block, with parameters.")
11754 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11755 "Matches the end of a dynamic block.")
11757 (defun org-create-dblock (plist)
11758 "Create a dynamic block section, with parameters taken from PLIST.
11759 PLIST must contain a :name entry which is used as name of the block."
11760 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11761 (end-of-line 1)
11762 (newline))
11763 (let ((col (current-column))
11764 (name (plist-get plist :name)))
11765 (insert "#+BEGIN: " name)
11766 (while plist
11767 (if (eq (car plist) :name)
11768 (setq plist (cddr plist))
11769 (insert " " (prin1-to-string (pop plist)))))
11770 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11771 (beginning-of-line -2)))
11773 (defun org-prepare-dblock ()
11774 "Prepare dynamic block for refresh.
11775 This empties the block, puts the cursor at the insert position and returns
11776 the property list including an extra property :name with the block name."
11777 (unless (looking-at org-dblock-start-re)
11778 (error "Not at a dynamic block"))
11779 (let* ((begdel (1+ (match-end 0)))
11780 (name (org-no-properties (match-string 1)))
11781 (params (append (list :name name)
11782 (read (concat "(" (match-string 3) ")")))))
11783 (save-excursion
11784 (beginning-of-line 1)
11785 (skip-chars-forward " \t")
11786 (setq params (plist-put params :indentation-column (current-column))))
11787 (unless (re-search-forward org-dblock-end-re nil t)
11788 (error "Dynamic block not terminated"))
11789 (setq params
11790 (append params
11791 (list :content (buffer-substring
11792 begdel (match-beginning 0)))))
11793 (delete-region begdel (match-beginning 0))
11794 (goto-char begdel)
11795 (open-line 1)
11796 params))
11798 (defun org-map-dblocks (&optional command)
11799 "Apply COMMAND to all dynamic blocks in the current buffer.
11800 If COMMAND is not given, use `org-update-dblock'."
11801 (let ((cmd (or command 'org-update-dblock)))
11802 (save-excursion
11803 (goto-char (point-min))
11804 (while (re-search-forward org-dblock-start-re nil t)
11805 (goto-char (match-beginning 0))
11806 (save-excursion
11807 (condition-case nil
11808 (funcall cmd)
11809 (error (message "Error during update of dynamic block"))))
11810 (unless (re-search-forward org-dblock-end-re nil t)
11811 (error "Dynamic block not terminated"))))))
11813 (defun org-dblock-update (&optional arg)
11814 "User command for updating dynamic blocks.
11815 Update the dynamic block at point. With prefix ARG, update all dynamic
11816 blocks in the buffer."
11817 (interactive "P")
11818 (if arg
11819 (org-update-all-dblocks)
11820 (or (looking-at org-dblock-start-re)
11821 (org-beginning-of-dblock))
11822 (org-update-dblock)))
11824 (defun org-update-dblock ()
11825 "Update the dynamic block at point.
11826 This means to empty the block, parse for parameters and then call
11827 the correct writing function."
11828 (interactive)
11829 (save-window-excursion
11830 (let* ((pos (point))
11831 (line (org-current-line))
11832 (params (org-prepare-dblock))
11833 (name (plist-get params :name))
11834 (indent (plist-get params :indentation-column))
11835 (cmd (intern (concat "org-dblock-write:" name))))
11836 (message "Updating dynamic block `%s' at line %d..." name line)
11837 (funcall cmd params)
11838 (message "Updating dynamic block `%s' at line %d...done" name line)
11839 (goto-char pos)
11840 (when (and indent (> indent 0))
11841 (setq indent (make-string indent ?\ ))
11842 (save-excursion
11843 (org-beginning-of-dblock)
11844 (forward-line 1)
11845 (while (not (looking-at org-dblock-end-re))
11846 (insert indent)
11847 (beginning-of-line 2))
11848 (when (looking-at org-dblock-end-re)
11849 (and (looking-at "[ \t]+")
11850 (replace-match ""))
11851 (insert indent)))))))
11853 (defun org-beginning-of-dblock ()
11854 "Find the beginning of the dynamic block at point.
11855 Error if there is no such block at point."
11856 (let ((pos (point))
11857 beg)
11858 (end-of-line 1)
11859 (if (and (re-search-backward org-dblock-start-re nil t)
11860 (setq beg (match-beginning 0))
11861 (re-search-forward org-dblock-end-re nil t)
11862 (> (match-end 0) pos))
11863 (goto-char beg)
11864 (goto-char pos)
11865 (error "Not in a dynamic block"))))
11867 (defun org-update-all-dblocks ()
11868 "Update all dynamic blocks in the buffer.
11869 This function can be used in a hook."
11870 (interactive)
11871 (when (derived-mode-p 'org-mode)
11872 (org-map-dblocks 'org-update-dblock)))
11875 ;;;; Completion
11877 (defun org-get-export-keywords ()
11878 "Return a list of all currently understood export keywords.
11879 Export keywords include options, block names, attributes and
11880 keywords relative to each registered export back-end."
11881 (delq nil
11882 (let (keywords)
11883 (mapc
11884 (lambda (back-end)
11885 (let ((props (cdr back-end)))
11886 ;; Back-end name (for keywords, like #+LATEX:)
11887 (push (upcase (symbol-name (car back-end))) keywords)
11888 ;; Back-end options.
11889 (mapc (lambda (option) (push (cadr option) keywords))
11890 (plist-get (cdr back-end) :options-alist))))
11891 (org-bound-and-true-p org-export-registered-backends))
11892 keywords)))
11894 (defconst org-options-keywords
11895 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11896 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11897 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11898 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11899 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11901 (defcustom org-structure-template-alist
11902 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11903 "<src lang=\"?\">\n\n</src>")
11904 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11905 "<example>\n?\n</example>")
11906 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11907 "<quote>\n?\n</quote>")
11908 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11909 "<verse>\n?\n</verse>")
11910 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11911 "<verbatim>\n?\n</verbatim>")
11912 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11913 "<center>\n?\n</center>")
11914 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11915 "<literal style=\"latex\">\n?\n</literal>")
11916 ("L" "#+LaTeX: "
11917 "<literal style=\"latex\">?</literal>")
11918 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11919 "<literal style=\"html\">\n?\n</literal>")
11920 ("H" "#+HTML: "
11921 "<literal style=\"html\">?</literal>")
11922 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11923 ("A" "#+ASCII: ")
11924 ("i" "#+INDEX: ?"
11925 "#+INDEX: ?")
11926 ("I" "#+INCLUDE: %file ?"
11927 "<include file=%file markup=\"?\">"))
11928 "Structure completion elements.
11929 This is a list of abbreviation keys and values. The value gets inserted
11930 if you type `<' followed by the key and then press the completion key,
11931 usually `M-TAB'. %file will be replaced by a file name after prompting
11932 for the file using completion. The cursor will be placed at the position
11933 of the `?` in the template.
11934 There are two templates for each key, the first uses the original Org syntax,
11935 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11936 the default when the /org-mtags.el/ module has been loaded. See also the
11937 variable `org-mtags-prefer-muse-templates'."
11938 :group 'org-completion
11939 :type '(repeat
11940 (string :tag "Key")
11941 (string :tag "Template")
11942 (string :tag "Muse Template")))
11944 (defun org-try-structure-completion ()
11945 "Try to complete a structure template before point.
11946 This looks for strings like \"<e\" on an otherwise empty line and
11947 expands them."
11948 (let ((l (buffer-substring (point-at-bol) (point)))
11950 (when (and (looking-at "[ \t]*$")
11951 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11952 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11953 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11954 (match-beginning 1)) a)
11955 t)))
11957 (defun org-complete-expand-structure-template (start cell)
11958 "Expand a structure template."
11959 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11960 (rpl (nth (if musep 2 1) cell))
11961 (ind ""))
11962 (delete-region start (point))
11963 (when (string-match "\\`#\\+" rpl)
11964 (cond
11965 ((bolp))
11966 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11967 (setq ind (buffer-substring (point-at-bol) (point))))
11968 (t (newline))))
11969 (setq start (point))
11970 (if (string-match "%file" rpl)
11971 (setq rpl (replace-match
11972 (concat
11973 "\""
11974 (save-match-data
11975 (abbreviate-file-name (read-file-name "Include file: ")))
11976 "\"")
11977 t t rpl)))
11978 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11979 (concat "\n" ind)))
11980 (insert rpl)
11981 (if (re-search-backward "\\?" start t) (delete-char 1))))
11983 ;;;; TODO, DEADLINE, Comments
11985 (defun org-toggle-comment ()
11986 "Change the COMMENT state of an entry."
11987 (interactive)
11988 (save-excursion
11989 (org-back-to-heading)
11990 (let (case-fold-search)
11991 (cond
11992 ((looking-at (format org-heading-keyword-regexp-format
11993 org-comment-string))
11994 (goto-char (match-end 1))
11995 (looking-at (concat " +" org-comment-string))
11996 (replace-match "" t t)
11997 (when (eolp) (insert " ")))
11998 ((looking-at org-outline-regexp)
11999 (goto-char (match-end 0))
12000 (insert org-comment-string " "))))))
12002 (defvar org-last-todo-state-is-todo nil
12003 "This is non-nil when the last TODO state change led to a TODO state.
12004 If the last change removed the TODO tag or switched to DONE, then
12005 this is nil.")
12007 (defvar org-setting-tags nil) ; dynamically skipped
12009 (defvar org-todo-setup-filter-hook nil
12010 "Hook for functions that pre-filter todo specs.
12011 Each function takes a todo spec and returns either nil or the spec
12012 transformed into canonical form." )
12014 (defvar org-todo-get-default-hook nil
12015 "Hook for functions that get a default item for todo.
12016 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12017 nil or a string to be used for the todo mark." )
12019 (defvar org-agenda-headline-snapshot-before-repeat)
12021 (defun org-current-effective-time ()
12022 "Return current time adjusted for `org-extend-today-until' variable."
12023 (let* ((ct (org-current-time))
12024 (dct (decode-time ct))
12025 (ct1
12026 (cond
12027 (org-use-last-clock-out-time-as-effective-time
12028 (or (org-clock-get-last-clock-out-time) ct))
12029 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12030 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12031 (t ct))))
12032 ct1))
12034 (defun org-todo-yesterday (&optional arg)
12035 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12036 (interactive "P")
12037 (if (eq major-mode 'org-agenda-mode)
12038 (apply 'org-agenda-todo-yesterday arg)
12039 (let* ((hour (third (decode-time
12040 (org-current-time))))
12041 (org-extend-today-until (1+ hour)))
12042 (org-todo arg))))
12044 (defvar org-block-entry-blocking ""
12045 "First entry preventing the TODO state change.")
12047 (defun org-todo (&optional arg)
12048 "Change the TODO state of an item.
12049 The state of an item is given by a keyword at the start of the heading,
12050 like
12051 *** TODO Write paper
12052 *** DONE Call mom
12054 The different keywords are specified in the variable `org-todo-keywords'.
12055 By default the available states are \"TODO\" and \"DONE\".
12056 So for this example: when the item starts with TODO, it is changed to DONE.
12057 When it starts with DONE, the DONE is removed. And when neither TODO nor
12058 DONE are present, add TODO at the beginning of the heading.
12060 With \\[universal-argument] prefix arg, use completion to determine the new \
12061 state.
12062 With numeric prefix arg, switch to that state.
12063 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12064 keywords (nextset).
12065 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12066 With a numeric prefix arg of 0, inhibit note taking for the change.
12068 For calling through lisp, arg is also interpreted in the following way:
12069 'none -> empty state
12070 \"\"(empty string) -> switch to empty state
12071 'done -> switch to DONE
12072 'nextset -> switch to the next set of keywords
12073 'previousset -> switch to the previous set of keywords
12074 \"WAITING\" -> switch to the specified keyword, but only if it
12075 really is a member of `org-todo-keywords'."
12076 (interactive "P")
12077 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12078 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12079 'region-start-level 'region))
12080 org-loop-over-headlines-in-active-region)
12081 (org-map-entries
12082 `(org-todo ,arg)
12083 org-loop-over-headlines-in-active-region
12084 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12085 (if (equal arg '(16)) (setq arg 'nextset))
12086 (let ((org-blocker-hook org-blocker-hook)
12087 commentp
12088 case-fold-search)
12089 (when (equal arg '(64))
12090 (setq arg nil org-blocker-hook nil))
12091 (when (and org-blocker-hook
12092 (or org-inhibit-blocking
12093 (org-entry-get nil "NOBLOCKING")))
12094 (setq org-blocker-hook nil))
12095 (save-excursion
12096 (catch 'exit
12097 (org-back-to-heading t)
12098 (when (looking-at (concat "^\\*+ " org-comment-string))
12099 (org-toggle-comment)
12100 (setq commentp t))
12101 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12102 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12103 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12104 (let* ((match-data (match-data))
12105 (startpos (point-at-bol))
12106 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12107 (org-log-done org-log-done)
12108 (org-log-repeat org-log-repeat)
12109 (org-todo-log-states org-todo-log-states)
12110 (org-inhibit-logging
12111 (if (equal arg 0)
12112 (progn (setq arg nil) 'note) org-inhibit-logging))
12113 (this (match-string 1))
12114 (hl-pos (match-beginning 0))
12115 (head (org-get-todo-sequence-head this))
12116 (ass (assoc head org-todo-kwd-alist))
12117 (interpret (nth 1 ass))
12118 (done-word (nth 3 ass))
12119 (final-done-word (nth 4 ass))
12120 (org-last-state (or this ""))
12121 (completion-ignore-case t)
12122 (member (member this org-todo-keywords-1))
12123 (tail (cdr member))
12124 (org-state (cond
12125 ((and org-todo-key-trigger
12126 (or (and (equal arg '(4))
12127 (eq org-use-fast-todo-selection 'prefix))
12128 (and (not arg) org-use-fast-todo-selection
12129 (not (eq org-use-fast-todo-selection
12130 'prefix)))))
12131 ;; Use fast selection
12132 (org-fast-todo-selection))
12133 ((and (equal arg '(4))
12134 (or (not org-use-fast-todo-selection)
12135 (not org-todo-key-trigger)))
12136 ;; Read a state with completion
12137 (org-icompleting-read
12138 "State: " (mapcar 'list org-todo-keywords-1)
12139 nil t))
12140 ((eq arg 'right)
12141 (if this
12142 (if tail (car tail) nil)
12143 (car org-todo-keywords-1)))
12144 ((eq arg 'left)
12145 (if (equal member org-todo-keywords-1)
12147 (if this
12148 (nth (- (length org-todo-keywords-1)
12149 (length tail) 2)
12150 org-todo-keywords-1)
12151 (org-last org-todo-keywords-1))))
12152 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12153 (setq arg nil))) ; hack to fall back to cycling
12154 (arg
12155 ;; user or caller requests a specific state
12156 (cond
12157 ((equal arg "") nil)
12158 ((eq arg 'none) nil)
12159 ((eq arg 'done) (or done-word (car org-done-keywords)))
12160 ((eq arg 'nextset)
12161 (or (car (cdr (member head org-todo-heads)))
12162 (car org-todo-heads)))
12163 ((eq arg 'previousset)
12164 (let ((org-todo-heads (reverse org-todo-heads)))
12165 (or (car (cdr (member head org-todo-heads)))
12166 (car org-todo-heads))))
12167 ((car (member arg org-todo-keywords-1)))
12168 ((stringp arg)
12169 (error "State `%s' not valid in this file" arg))
12170 ((nth (1- (prefix-numeric-value arg))
12171 org-todo-keywords-1))))
12172 ((null member) (or head (car org-todo-keywords-1)))
12173 ((equal this final-done-word) nil) ;; -> make empty
12174 ((null tail) nil) ;; -> first entry
12175 ((memq interpret '(type priority))
12176 (if (eq this-command last-command)
12177 (car tail)
12178 (if (> (length tail) 0)
12179 (or done-word (car org-done-keywords))
12180 nil)))
12182 (car tail))))
12183 (org-state (or
12184 (run-hook-with-args-until-success
12185 'org-todo-get-default-hook org-state org-last-state)
12186 org-state))
12187 (next (if org-state (concat " " org-state " ") " "))
12188 (change-plist (list :type 'todo-state-change :from this :to org-state
12189 :position startpos))
12190 dolog now-done-p)
12191 (when org-blocker-hook
12192 (setq org-last-todo-state-is-todo
12193 (not (member this org-done-keywords)))
12194 (unless (save-excursion
12195 (save-match-data
12196 (org-with-wide-buffer
12197 (run-hook-with-args-until-failure
12198 'org-blocker-hook change-plist))))
12199 (if (org-called-interactively-p 'interactive)
12200 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12201 this org-state org-block-entry-blocking)
12202 ;; fail silently
12203 (message "TODO state change from %s to %s blocked (by \"%s\")"
12204 this org-state org-block-entry-blocking)
12205 (throw 'exit nil))))
12206 (store-match-data match-data)
12207 (replace-match next t t)
12208 (unless (pos-visible-in-window-p hl-pos)
12209 (message "TODO state changed to %s" (org-trim next)))
12210 (unless head
12211 (setq head (org-get-todo-sequence-head org-state)
12212 ass (assoc head org-todo-kwd-alist)
12213 interpret (nth 1 ass)
12214 done-word (nth 3 ass)
12215 final-done-word (nth 4 ass)))
12216 (when (memq arg '(nextset previousset))
12217 (message "Keyword-Set %d/%d: %s"
12218 (- (length org-todo-sets) -1
12219 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12220 (length org-todo-sets)
12221 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12222 (setq org-last-todo-state-is-todo
12223 (not (member org-state org-done-keywords)))
12224 (setq now-done-p (and (member org-state org-done-keywords)
12225 (not (member this org-done-keywords))))
12226 (and logging (org-local-logging logging))
12227 (when (and (or org-todo-log-states org-log-done)
12228 (not (eq org-inhibit-logging t))
12229 (not (memq arg '(nextset previousset))))
12230 ;; we need to look at recording a time and note
12231 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12232 (nth 2 (assoc this org-todo-log-states))))
12233 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12234 (setq dolog 'time))
12235 (when (and org-state
12236 (member org-state org-not-done-keywords)
12237 (not (member this org-not-done-keywords)))
12238 ;; This is now a todo state and was not one before
12239 ;; If there was a CLOSED time stamp, get rid of it.
12240 (org-add-planning-info nil nil 'closed))
12241 (when (and now-done-p org-log-done)
12242 ;; It is now done, and it was not done before
12243 (org-add-planning-info 'closed (org-current-effective-time))
12244 (if (and (not dolog) (eq 'note org-log-done))
12245 (org-add-log-setup 'done org-state this 'findpos 'note)))
12246 (when (and org-state dolog)
12247 ;; This is a non-nil state, and we need to log it
12248 (org-add-log-setup 'state org-state this 'findpos dolog)))
12249 ;; Fixup tag positioning
12250 (org-todo-trigger-tag-changes org-state)
12251 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12252 (when org-provide-todo-statistics
12253 (org-update-parent-todo-statistics))
12254 (run-hooks 'org-after-todo-state-change-hook)
12255 (if (and arg (not (member org-state org-done-keywords)))
12256 (setq head (org-get-todo-sequence-head org-state)))
12257 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12258 ;; Do we need to trigger a repeat?
12259 (when now-done-p
12260 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12261 ;; This is for the agenda, take a snapshot of the headline.
12262 (save-match-data
12263 (setq org-agenda-headline-snapshot-before-repeat
12264 (org-get-heading))))
12265 (org-auto-repeat-maybe org-state))
12266 ;; Fixup cursor location if close to the keyword
12267 (if (and (outline-on-heading-p)
12268 (not (bolp))
12269 (save-excursion (beginning-of-line 1)
12270 (looking-at org-todo-line-regexp))
12271 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12272 (progn
12273 (goto-char (or (match-end 2) (match-end 1)))
12274 (and (looking-at " ") (just-one-space))))
12275 (when org-trigger-hook
12276 (save-excursion
12277 (run-hook-with-args 'org-trigger-hook change-plist)))
12278 (when commentp (org-toggle-comment))))))))
12280 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12281 "Block turning an entry into a TODO, using the hierarchy.
12282 This checks whether the current task should be blocked from state
12283 changes. Such blocking occurs when:
12285 1. The task has children which are not all in a completed state.
12287 2. A task has a parent with the property :ORDERED:, and there
12288 are siblings prior to the current task with incomplete
12289 status.
12291 3. The parent of the task is blocked because it has siblings that should
12292 be done first, or is child of a block grandparent TODO entry."
12294 (if (not org-enforce-todo-dependencies)
12295 t ; if locally turned off don't block
12296 (catch 'dont-block
12297 ;; If this is not a todo state change, or if this entry is already DONE,
12298 ;; do not block
12299 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12300 (member (plist-get change-plist :from)
12301 (cons 'done org-done-keywords))
12302 (member (plist-get change-plist :to)
12303 (cons 'todo org-not-done-keywords))
12304 (not (plist-get change-plist :to)))
12305 (throw 'dont-block t))
12306 ;; If this task has children, and any are undone, it's blocked
12307 (save-excursion
12308 (org-back-to-heading t)
12309 (let ((this-level (funcall outline-level)))
12310 (outline-next-heading)
12311 (let ((child-level (funcall outline-level)))
12312 (while (and (not (eobp))
12313 (> child-level this-level))
12314 ;; this todo has children, check whether they are all
12315 ;; completed
12316 (if (and (not (org-entry-is-done-p))
12317 (org-entry-is-todo-p))
12318 (progn (setq org-block-entry-blocking (org-get-heading))
12319 (throw 'dont-block nil)))
12320 (outline-next-heading)
12321 (setq child-level (funcall outline-level))))))
12322 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12323 ;; any previous siblings are undone, it's blocked
12324 (save-excursion
12325 (org-back-to-heading t)
12326 (let* ((pos (point))
12327 (parent-pos (and (org-up-heading-safe) (point))))
12328 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12329 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12330 (forward-line 1)
12331 (re-search-forward org-not-done-heading-regexp pos t))
12332 (setq org-block-entry-blocking (match-string 0))
12333 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12334 ;; Search further up the hierarchy, to see if an ancestor is blocked
12335 (while t
12336 (goto-char parent-pos)
12337 (if (not (looking-at org-not-done-heading-regexp))
12338 (throw 'dont-block t)) ; do not block, parent is not a TODO
12339 (setq pos (point))
12340 (setq parent-pos (and (org-up-heading-safe) (point)))
12341 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12342 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12343 (forward-line 1)
12344 (re-search-forward org-not-done-heading-regexp pos t)
12345 (setq org-block-entry-blocking (org-get-heading)))
12346 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12348 (defcustom org-track-ordered-property-with-tag nil
12349 "Should the ORDERED property also be shown as a tag?
12350 The ORDERED property decides if an entry should require subtasks to be
12351 completed in sequence. Since a property is not very visible, setting
12352 this option means that toggling the ORDERED property with the command
12353 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12354 not relevant for the behavior, but it makes things more visible.
12356 Note that toggling the tag with tags commands will not change the property
12357 and therefore not influence behavior!
12359 This can be t, meaning the tag ORDERED should be used, It can also be a
12360 string to select a different tag for this task."
12361 :group 'org-todo
12362 :type '(choice
12363 (const :tag "No tracking" nil)
12364 (const :tag "Track with ORDERED tag" t)
12365 (string :tag "Use other tag")))
12367 (defun org-toggle-ordered-property ()
12368 "Toggle the ORDERED property of the current entry.
12369 For better visibility, you can track the value of this property with a tag.
12370 See variable `org-track-ordered-property-with-tag'."
12371 (interactive)
12372 (let* ((t1 org-track-ordered-property-with-tag)
12373 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12374 (save-excursion
12375 (org-back-to-heading)
12376 (if (org-entry-get nil "ORDERED")
12377 (progn
12378 (org-delete-property "ORDERED" "PROPERTIES")
12379 (and tag (org-toggle-tag tag 'off))
12380 (message "Subtasks can be completed in arbitrary order"))
12381 (org-entry-put nil "ORDERED" "t")
12382 (and tag (org-toggle-tag tag 'on))
12383 (message "Subtasks must be completed in sequence")))))
12385 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12386 (defun org-block-todo-from-checkboxes (change-plist)
12387 "Block turning an entry into a TODO, using checkboxes.
12388 This checks whether the current task should be blocked from state
12389 changes because there are unchecked boxes in this entry."
12390 (if (not org-enforce-todo-checkbox-dependencies)
12391 t ; if locally turned off don't block
12392 (catch 'dont-block
12393 ;; If this is not a todo state change, or if this entry is already DONE,
12394 ;; do not block
12395 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12396 (member (plist-get change-plist :from)
12397 (cons 'done org-done-keywords))
12398 (member (plist-get change-plist :to)
12399 (cons 'todo org-not-done-keywords))
12400 (not (plist-get change-plist :to)))
12401 (throw 'dont-block t))
12402 ;; If this task has checkboxes that are not checked, it's blocked
12403 (save-excursion
12404 (org-back-to-heading t)
12405 (let ((beg (point)) end)
12406 (outline-next-heading)
12407 (setq end (point))
12408 (goto-char beg)
12409 (if (org-list-search-forward
12410 (concat (org-item-beginning-re)
12411 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12412 "\\[[- ]\\]")
12413 end t)
12414 (progn
12415 (if (boundp 'org-blocked-by-checkboxes)
12416 (setq org-blocked-by-checkboxes t))
12417 (throw 'dont-block nil)))))
12418 t))) ; do not block
12420 (defun org-entry-blocked-p ()
12421 "Is the current entry blocked?"
12422 (org-with-silent-modifications
12423 (if (org-entry-get nil "NOBLOCKING")
12424 nil ;; Never block this entry
12425 (not (run-hook-with-args-until-failure
12426 'org-blocker-hook
12427 (list :type 'todo-state-change
12428 :position (point)
12429 :from 'todo
12430 :to 'done))))))
12432 (defun org-update-statistics-cookies (all)
12433 "Update the statistics cookie, either from TODO or from checkboxes.
12434 This should be called with the cursor in a line with a statistics cookie."
12435 (interactive "P")
12436 (if all
12437 (progn
12438 (org-update-checkbox-count 'all)
12439 (org-map-entries 'org-update-parent-todo-statistics))
12440 (if (not (org-at-heading-p))
12441 (org-update-checkbox-count)
12442 (let ((pos (point-marker))
12443 end l1 l2)
12444 (ignore-errors (org-back-to-heading t))
12445 (if (not (org-at-heading-p))
12446 (org-update-checkbox-count)
12447 (setq l1 (org-outline-level))
12448 (setq end (save-excursion
12449 (outline-next-heading)
12450 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12451 (point)))
12452 (if (and (save-excursion
12453 (re-search-forward
12454 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12455 (not (save-excursion (re-search-forward
12456 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12457 (org-update-checkbox-count)
12458 (if (and l2 (> l2 l1))
12459 (progn
12460 (goto-char end)
12461 (org-update-parent-todo-statistics))
12462 (goto-char pos)
12463 (beginning-of-line 1)
12464 (while (re-search-forward
12465 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12466 (point-at-eol) t)
12467 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12468 (goto-char pos)
12469 (move-marker pos nil)))))
12471 (defvar org-entry-property-inherited-from) ;; defined below
12472 (defun org-update-parent-todo-statistics ()
12473 "Update any statistics cookie in the parent of the current headline.
12474 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12475 the entire subtree and this will travel up the hierarchy and update
12476 statistics everywhere."
12477 (let* ((prop (save-excursion (org-up-heading-safe)
12478 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12479 (recursive (or (not org-hierarchical-todo-statistics)
12480 (and prop (string-match "\\<recursive\\>" prop))))
12481 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12483 (first t)
12484 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12485 level ltoggle l1 new ndel
12486 (cnt-all 0) (cnt-done 0) is-percent kwd
12487 checkbox-beg ov ovs ove cookie-present)
12488 (catch 'exit
12489 (save-excursion
12490 (beginning-of-line 1)
12491 (setq ltoggle (funcall outline-level))
12492 ;; Three situations are to consider:
12494 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12495 ;; to the top-level ancestor on the headline;
12497 ;; 2. If parent has "recursive" property, repeat up to the
12498 ;; headline setting that property, taking inheritance into
12499 ;; account;
12501 ;; 3. Else, move up to direct parent and proceed only once.
12502 (while (and (setq level (org-up-heading-safe))
12503 (or recursive first)
12504 (>= (point) lim))
12505 (setq first nil cookie-present nil)
12506 (unless (and level
12507 (not (string-match
12508 "\\<checkbox\\>"
12509 (downcase (or (org-entry-get nil "COOKIE_DATA")
12510 "")))))
12511 (throw 'exit nil))
12512 (while (re-search-forward box-re (point-at-eol) t)
12513 (setq cnt-all 0 cnt-done 0 cookie-present t)
12514 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12515 (save-match-data
12516 (unless (outline-next-heading) (throw 'exit nil))
12517 (while (and (looking-at org-complex-heading-regexp)
12518 (> (setq l1 (length (match-string 1))) level))
12519 (setq kwd (and (or recursive (= l1 ltoggle))
12520 (match-string 2)))
12521 (if (or (eq org-provide-todo-statistics 'all-headlines)
12522 (and (listp org-provide-todo-statistics)
12523 (or (member kwd org-provide-todo-statistics)
12524 (member kwd org-done-keywords))))
12525 (setq cnt-all (1+ cnt-all))
12526 (if (eq org-provide-todo-statistics t)
12527 (and kwd (setq cnt-all (1+ cnt-all)))))
12528 (and (member kwd org-done-keywords)
12529 (setq cnt-done (1+ cnt-done)))
12530 (outline-next-heading)))
12531 (setq new
12532 (if is-percent
12533 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12534 (format "[%d/%d]" cnt-done cnt-all))
12535 ndel (- (match-end 0) checkbox-beg))
12536 ;; handle overlays when updating cookie from column view
12537 (when (setq ov (car (overlays-at checkbox-beg)))
12538 (setq ovs (overlay-start ov) ove (overlay-end ov))
12539 (delete-overlay ov))
12540 (goto-char checkbox-beg)
12541 (insert new)
12542 (delete-region (point) (+ (point) ndel))
12543 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12544 (when ov (move-overlay ov ovs ove)))
12545 (when cookie-present
12546 (run-hook-with-args 'org-after-todo-statistics-hook
12547 cnt-done (- cnt-all cnt-done))))))
12548 (run-hooks 'org-todo-statistics-hook)))
12550 (defvar org-after-todo-statistics-hook nil
12551 "Hook that is called after a TODO statistics cookie has been updated.
12552 Each function is called with two arguments: the number of not-done entries
12553 and the number of done entries.
12555 For example, the following function, when added to this hook, will switch
12556 an entry to DONE when all children are done, and back to TODO when new
12557 entries are set to a TODO status. Note that this hook is only called
12558 when there is a statistics cookie in the headline!
12560 (defun org-summary-todo (n-done n-not-done)
12561 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12562 (let (org-log-done org-log-states) ; turn off logging
12563 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12566 (defvar org-todo-statistics-hook nil
12567 "Hook that is run whenever Org thinks TODO statistics should be updated.
12568 This hook runs even if there is no statistics cookie present, in which case
12569 `org-after-todo-statistics-hook' would not run.")
12571 (defun org-todo-trigger-tag-changes (state)
12572 "Apply the changes defined in `org-todo-state-tags-triggers'."
12573 (let ((l org-todo-state-tags-triggers)
12574 changes)
12575 (when (or (not state) (equal state ""))
12576 (setq changes (append changes (cdr (assoc "" l)))))
12577 (when (and (stringp state) (> (length state) 0))
12578 (setq changes (append changes (cdr (assoc state l)))))
12579 (when (member state org-not-done-keywords)
12580 (setq changes (append changes (cdr (assoc 'todo l)))))
12581 (when (member state org-done-keywords)
12582 (setq changes (append changes (cdr (assoc 'done l)))))
12583 (dolist (c changes)
12584 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12586 (defun org-local-logging (value)
12587 "Get logging settings from a property VALUE."
12588 (let* (words w a)
12589 ;; directly set the variables, they are already local.
12590 (setq org-log-done nil
12591 org-log-repeat nil
12592 org-todo-log-states nil)
12593 (setq words (org-split-string value))
12594 (while (setq w (pop words))
12595 (cond
12596 ((setq a (assoc w org-startup-options))
12597 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12598 (set (nth 1 a) (nth 2 a))))
12599 ((setq a (org-extract-log-state-settings w))
12600 (and (member (car a) org-todo-keywords-1)
12601 (push a org-todo-log-states)))))))
12603 (defun org-get-todo-sequence-head (kwd)
12604 "Return the head of the TODO sequence to which KWD belongs.
12605 If KWD is not set, check if there is a text property remembering the
12606 right sequence."
12607 (let (p)
12608 (cond
12609 ((not kwd)
12610 (or (get-text-property (point-at-bol) 'org-todo-head)
12611 (progn
12612 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12613 nil (point-at-eol)))
12614 (get-text-property p 'org-todo-head))))
12615 ((not (member kwd org-todo-keywords-1))
12616 (car org-todo-keywords-1))
12617 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12619 (defun org-fast-todo-selection ()
12620 "Fast TODO keyword selection with single keys.
12621 Returns the new TODO keyword, or nil if no state change should occur."
12622 (let* ((fulltable org-todo-key-alist)
12623 (done-keywords org-done-keywords) ;; needed for the faces.
12624 (maxlen (apply 'max (mapcar
12625 (lambda (x)
12626 (if (stringp (car x)) (string-width (car x)) 0))
12627 fulltable)))
12628 (expert nil)
12629 (fwidth (+ maxlen 3 1 3))
12630 (ncol (/ (- (window-width) 4) fwidth))
12631 tg cnt e c tbl
12632 groups ingroup)
12633 (save-excursion
12634 (save-window-excursion
12635 (if expert
12636 (set-buffer (get-buffer-create " *Org todo*"))
12637 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12638 (erase-buffer)
12639 (org-set-local 'org-done-keywords done-keywords)
12640 (setq tbl fulltable cnt 0)
12641 (while (setq e (pop tbl))
12642 (cond
12643 ((equal e '(:startgroup))
12644 (push '() groups) (setq ingroup t)
12645 (when (not (= cnt 0))
12646 (setq cnt 0)
12647 (insert "\n"))
12648 (insert "{ "))
12649 ((equal e '(:endgroup))
12650 (setq ingroup nil cnt 0)
12651 (insert "}\n"))
12652 ((equal e '(:newline))
12653 (when (not (= cnt 0))
12654 (setq cnt 0)
12655 (insert "\n")
12656 (setq e (car tbl))
12657 (while (equal (car tbl) '(:newline))
12658 (insert "\n")
12659 (setq tbl (cdr tbl)))))
12661 (setq tg (car e) c (cdr e))
12662 (if ingroup (push tg (car groups)))
12663 (setq tg (org-add-props tg nil 'face
12664 (org-get-todo-face tg)))
12665 (if (and (= cnt 0) (not ingroup)) (insert " "))
12666 (insert "[" c "] " tg (make-string
12667 (- fwidth 4 (length tg)) ?\ ))
12668 (when (= (setq cnt (1+ cnt)) ncol)
12669 (insert "\n")
12670 (if ingroup (insert " "))
12671 (setq cnt 0)))))
12672 (insert "\n")
12673 (goto-char (point-min))
12674 (if (not expert) (org-fit-window-to-buffer))
12675 (message "[a-z..]:Set [SPC]:clear")
12676 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12677 (cond
12678 ((or (= c ?\C-g)
12679 (and (= c ?q) (not (rassoc c fulltable))))
12680 (setq quit-flag t))
12681 ((= c ?\ ) nil)
12682 ((setq e (rassoc c fulltable) tg (car e))
12684 (t (setq quit-flag t)))))))
12686 (defun org-entry-is-todo-p ()
12687 (member (org-get-todo-state) org-not-done-keywords))
12689 (defun org-entry-is-done-p ()
12690 (member (org-get-todo-state) org-done-keywords))
12692 (defun org-get-todo-state ()
12693 "Return the TODO keyword of the current subtree."
12694 (save-excursion
12695 (org-back-to-heading t)
12696 (and (looking-at org-todo-line-regexp)
12697 (match-end 2)
12698 (match-string 2))))
12700 (defun org-at-date-range-p (&optional inactive-ok)
12701 "Is the cursor inside a date range?"
12702 (interactive)
12703 (save-excursion
12704 (catch 'exit
12705 (let ((pos (point)))
12706 (skip-chars-backward "^[<\r\n")
12707 (skip-chars-backward "<[")
12708 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12709 (>= (match-end 0) pos)
12710 (throw 'exit t))
12711 (skip-chars-backward "^<[\r\n")
12712 (skip-chars-backward "<[")
12713 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12714 (>= (match-end 0) pos)
12715 (throw 'exit t)))
12716 nil)))
12718 (defun org-get-repeat (&optional tagline)
12719 "Check if there is a deadline/schedule with repeater in this entry."
12720 (save-match-data
12721 (save-excursion
12722 (org-back-to-heading t)
12723 (and (re-search-forward (if tagline
12724 (concat tagline "\\s-*" org-repeat-re)
12725 org-repeat-re)
12726 (org-entry-end-position) t)
12727 (match-string-no-properties 1)))))
12729 (defvar org-last-changed-timestamp)
12730 (defvar org-last-inserted-timestamp)
12731 (defvar org-log-post-message)
12732 (defvar org-log-note-purpose)
12733 (defvar org-log-note-how)
12734 (defvar org-log-note-extra)
12735 (defun org-auto-repeat-maybe (done-word)
12736 "Check if the current headline contains a repeated deadline/schedule.
12737 If yes, set TODO state back to what it was and change the base date
12738 of repeating deadline/scheduled time stamps to new date.
12739 This function is run automatically after each state change to a DONE state."
12740 ;; last-state is dynamically scoped into this function
12741 (let* ((repeat (org-get-repeat))
12742 (aa (assoc org-last-state org-todo-kwd-alist))
12743 (interpret (nth 1 aa))
12744 (head (nth 2 aa))
12745 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12746 (msg "Entry repeats: ")
12747 (org-log-done nil)
12748 (org-todo-log-states nil)
12749 re type n what ts time to-state)
12750 (when repeat
12751 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12752 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12753 org-todo-repeat-to-state))
12754 (unless (and to-state (member to-state org-todo-keywords-1))
12755 (setq to-state (if (eq interpret 'type) org-last-state head)))
12756 (org-todo to-state)
12757 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12758 (org-entry-put nil "LAST_REPEAT" (format-time-string
12759 (org-time-stamp-format t t))))
12760 (when org-log-repeat
12761 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12762 (memq 'org-add-log-note post-command-hook))
12763 ;; OK, we are already setup for some record
12764 (if (eq org-log-repeat 'note)
12765 ;; make sure we take a note, not only a time stamp
12766 (setq org-log-note-how 'note))
12767 ;; Set up for taking a record
12768 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12769 org-last-state
12770 'findpos org-log-repeat)))
12771 (org-back-to-heading t)
12772 (org-add-planning-info nil nil 'closed)
12773 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12774 org-deadline-time-regexp "\\)\\|\\("
12775 org-ts-regexp "\\)"))
12776 (while (re-search-forward
12777 re (save-excursion (outline-next-heading) (point)) t)
12778 (setq type (if (match-end 1) org-scheduled-string
12779 (if (match-end 3) org-deadline-string "Plain:"))
12780 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12781 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12782 (setq n (string-to-number (match-string 2 ts))
12783 what (match-string 3 ts))
12784 (if (equal what "w") (setq n (* n 7) what "d"))
12785 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12786 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12787 ;; Preparation, see if we need to modify the start date for the change
12788 (when (match-end 1)
12789 (setq time (save-match-data (org-time-string-to-time ts)))
12790 (cond
12791 ((equal (match-string 1 ts) ".")
12792 ;; Shift starting date to today
12793 (org-timestamp-change
12794 (- (org-today) (time-to-days time))
12795 'day))
12796 ((equal (match-string 1 ts) "+")
12797 (let ((nshiftmax 10) (nshift 0))
12798 (while (or (= nshift 0)
12799 (<= (time-to-days time)
12800 (time-to-days (current-time))))
12801 (when (= (incf nshift) nshiftmax)
12802 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12803 (error "Abort")))
12804 (org-timestamp-change n (cdr (assoc what whata)))
12805 (org-at-timestamp-p t)
12806 (setq ts (match-string 1))
12807 (setq time (save-match-data (org-time-string-to-time ts)))))
12808 (org-timestamp-change (- n) (cdr (assoc what whata)))
12809 ;; rematch, so that we have everything in place for the real shift
12810 (org-at-timestamp-p t)
12811 (setq ts (match-string 1))
12812 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12813 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12814 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12815 (setq org-log-post-message msg)
12816 (message "%s" msg))))
12818 (defun org-show-todo-tree (arg)
12819 "Make a compact tree which shows all headlines marked with TODO.
12820 The tree will show the lines where the regexp matches, and all higher
12821 headlines above the match.
12822 With a \\[universal-argument] prefix, prompt for a regexp to match.
12823 With a numeric prefix N, construct a sparse tree for the Nth element
12824 of `org-todo-keywords-1'."
12825 (interactive "P")
12826 (let ((case-fold-search nil)
12827 (kwd-re
12828 (cond ((null arg) org-not-done-regexp)
12829 ((equal arg '(4))
12830 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12831 (mapcar 'list org-todo-keywords-1))))
12832 (concat "\\("
12833 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12834 "\\)\\>")))
12835 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12836 (regexp-quote (nth (1- (prefix-numeric-value arg))
12837 org-todo-keywords-1)))
12838 (t (error "Invalid prefix argument: %s" arg)))))
12839 (message "%d TODO entries found"
12840 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12842 (defun org-deadline (arg &optional time)
12843 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12844 With one universal prefix argument, remove any deadline from the item.
12845 With two universal prefix arguments, prompt for a warning delay.
12846 With argument TIME, set the deadline at the corresponding date. TIME
12847 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12848 (interactive "P")
12849 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12850 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12851 'region-start-level 'region))
12852 org-loop-over-headlines-in-active-region)
12853 (org-map-entries
12854 `(org-deadline ',arg ,time)
12855 org-loop-over-headlines-in-active-region
12856 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12857 (let* ((old-date (org-entry-get nil "DEADLINE"))
12858 (old-date-time (if old-date (org-time-string-to-time old-date)))
12859 (repeater (and old-date
12860 (string-match
12861 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12862 old-date)
12863 (match-string 1 old-date))))
12864 (cond
12865 ((equal arg '(4))
12866 (when (and old-date org-log-redeadline)
12867 (org-add-log-setup 'deldeadline nil old-date 'findpos
12868 org-log-redeadline))
12869 (org-remove-timestamp-with-keyword org-deadline-string)
12870 (message "Item no longer has a deadline."))
12871 ((equal arg '(16))
12872 (save-excursion
12873 (if (re-search-forward
12874 org-deadline-time-regexp
12875 (save-excursion (outline-next-heading) (point)) t)
12876 (let* ((rpl0 (match-string 1))
12877 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12878 (replace-match
12879 (concat org-deadline-string
12880 " <" rpl
12881 (format " -%dd"
12882 (abs
12883 (- (time-to-days
12884 (save-match-data
12885 (org-read-date nil t nil "Warn starting from" old-date-time)))
12886 (time-to-days old-date-time))))
12887 ">") t t))
12888 (user-error "No deadline information to update"))))
12890 (org-add-planning-info 'deadline time 'closed)
12891 (when (and old-date org-log-redeadline
12892 (not (equal old-date
12893 (substring org-last-inserted-timestamp 1 -1))))
12894 (org-add-log-setup 'redeadline nil old-date 'findpos
12895 org-log-redeadline))
12896 (when repeater
12897 (save-excursion
12898 (org-back-to-heading t)
12899 (when (re-search-forward (concat org-deadline-string " "
12900 org-last-inserted-timestamp)
12901 (save-excursion
12902 (outline-next-heading) (point)) t)
12903 (goto-char (1- (match-end 0)))
12904 (insert " " repeater)
12905 (setq org-last-inserted-timestamp
12906 (concat (substring org-last-inserted-timestamp 0 -1)
12907 " " repeater
12908 (substring org-last-inserted-timestamp -1))))))
12909 (message "Deadline on %s" org-last-inserted-timestamp))))))
12911 (defun org-schedule (arg &optional time)
12912 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12913 With one universal prefix argument, remove any scheduling date from the item.
12914 With two universal prefix arguments, prompt for a delay cookie.
12915 With argument TIME, scheduled at the corresponding date. TIME can
12916 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12917 (interactive "P")
12918 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12919 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12920 'region-start-level 'region))
12921 org-loop-over-headlines-in-active-region)
12922 (org-map-entries
12923 `(org-schedule ',arg ,time)
12924 org-loop-over-headlines-in-active-region
12925 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12926 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12927 (old-date-time (if old-date (org-time-string-to-time old-date)))
12928 (repeater (and old-date
12929 (string-match
12930 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12931 old-date)
12932 (match-string 1 old-date))))
12933 (cond
12934 ((equal arg '(4))
12935 (progn
12936 (when (and old-date org-log-reschedule)
12937 (org-add-log-setup 'delschedule nil old-date 'findpos
12938 org-log-reschedule))
12939 (org-remove-timestamp-with-keyword org-scheduled-string)
12940 (message "Item is no longer scheduled.")))
12941 ((equal arg '(16))
12942 (save-excursion
12943 (if (re-search-forward
12944 org-scheduled-time-regexp
12945 (save-excursion (outline-next-heading) (point)) t)
12946 (let* ((rpl0 (match-string 1))
12947 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12948 (replace-match
12949 (concat org-scheduled-string
12950 " <" rpl
12951 (format " -%dd"
12952 (abs
12953 (- (time-to-days
12954 (save-match-data
12955 (org-read-date nil t nil "Delay until" old-date-time)))
12956 (time-to-days old-date-time))))
12957 ">") t t))
12958 (user-error "No scheduled information to update"))))
12960 (org-add-planning-info 'scheduled time 'closed)
12961 (when (and old-date org-log-reschedule
12962 (not (equal old-date
12963 (substring org-last-inserted-timestamp 1 -1))))
12964 (org-add-log-setup 'reschedule nil old-date 'findpos
12965 org-log-reschedule))
12966 (when repeater
12967 (save-excursion
12968 (org-back-to-heading t)
12969 (when (re-search-forward (concat org-scheduled-string " "
12970 org-last-inserted-timestamp)
12971 (save-excursion
12972 (outline-next-heading) (point)) t)
12973 (goto-char (1- (match-end 0)))
12974 (insert " " repeater)
12975 (setq org-last-inserted-timestamp
12976 (concat (substring org-last-inserted-timestamp 0 -1)
12977 " " repeater
12978 (substring org-last-inserted-timestamp -1))))))
12979 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12981 (defun org-get-scheduled-time (pom &optional inherit)
12982 "Get the scheduled time as a time tuple, of a format suitable
12983 for calling org-schedule with, or if there is no scheduling,
12984 returns nil."
12985 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12986 (when time
12987 (apply 'encode-time (org-parse-time-string time)))))
12989 (defun org-get-deadline-time (pom &optional inherit)
12990 "Get the deadline as a time tuple, of a format suitable for
12991 calling org-deadline with, or if there is no scheduling, returns
12992 nil."
12993 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12994 (when time
12995 (apply 'encode-time (org-parse-time-string time)))))
12997 (defun org-remove-timestamp-with-keyword (keyword)
12998 "Remove all time stamps with KEYWORD in the current entry."
12999 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13000 beg)
13001 (save-excursion
13002 (org-back-to-heading t)
13003 (setq beg (point))
13004 (outline-next-heading)
13005 (while (re-search-backward re beg t)
13006 (replace-match "")
13007 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13008 (equal (char-before) ?\ ))
13009 (backward-delete-char 1)
13010 (if (string-match "^[ \t]*$" (buffer-substring
13011 (point-at-bol) (point-at-eol)))
13012 (delete-region (point-at-bol)
13013 (min (point-max) (1+ (point-at-eol))))))))))
13015 (defun org-add-planning-info (what &optional time &rest remove)
13016 "Insert new timestamp with keyword in the line directly after the headline.
13017 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13018 If non is given, the user is prompted for a date.
13019 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13020 be removed."
13021 (interactive)
13022 (let (org-time-was-given org-end-time-was-given ts
13023 end default-time default-input)
13025 (catch 'exit
13026 (when (and (memq what '(scheduled deadline))
13027 (or (not time)
13028 (and (stringp time)
13029 (string-match "^[-+]+[0-9]" time))))
13030 ;; Try to get a default date/time from existing timestamp
13031 (save-excursion
13032 (org-back-to-heading t)
13033 (setq end (save-excursion (outline-next-heading) (point)))
13034 (when (re-search-forward (if (eq what 'scheduled)
13035 org-scheduled-time-regexp
13036 org-deadline-time-regexp)
13037 end t)
13038 (setq ts (match-string 1)
13039 default-time
13040 (apply 'encode-time (org-parse-time-string ts))
13041 default-input (and ts (org-get-compact-tod ts))))))
13042 (when what
13043 (setq time
13044 (if (stringp time)
13045 ;; This is a string (relative or absolute), set proper date
13046 (apply 'encode-time
13047 (org-read-date-analyze
13048 time default-time (decode-time default-time)))
13049 ;; If necessary, get the time from the user
13050 (or time (org-read-date nil 'to-time nil nil
13051 default-time default-input)))))
13053 (when (and org-insert-labeled-timestamps-at-point
13054 (member what '(scheduled deadline)))
13055 (insert
13056 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13057 (org-insert-time-stamp time org-time-was-given
13058 nil nil nil (list org-end-time-was-given))
13059 (setq what nil))
13060 (save-excursion
13061 (save-restriction
13062 (let (col list elt ts buffer-invisibility-spec)
13063 (org-back-to-heading t)
13064 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13065 (goto-char (match-end 1))
13066 (setq col (current-column))
13067 (goto-char (match-end 0))
13068 (if (eobp) (insert "\n") (forward-char 1))
13069 (when (and (not what)
13070 (not (looking-at
13071 (concat "[ \t]*"
13072 org-keyword-time-not-clock-regexp))))
13073 ;; Nothing to add, nothing to remove...... :-)
13074 (throw 'exit nil))
13075 (if (and (not (looking-at org-outline-regexp))
13076 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13077 "[^\r\n]*"))
13078 (not (equal (match-string 1) org-clock-string)))
13079 (narrow-to-region (match-beginning 0) (match-end 0))
13080 (insert-before-markers "\n")
13081 (backward-char 1)
13082 (narrow-to-region (point) (point))
13083 (and org-adapt-indentation (org-indent-to-column col)))
13084 ;; Check if we have to remove something.
13085 (setq list (cons what remove))
13086 (while list
13087 (setq elt (pop list))
13088 (when (or (and (eq elt 'scheduled)
13089 (re-search-forward org-scheduled-time-regexp nil t))
13090 (and (eq elt 'deadline)
13091 (re-search-forward org-deadline-time-regexp nil t))
13092 (and (eq elt 'closed)
13093 (re-search-forward org-closed-time-regexp nil t)))
13094 (replace-match "")
13095 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13096 (and (looking-at "[ \t]+") (replace-match ""))
13097 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13098 (when what
13099 (insert
13100 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13101 (cond ((eq what 'scheduled) org-scheduled-string)
13102 ((eq what 'deadline) org-deadline-string)
13103 ((eq what 'closed) org-closed-string))
13104 " ")
13105 (setq ts (org-insert-time-stamp
13106 time
13107 (or org-time-was-given
13108 (and (eq what 'closed) org-log-done-with-time))
13109 (eq what 'closed)
13110 nil nil (list org-end-time-was-given)))
13111 (insert
13112 (if (not (or (bolp) (eq (char-before) ?\ )
13113 (memq (char-after) '(32 10))
13114 (eobp))) " " ""))
13115 (end-of-line 1))
13116 (goto-char (point-min))
13117 (widen)
13118 (if (and (looking-at "[ \t]*\n")
13119 (equal (char-before) ?\n))
13120 (delete-region (1- (point)) (point-at-eol)))
13121 ts))))))
13123 (defvar org-log-note-marker (make-marker))
13124 (defvar org-log-note-purpose nil)
13125 (defvar org-log-note-state nil)
13126 (defvar org-log-note-previous-state nil)
13127 (defvar org-log-note-how nil)
13128 (defvar org-log-note-extra nil)
13129 (defvar org-log-note-window-configuration nil)
13130 (defvar org-log-note-return-to (make-marker))
13131 (defvar org-log-note-effective-time nil
13132 "Remembered current time so that dynamically scoped
13133 `org-extend-today-until' affects tha timestamps in state change
13134 log")
13136 (defvar org-log-post-message nil
13137 "Message to be displayed after a log note has been stored.
13138 The auto-repeater uses this.")
13140 (defun org-add-note ()
13141 "Add a note to the current entry.
13142 This is done in the same way as adding a state change note."
13143 (interactive)
13144 (org-add-log-setup 'note nil nil 'findpos nil))
13146 (defvar org-property-end-re)
13147 (defun org-add-log-setup (&optional purpose state prev-state
13148 findpos how extra)
13149 "Set up the post command hook to take a note.
13150 If this is about to TODO state change, the new state is expected in STATE.
13151 When FINDPOS is non-nil, find the correct position for the note in
13152 the current entry. If not, assume that it can be inserted at point.
13153 HOW is an indicator what kind of note should be created.
13154 EXTRA is additional text that will be inserted into the notes buffer."
13155 (let* ((org-log-into-drawer (org-log-into-drawer))
13156 (drawer (cond ((stringp org-log-into-drawer)
13157 org-log-into-drawer)
13158 (org-log-into-drawer "LOGBOOK"))))
13159 (save-restriction
13160 (save-excursion
13161 (when findpos
13162 (org-back-to-heading t)
13163 (narrow-to-region (point) (save-excursion
13164 (outline-next-heading) (point)))
13165 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13166 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13167 "[^\r\n]*\\)?"))
13168 (goto-char (match-end 0))
13169 (cond
13170 (drawer
13171 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13172 nil t)
13173 (progn
13174 (goto-char (match-end 0))
13175 (or org-log-states-order-reversed
13176 (and (re-search-forward org-property-end-re nil t)
13177 (goto-char (1- (match-beginning 0))))))
13178 (insert "\n:" drawer ":\n:END:")
13179 (beginning-of-line 0)
13180 (org-indent-line)
13181 (beginning-of-line 2)
13182 (org-indent-line)
13183 (end-of-line 0)))
13184 ((and org-log-state-notes-insert-after-drawers
13185 (save-excursion
13186 (forward-line) (looking-at org-drawer-regexp)))
13187 (forward-line)
13188 (while (looking-at org-drawer-regexp)
13189 (goto-char (match-end 0))
13190 (re-search-forward org-property-end-re (point-max) t)
13191 (forward-line))
13192 (forward-line -1)))
13193 (unless org-log-states-order-reversed
13194 (and (= (char-after) ?\n) (forward-char 1))
13195 (org-skip-over-state-notes)
13196 (skip-chars-backward " \t\n\r")))
13197 (move-marker org-log-note-marker (point))
13198 (setq org-log-note-purpose purpose
13199 org-log-note-state state
13200 org-log-note-previous-state prev-state
13201 org-log-note-how how
13202 org-log-note-extra extra
13203 org-log-note-effective-time (org-current-effective-time))
13204 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13206 (defun org-skip-over-state-notes ()
13207 "Skip past the list of State notes in an entry."
13208 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13209 (when (ignore-errors (goto-char (org-in-item-p)))
13210 (let* ((struct (org-list-struct))
13211 (prevs (org-list-prevs-alist struct)))
13212 (while (looking-at "[ \t]*- State")
13213 (goto-char (or (org-list-get-next-item (point) struct prevs)
13214 (org-list-get-item-end (point) struct)))))))
13216 (defun org-add-log-note (&optional purpose)
13217 "Pop up a window for taking a note, and add this note later at point."
13218 (remove-hook 'post-command-hook 'org-add-log-note)
13219 (setq org-log-note-window-configuration (current-window-configuration))
13220 (delete-other-windows)
13221 (move-marker org-log-note-return-to (point))
13222 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13223 (goto-char org-log-note-marker)
13224 (org-switch-to-buffer-other-window "*Org Note*")
13225 (erase-buffer)
13226 (if (memq org-log-note-how '(time state))
13227 (let (current-prefix-arg) (org-store-log-note))
13228 (let ((org-inhibit-startup t)) (org-mode))
13229 (insert (format "# Insert note for %s.
13230 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13231 (cond
13232 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13233 ((eq org-log-note-purpose 'done) "closed todo item")
13234 ((eq org-log-note-purpose 'state)
13235 (format "state change from \"%s\" to \"%s\""
13236 (or org-log-note-previous-state "")
13237 (or org-log-note-state "")))
13238 ((eq org-log-note-purpose 'reschedule)
13239 "rescheduling")
13240 ((eq org-log-note-purpose 'delschedule)
13241 "no longer scheduled")
13242 ((eq org-log-note-purpose 'redeadline)
13243 "changing deadline")
13244 ((eq org-log-note-purpose 'deldeadline)
13245 "removing deadline")
13246 ((eq org-log-note-purpose 'refile)
13247 "refiling")
13248 ((eq org-log-note-purpose 'note)
13249 "this entry")
13250 (t (error "This should not happen")))))
13251 (if org-log-note-extra (insert org-log-note-extra))
13252 (org-set-local 'org-finish-function 'org-store-log-note)
13253 (run-hooks 'org-log-buffer-setup-hook)))
13255 (defvar org-note-abort nil) ; dynamically scoped
13256 (defun org-store-log-note ()
13257 "Finish taking a log note, and insert it to where it belongs."
13258 (let ((txt (buffer-string)))
13259 (kill-buffer (current-buffer))
13260 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13261 lines ind bul)
13262 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13263 (setq txt (replace-match "" t t txt)))
13264 (if (string-match "\\s-+\\'" txt)
13265 (setq txt (replace-match "" t t txt)))
13266 (setq lines (org-split-string txt "\n"))
13267 (when (and note (string-match "\\S-" note))
13268 (setq note
13269 (org-replace-escapes
13270 note
13271 (list (cons "%u" (user-login-name))
13272 (cons "%U" user-full-name)
13273 (cons "%t" (format-time-string
13274 (org-time-stamp-format 'long 'inactive)
13275 org-log-note-effective-time))
13276 (cons "%T" (format-time-string
13277 (org-time-stamp-format 'long nil)
13278 org-log-note-effective-time))
13279 (cons "%d" (format-time-string
13280 (org-time-stamp-format nil 'inactive)
13281 org-log-note-effective-time))
13282 (cons "%D" (format-time-string
13283 (org-time-stamp-format nil nil)
13284 org-log-note-effective-time))
13285 (cons "%s" (if org-log-note-state
13286 (concat "\"" org-log-note-state "\"")
13287 ""))
13288 (cons "%S" (if org-log-note-previous-state
13289 (concat "\"" org-log-note-previous-state "\"")
13290 "\"\"")))))
13291 (if lines (setq note (concat note " \\\\")))
13292 (push note lines))
13293 (when (or current-prefix-arg org-note-abort)
13294 (when org-log-into-drawer
13295 (org-remove-empty-drawer-at
13296 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13297 org-log-note-marker))
13298 (setq lines nil))
13299 (when lines
13300 (with-current-buffer (marker-buffer org-log-note-marker)
13301 (save-excursion
13302 (goto-char org-log-note-marker)
13303 (move-marker org-log-note-marker nil)
13304 (end-of-line 1)
13305 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13306 (setq ind (save-excursion
13307 (if (ignore-errors (goto-char (org-in-item-p)))
13308 (let ((struct (org-list-struct)))
13309 (org-list-get-ind
13310 (org-list-get-top-point struct) struct))
13311 (skip-chars-backward " \r\t\n")
13312 (cond
13313 ((and (org-at-heading-p)
13314 org-adapt-indentation)
13315 (1+ (org-current-level)))
13316 ((org-at-heading-p) 0)
13317 (t (org-get-indentation))))))
13318 (setq bul (org-list-bullet-string "-"))
13319 (org-indent-line-to ind)
13320 (insert bul (pop lines))
13321 (let ((ind-body (+ (length bul) ind)))
13322 (while lines
13323 (insert "\n")
13324 (org-indent-line-to ind-body)
13325 (insert (pop lines))))
13326 (message "Note stored")
13327 (org-back-to-heading t)
13328 (org-cycle-hide-drawers 'children))
13329 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13330 ;; from within `org-add-log-note' because `buffer-undo-list'
13331 ;; is then modified outside of `org-with-remote-undo'.
13332 (when (eq this-command 'org-agenda-todo)
13333 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13334 ;; Don't add undo information when called from `org-agenda-todo'
13335 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13336 (set-window-configuration org-log-note-window-configuration)
13337 (with-current-buffer (marker-buffer org-log-note-return-to)
13338 (goto-char org-log-note-return-to))
13339 (move-marker org-log-note-return-to nil)
13340 (and org-log-post-message (message "%s" org-log-post-message))))
13342 (defun org-remove-empty-drawer-at (drawer pos)
13343 "Remove an empty drawer DRAWER at position POS.
13344 POS may also be a marker."
13345 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13346 (save-excursion
13347 (save-restriction
13348 (widen)
13349 (goto-char pos)
13350 (if (org-in-regexp
13351 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13352 (replace-match ""))))))
13354 (defvar org-ts-type nil)
13355 (defun org-sparse-tree (&optional arg type)
13356 "Create a sparse tree, prompt for the details.
13357 This command can create sparse trees. You first need to select the type
13358 of match used to create the tree:
13360 t Show all TODO entries.
13361 T Show entries with a specific TODO keyword.
13362 m Show entries selected by a tags/property match.
13363 p Enter a property name and its value (both with completion on existing
13364 names/values) and show entries with that property.
13365 r Show entries matching a regular expression (`/' can be used as well).
13366 b Show deadlines and scheduled items before a date.
13367 a Show deadlines and scheduled items after a date.
13368 d Show deadlines due within `org-deadline-warning-days'.
13369 D Show deadlines and scheduled items between a date range."
13370 (interactive "P")
13371 (let (ans kwd value ts-type)
13372 (setq type (or type org-sparse-tree-default-date-type))
13373 (setq org-ts-type type)
13374 (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"
13375 (cond ((eq type 'all) "all timestamps")
13376 ((eq type 'scheduled) "only scheduled")
13377 ((eq type 'deadline) "only deadline")
13378 ((eq type 'active) "only active timestamps")
13379 ((eq type 'inactive) "only inactive timestamps")
13380 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13381 ((eq type 'closed) "with a closed time-stamp")
13382 (t "scheduled/deadline")))
13383 (setq ans (read-char-exclusive))
13384 (cond
13385 ((equal ans ?c)
13386 (org-sparse-tree
13387 arg (cadr (member type '(scheduled-or-deadline
13388 all scheduled deadline active inactive closed)))))
13389 ((equal ans ?d)
13390 (call-interactively 'org-check-deadlines))
13391 ((equal ans ?b)
13392 (call-interactively 'org-check-before-date))
13393 ((equal ans ?a)
13394 (call-interactively 'org-check-after-date))
13395 ((equal ans ?D)
13396 (call-interactively 'org-check-dates-range))
13397 ((equal ans ?t)
13398 (call-interactively 'org-show-todo-tree))
13399 ((equal ans ?T)
13400 (org-show-todo-tree '(4)))
13401 ((member ans '(?T ?m))
13402 (call-interactively 'org-match-sparse-tree))
13403 ((member ans '(?p ?P))
13404 (setq kwd (org-icompleting-read "Property: "
13405 (mapcar 'list (org-buffer-property-keys))))
13406 (setq value (org-icompleting-read "Value: "
13407 (mapcar 'list (org-property-values kwd))))
13408 (unless (string-match "\\`{.*}\\'" value)
13409 (setq value (concat "\"" value "\"")))
13410 (org-match-sparse-tree arg (concat kwd "=" value)))
13411 ((member ans '(?r ?R ?/))
13412 (call-interactively 'org-occur))
13413 (t (error "No such sparse tree command \"%c\"" ans)))))
13415 (defvar org-occur-highlights nil
13416 "List of overlays used for occur matches.")
13417 (make-variable-buffer-local 'org-occur-highlights)
13418 (defvar org-occur-parameters nil
13419 "Parameters of the active org-occur calls.
13420 This is a list, each call to org-occur pushes as cons cell,
13421 containing the regular expression and the callback, onto the list.
13422 The list can contain several entries if `org-occur' has been called
13423 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13424 will only contain one set of parameters. When the highlights are
13425 removed (for example with `C-c C-c', or with the next edit (depending
13426 on `org-remove-highlights-with-change'), this variable is emptied
13427 as well.")
13428 (make-variable-buffer-local 'org-occur-parameters)
13430 (defun org-occur (regexp &optional keep-previous callback)
13431 "Make a compact tree which shows all matches of REGEXP.
13432 The tree will show the lines where the regexp matches, and all higher
13433 headlines above the match. It will also show the heading after the match,
13434 to make sure editing the matching entry is easy.
13435 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13436 call to `org-occur' will be kept, to allow stacking of calls to this
13437 command.
13438 If CALLBACK is non-nil, it is a function which is called to confirm
13439 that the match should indeed be shown."
13440 (interactive "sRegexp: \nP")
13441 (when (equal regexp "")
13442 (error "Regexp cannot be empty"))
13443 (unless keep-previous
13444 (org-remove-occur-highlights nil nil t))
13445 (push (cons regexp callback) org-occur-parameters)
13446 (let ((cnt 0))
13447 (save-excursion
13448 (goto-char (point-min))
13449 (if (or (not keep-previous) ; do not want to keep
13450 (not org-occur-highlights)) ; no previous matches
13451 ;; hide everything
13452 (org-overview))
13453 (while (re-search-forward regexp nil t)
13454 (when (or (not callback)
13455 (save-match-data (funcall callback)))
13456 (setq cnt (1+ cnt))
13457 (when org-highlight-sparse-tree-matches
13458 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13459 (org-show-context 'occur-tree))))
13460 (when org-remove-highlights-with-change
13461 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13462 nil 'local))
13463 (unless org-sparse-tree-open-archived-trees
13464 (org-hide-archived-subtrees (point-min) (point-max)))
13465 (run-hooks 'org-occur-hook)
13466 (if (org-called-interactively-p 'interactive)
13467 (message "%d match(es) for regexp %s" cnt regexp))
13468 cnt))
13470 (defun org-occur-next-match (&optional n reset)
13471 "Function for `next-error-function' to find sparse tree matches.
13472 N is the number of matches to move, when negative move backwards.
13473 RESET is entirely ignored - this function always goes back to the
13474 starting point when no match is found."
13475 (let* ((limit (if (< n 0) (point-min) (point-max)))
13476 (search-func (if (< n 0)
13477 'previous-single-char-property-change
13478 'next-single-char-property-change))
13479 (n (abs n))
13480 (pos (point))
13482 (catch 'exit
13483 (while (setq p1 (funcall search-func (point) 'org-type))
13484 (when (equal p1 limit)
13485 (goto-char pos)
13486 (error "No more matches"))
13487 (when (equal (get-char-property p1 'org-type) 'org-occur)
13488 (setq n (1- n))
13489 (when (= n 0)
13490 (goto-char p1)
13491 (throw 'exit (point))))
13492 (goto-char p1))
13493 (goto-char p1)
13494 (error "No more matches"))))
13496 (defun org-show-context (&optional key)
13497 "Make sure point and context are visible.
13498 How much context is shown depends upon the variables
13499 `org-show-hierarchy-above', `org-show-following-heading',
13500 `org-show-entry-below' and `org-show-siblings'."
13501 (let ((heading-p (org-at-heading-p t))
13502 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13503 (following-p (org-get-alist-option org-show-following-heading key))
13504 (entry-p (org-get-alist-option org-show-entry-below key))
13505 (siblings-p (org-get-alist-option org-show-siblings key)))
13506 ;; Show heading or entry text
13507 (if (and heading-p (not entry-p))
13508 (org-flag-heading nil) ; only show the heading
13509 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13510 (org-show-hidden-entry))) ; show entire entry
13511 (when following-p
13512 ;; Show next sibling, or heading below text
13513 (save-excursion
13514 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13515 (org-flag-heading nil))))
13516 (when siblings-p (org-show-siblings))
13517 (when hierarchy-p
13518 ;; show all higher headings, possibly with siblings
13519 (save-excursion
13520 (while (and (condition-case nil
13521 (progn (org-up-heading-all 1) t)
13522 (error nil))
13523 (not (bobp)))
13524 (org-flag-heading nil)
13525 (when siblings-p (org-show-siblings)))))
13526 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13528 (defvar org-reveal-start-hook nil
13529 "Hook run before revealing a location.")
13531 (defun org-reveal (&optional siblings)
13532 "Show current entry, hierarchy above it, and the following headline.
13533 This can be used to show a consistent set of context around locations
13534 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13535 not t for the search context.
13537 With optional argument SIBLINGS, on each level of the hierarchy all
13538 siblings are shown. This repairs the tree structure to what it would
13539 look like when opened with hierarchical calls to `org-cycle'.
13540 With double optional argument \\[universal-argument] \\[universal-argument], \
13541 go to the parent and show the
13542 entire tree."
13543 (interactive "P")
13544 (run-hooks 'org-reveal-start-hook)
13545 (let ((org-show-hierarchy-above t)
13546 (org-show-following-heading t)
13547 (org-show-siblings (if siblings t org-show-siblings)))
13548 (org-show-context nil))
13549 (when (equal siblings '(16))
13550 (save-excursion
13551 (when (org-up-heading-safe)
13552 (org-show-subtree)
13553 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13555 (defun org-highlight-new-match (beg end)
13556 "Highlight from BEG to END and mark the highlight is an occur headline."
13557 (let ((ov (make-overlay beg end)))
13558 (overlay-put ov 'face 'secondary-selection)
13559 (overlay-put ov 'org-type 'org-occur)
13560 (push ov org-occur-highlights)))
13562 (defun org-remove-occur-highlights (&optional beg end noremove)
13563 "Remove the occur highlights from the buffer.
13564 BEG and END are ignored. If NOREMOVE is nil, remove this function
13565 from the `before-change-functions' in the current buffer."
13566 (interactive)
13567 (unless org-inhibit-highlight-removal
13568 (mapc 'delete-overlay org-occur-highlights)
13569 (setq org-occur-highlights nil)
13570 (setq org-occur-parameters nil)
13571 (unless noremove
13572 (remove-hook 'before-change-functions
13573 'org-remove-occur-highlights 'local))))
13575 ;;;; Priorities
13577 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13578 "Regular expression matching the priority indicator.")
13580 (defvar org-remove-priority-next-time nil)
13582 (defun org-priority-up ()
13583 "Increase the priority of the current item."
13584 (interactive)
13585 (org-priority 'up))
13587 (defun org-priority-down ()
13588 "Decrease the priority of the current item."
13589 (interactive)
13590 (org-priority 'down))
13592 (defun org-priority (&optional action show)
13593 "Change the priority of an item.
13594 ACTION can be `set', `up', `down', or a character."
13595 (interactive "P")
13596 (if (equal action '(4))
13597 (org-show-priority)
13598 (unless org-enable-priority-commands
13599 (error "Priority commands are disabled"))
13600 (setq action (or action 'set))
13601 (let (current new news have remove)
13602 (save-excursion
13603 (org-back-to-heading t)
13604 (if (looking-at org-priority-regexp)
13605 (setq current (string-to-char (match-string 2))
13606 have t))
13607 (cond
13608 ((eq action 'remove)
13609 (setq remove t new ?\ ))
13610 ((or (eq action 'set)
13611 (if (featurep 'xemacs) (characterp action) (integerp action)))
13612 (if (not (eq action 'set))
13613 (setq new action)
13614 (message "Priority %c-%c, SPC to remove: "
13615 org-highest-priority org-lowest-priority)
13616 (save-match-data
13617 (setq new (read-char-exclusive))))
13618 (if (and (= (upcase org-highest-priority) org-highest-priority)
13619 (= (upcase org-lowest-priority) org-lowest-priority))
13620 (setq new (upcase new)))
13621 (cond ((equal new ?\ ) (setq remove t))
13622 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13623 (error "Priority must be between `%c' and `%c'"
13624 org-highest-priority org-lowest-priority))))
13625 ((eq action 'up)
13626 (setq new (if have
13627 (1- current) ; normal cycling
13628 ;; last priority was empty
13629 (if (eq last-command this-command)
13630 org-lowest-priority ; wrap around empty to lowest
13631 ;; default
13632 (if org-priority-start-cycle-with-default
13633 org-default-priority
13634 (1- org-default-priority))))))
13635 ((eq action 'down)
13636 (setq new (if have
13637 (1+ current) ; normal cycling
13638 ;; last priority was empty
13639 (if (eq last-command this-command)
13640 org-highest-priority ; wrap around empty to highest
13641 ;; default
13642 (if org-priority-start-cycle-with-default
13643 org-default-priority
13644 (1+ org-default-priority))))))
13645 (t (error "Invalid action")))
13646 (if (or (< (upcase new) org-highest-priority)
13647 (> (upcase new) org-lowest-priority))
13648 (if (and (memq action '(up down))
13649 (not have) (not (eq last-command this-command)))
13650 ;; `new' is from default priority
13651 (error
13652 "The default can not be set, see `org-default-priority' why")
13653 ;; normal cycling: `new' is beyond highest/lowest priority
13654 ;; and is wrapped around to the empty priority
13655 (setq remove t)))
13656 (setq news (format "%c" new))
13657 (if have
13658 (if remove
13659 (replace-match "" t t nil 1)
13660 (replace-match news t t nil 2))
13661 (if remove
13662 (error "No priority cookie found in line")
13663 (let ((case-fold-search nil))
13664 (looking-at org-todo-line-regexp))
13665 (if (match-end 2)
13666 (progn
13667 (goto-char (match-end 2))
13668 (insert " [#" news "]"))
13669 (goto-char (match-beginning 3))
13670 (insert "[#" news "] "))))
13671 (org-preserve-lc (org-set-tags nil 'align)))
13672 (if remove
13673 (message "Priority removed")
13674 (message "Priority of current item set to %s" news)))))
13676 (defun org-show-priority ()
13677 "Show the priority of the current item.
13678 This priority is composed of the main priority given with the [#A] cookies,
13679 and by additional input from the age of a schedules or deadline entry."
13680 (interactive)
13681 (let ((pri (if (eq major-mode 'org-agenda-mode)
13682 (org-get-at-bol 'priority)
13683 (save-excursion
13684 (save-match-data
13685 (beginning-of-line)
13686 (and (looking-at org-heading-regexp)
13687 (org-get-priority (match-string 0))))))))
13688 (message "Priority is %d" (if pri pri -1000))))
13690 (defun org-get-priority (s)
13691 "Find priority cookie and return priority."
13692 (save-match-data
13693 (if (functionp org-get-priority-function)
13694 (funcall org-get-priority-function)
13695 (if (not (string-match org-priority-regexp s))
13696 (* 1000 (- org-lowest-priority org-default-priority))
13697 (* 1000 (- org-lowest-priority
13698 (string-to-char (match-string 2 s))))))))
13700 ;;;; Tags
13702 (defvar org-agenda-archives-mode)
13703 (defvar org-map-continue-from nil
13704 "Position from where mapping should continue.
13705 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13707 (defvar org-scanner-tags nil
13708 "The current tag list while the tags scanner is running.")
13709 (defvar org-trust-scanner-tags nil
13710 "Should `org-get-tags-at' use the tags for the scanner.
13711 This is for internal dynamical scoping only.
13712 When this is non-nil, the function `org-get-tags-at' will return the value
13713 of `org-scanner-tags' instead of building the list by itself. This
13714 can lead to large speed-ups when the tags scanner is used in a file with
13715 many entries, and when the list of tags is retrieved, for example to
13716 obtain a list of properties. Building the tags list for each entry in such
13717 a file becomes an N^2 operation - but with this variable set, it scales
13718 as N.")
13720 (defun org-scan-tags (action matcher todo-only &optional start-level)
13721 "Sca headline tags with inheritance and produce output ACTION.
13723 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13724 or `agenda' to produce an entry list for an agenda view. It can also be
13725 a Lisp form or a function that should be called at each matched headline, in
13726 this case the return value is a list of all return values from these calls.
13728 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13729 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13730 only lines with a not-done TODO keyword are included in the output.
13731 This should be the same variable that was scoped into
13732 and set by `org-make-tags-matcher' when it constructed MATCHER.
13734 START-LEVEL can be a string with asterisks, reducing the scope to
13735 headlines matching this string."
13736 (require 'org-agenda)
13737 (let* ((re (concat "^"
13738 (if start-level
13739 ;; Get the correct level to match
13740 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13741 org-outline-regexp)
13742 " *\\(\\<\\("
13743 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13744 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13745 (props (list 'face 'default
13746 'done-face 'org-agenda-done
13747 'undone-face 'default
13748 'mouse-face 'highlight
13749 'org-not-done-regexp org-not-done-regexp
13750 'org-todo-regexp org-todo-regexp
13751 'org-complex-heading-regexp org-complex-heading-regexp
13752 'help-echo
13753 (format "mouse-2 or RET jump to org file %s"
13754 (abbreviate-file-name
13755 (or (buffer-file-name (buffer-base-buffer))
13756 (buffer-name (buffer-base-buffer)))))))
13757 (case-fold-search nil)
13758 (org-map-continue-from nil)
13759 lspos tags tags-list
13760 (tags-alist (list (cons 0 org-file-tags)))
13761 (llast 0) rtn rtn1 level category i txt
13762 todo marker entry priority)
13763 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13764 (setq action (list 'lambda nil action)))
13765 (save-excursion
13766 (goto-char (point-min))
13767 (when (eq action 'sparse-tree)
13768 (org-overview)
13769 (org-remove-occur-highlights))
13770 (while (re-search-forward re nil t)
13771 (setq org-map-continue-from nil)
13772 (catch :skip
13773 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13774 tags (if (match-end 4) (org-match-string-no-properties 4)))
13775 (goto-char (setq lspos (match-beginning 0)))
13776 (setq level (org-reduced-level (org-outline-level))
13777 category (org-get-category))
13778 (setq i llast llast level)
13779 ;; remove tag lists from same and sublevels
13780 (while (>= i level)
13781 (when (setq entry (assoc i tags-alist))
13782 (setq tags-alist (delete entry tags-alist)))
13783 (setq i (1- i)))
13784 ;; add the next tags
13785 (when tags
13786 (setq tags (org-split-string tags ":")
13787 tags-alist
13788 (cons (cons level tags) tags-alist)))
13789 ;; compile tags for current headline
13790 (setq tags-list
13791 (if org-use-tag-inheritance
13792 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13793 tags)
13794 org-scanner-tags tags-list)
13795 (when org-use-tag-inheritance
13796 (setcdr (car tags-alist)
13797 (mapcar (lambda (x)
13798 (setq x (copy-sequence x))
13799 (org-add-prop-inherited x))
13800 (cdar tags-alist))))
13801 (when (and tags org-use-tag-inheritance
13802 (or (not (eq t org-use-tag-inheritance))
13803 org-tags-exclude-from-inheritance))
13804 ;; selective inheritance, remove uninherited ones
13805 (setcdr (car tags-alist)
13806 (org-remove-uninherited-tags (cdar tags-alist))))
13807 (when (and
13809 ;; eval matcher only when the todo condition is OK
13810 (and (or (not todo-only) (member todo org-not-done-keywords))
13811 (let ((case-fold-search t) (org-trust-scanner-tags t))
13812 (eval matcher)))
13814 ;; Call the skipper, but return t if it does not skip,
13815 ;; so that the `and' form continues evaluating
13816 (progn
13817 (unless (eq action 'sparse-tree) (org-agenda-skip))
13820 ;; Check if timestamps are deselecting this entry
13821 (or (not todo-only)
13822 (and (member todo org-not-done-keywords)
13823 (or (not org-agenda-tags-todo-honor-ignore-options)
13824 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13826 ;; select this headline
13827 (cond
13828 ((eq action 'sparse-tree)
13829 (and org-highlight-sparse-tree-matches
13830 (org-get-heading) (match-end 0)
13831 (org-highlight-new-match
13832 (match-beginning 1) (match-end 1)))
13833 (org-show-context 'tags-tree))
13834 ((eq action 'agenda)
13835 (setq txt (org-agenda-format-item
13837 (concat
13838 (if (eq org-tags-match-list-sublevels 'indented)
13839 (make-string (1- level) ?.) "")
13840 (org-get-heading))
13841 level category
13842 tags-list)
13843 priority (org-get-priority txt))
13844 (goto-char lspos)
13845 (setq marker (org-agenda-new-marker))
13846 (org-add-props txt props
13847 'org-marker marker 'org-hd-marker marker 'org-category category
13848 'todo-state todo
13849 'priority priority 'type "tagsmatch")
13850 (push txt rtn))
13851 ((functionp action)
13852 (setq org-map-continue-from nil)
13853 (save-excursion
13854 (setq rtn1 (funcall action))
13855 (push rtn1 rtn)))
13856 (t (error "Invalid action")))
13858 ;; if we are to skip sublevels, jump to end of subtree
13859 (unless org-tags-match-list-sublevels
13860 (org-end-of-subtree t)
13861 (backward-char 1))))
13862 ;; Get the correct position from where to continue
13863 (if org-map-continue-from
13864 (goto-char org-map-continue-from)
13865 (and (= (point) lspos) (end-of-line 1)))))
13866 (when (and (eq action 'sparse-tree)
13867 (not org-sparse-tree-open-archived-trees))
13868 (org-hide-archived-subtrees (point-min) (point-max)))
13869 (nreverse rtn)))
13871 (defun org-remove-uninherited-tags (tags)
13872 "Remove all tags that are not inherited from the list TAGS."
13873 (cond
13874 ((eq org-use-tag-inheritance t)
13875 (if org-tags-exclude-from-inheritance
13876 (org-delete-all org-tags-exclude-from-inheritance tags)
13877 tags))
13878 ((not org-use-tag-inheritance) nil)
13879 ((stringp org-use-tag-inheritance)
13880 (delq nil (mapcar
13881 (lambda (x)
13882 (if (and (string-match org-use-tag-inheritance x)
13883 (not (member x org-tags-exclude-from-inheritance)))
13884 x nil))
13885 tags)))
13886 ((listp org-use-tag-inheritance)
13887 (delq nil (mapcar
13888 (lambda (x)
13889 (if (member x org-use-tag-inheritance) x nil))
13890 tags)))))
13892 (defun org-match-sparse-tree (&optional todo-only match)
13893 "Create a sparse tree according to tags string MATCH.
13894 MATCH can contain positive and negative selection of tags, like
13895 \"+WORK+URGENT-WITHBOSS\".
13896 If optional argument TODO-ONLY is non-nil, only select lines that are
13897 also TODO lines."
13898 (interactive "P")
13899 (org-agenda-prepare-buffers (list (current-buffer)))
13900 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13902 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13904 (defvar org-cached-props nil)
13905 (defun org-cached-entry-get (pom property)
13906 (if (or (eq t org-use-property-inheritance)
13907 (and (stringp org-use-property-inheritance)
13908 (string-match org-use-property-inheritance property))
13909 (and (listp org-use-property-inheritance)
13910 (member property org-use-property-inheritance)))
13911 ;; Caching is not possible, check it directly
13912 (org-entry-get pom property 'inherit)
13913 ;; Get all properties, so that we can do complicated checks easily
13914 (cdr (assoc property (or org-cached-props
13915 (setq org-cached-props
13916 (org-entry-properties pom)))))))
13918 (defun org-global-tags-completion-table (&optional files)
13919 "Return the list of all tags in all agenda buffer/files.
13920 Optional FILES argument is a list of files which can be used
13921 instead of the agenda files."
13922 (save-excursion
13923 (org-uniquify
13924 (delq nil
13925 (apply 'append
13926 (mapcar
13927 (lambda (file)
13928 (set-buffer (find-file-noselect file))
13929 (append (org-get-buffer-tags)
13930 (mapcar (lambda (x) (if (stringp (car-safe x))
13931 (list (car-safe x)) nil))
13932 org-tag-alist)))
13933 (if (and files (car files))
13934 files
13935 (org-agenda-files))))))))
13937 (defun org-make-tags-matcher (match)
13938 "Create the TAGS/TODO matcher form for the selection string MATCH.
13940 The variable `todo-only' is scoped dynamically into this function.
13941 It will be set to t if the matcher restricts matching to TODO entries,
13942 otherwise will not be touched.
13944 Returns a cons of the selection string MATCH and the constructed
13945 lisp form implementing the matcher. The matcher is to be evaluated
13946 at an Org entry, with point on the headline, and returns t if the
13947 entry matches the selection string MATCH. The returned lisp form
13948 references two variables with information about the entry, which
13949 must be bound around the form's evaluation: todo, the TODO keyword
13950 at the entry (or nil of none); and tags-list, the list of all tags
13951 at the entry including inherited ones. Additionally, the category
13952 of the entry (if any) must be specified as the text property
13953 'org-category on the headline.
13955 See also `org-scan-tags'.
13957 (declare (special todo-only))
13958 (unless (boundp 'todo-only)
13959 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13960 (unless match
13961 ;; Get a new match request, with completion
13962 (let ((org-last-tags-completion-table
13963 (org-global-tags-completion-table)))
13964 (setq match (org-completing-read-no-i
13965 "Match: " 'org-tags-completion-function nil nil nil
13966 'org-tags-history))))
13968 ;; Parse the string and create a lisp form
13969 (let ((match0 match)
13970 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13971 minus tag mm
13972 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13973 orterms term orlist re-p str-p level-p level-op time-p
13974 prop-p pn pv po gv rest)
13975 ;; Expand group tags
13976 (setq match (org-tags-expand match))
13977 (if (string-match "/+" match)
13978 ;; match contains also a todo-matching request
13979 (progn
13980 (setq tagsmatch (substring match 0 (match-beginning 0))
13981 todomatch (substring match (match-end 0)))
13982 (if (string-match "^!" todomatch)
13983 (setq todo-only t todomatch (substring todomatch 1)))
13984 (if (string-match "^\\s-*$" todomatch)
13985 (setq todomatch nil)))
13986 ;; only matching tags
13987 (setq tagsmatch match todomatch nil))
13989 ;; Make the tags matcher
13990 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13991 (setq tagsmatcher t)
13992 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13993 (while (setq term (pop orterms))
13994 (while (and (equal (substring term -1) "\\") orterms)
13995 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13996 (while (string-match re term)
13997 (setq rest (substring term (match-end 0))
13998 minus (and (match-end 1)
13999 (equal (match-string 1 term) "-"))
14000 tag (save-match-data (replace-regexp-in-string
14001 "\\\\-" "-"
14002 (match-string 2 term)))
14003 re-p (equal (string-to-char tag) ?{)
14004 level-p (match-end 4)
14005 prop-p (match-end 5)
14006 mm (cond
14007 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14008 (level-p
14009 (setq level-op (org-op-to-function (match-string 3 term)))
14010 `(,level-op level ,(string-to-number
14011 (match-string 4 term))))
14012 (prop-p
14013 (setq pn (match-string 5 term)
14014 po (match-string 6 term)
14015 pv (match-string 7 term)
14016 re-p (equal (string-to-char pv) ?{)
14017 str-p (equal (string-to-char pv) ?\")
14018 time-p (save-match-data
14019 (string-match "^\"[[<].*[]>]\"$" pv))
14020 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14021 (if time-p (setq pv (org-matcher-time pv)))
14022 (setq po (org-op-to-function po (if time-p 'time str-p)))
14023 (cond
14024 ((equal pn "CATEGORY")
14025 (setq gv '(get-text-property (point) 'org-category)))
14026 ((equal pn "TODO")
14027 (setq gv 'todo))
14029 (setq gv `(org-cached-entry-get nil ,pn))))
14030 (if re-p
14031 (if (eq po 'org<>)
14032 `(not (string-match ,pv (or ,gv "")))
14033 `(string-match ,pv (or ,gv "")))
14034 (if str-p
14035 `(,po (or ,gv "") ,pv)
14036 `(,po (string-to-number (or ,gv ""))
14037 ,(string-to-number pv) ))))
14038 (t `(member ,tag tags-list)))
14039 mm (if minus (list 'not mm) mm)
14040 term rest)
14041 (push mm tagsmatcher))
14042 (push (if (> (length tagsmatcher) 1)
14043 (cons 'and tagsmatcher)
14044 (car tagsmatcher))
14045 orlist)
14046 (setq tagsmatcher nil))
14047 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14048 (setq tagsmatcher
14049 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14050 ;; Make the todo matcher
14051 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14052 (setq todomatcher t)
14053 (setq orterms (org-split-string todomatch "|") orlist nil)
14054 (while (setq term (pop orterms))
14055 (while (string-match re term)
14056 (setq minus (and (match-end 1)
14057 (equal (match-string 1 term) "-"))
14058 kwd (match-string 2 term)
14059 re-p (equal (string-to-char kwd) ?{)
14060 term (substring term (match-end 0))
14061 mm (if re-p
14062 `(string-match ,(substring kwd 1 -1) todo)
14063 (list 'equal 'todo kwd))
14064 mm (if minus (list 'not mm) mm))
14065 (push mm todomatcher))
14066 (push (if (> (length todomatcher) 1)
14067 (cons 'and todomatcher)
14068 (car todomatcher))
14069 orlist)
14070 (setq todomatcher nil))
14071 (setq todomatcher (if (> (length orlist) 1)
14072 (cons 'or orlist) (car orlist))))
14074 ;; Return the string and lisp forms of the matcher
14075 (setq matcher (if todomatcher
14076 (list 'and tagsmatcher todomatcher)
14077 tagsmatcher))
14078 (when todo-only
14079 (setq matcher (list 'and '(member todo org-not-done-keywords)
14080 matcher)))
14081 (cons match0 matcher)))
14083 (defun org-tags-expand (match &optional single-as-list downcased)
14084 "Expand group tags in MATCH.
14086 This replaces every group tag in MATCH with a regexp tag search.
14087 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14088 will be replaced like this:
14090 Work => {\(?:Work\|Lab\|Conf\}
14091 +Work => +{\(?:Work\|Lab\|Conf\}
14092 -Work => -{\(?:Work\|Lab\|Conf\}
14094 Replacing by a regexp preserves the structure of the match.
14095 E.g., this expansion
14097 Work|Home => {\(?:Work\|Lab\|Conf\}|Home
14099 will match anything tagged with \"Lab\" and \"Home\", or tagged
14100 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14102 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14103 assumed to be a single group tag, and the function will return
14104 the list of tags in this group.
14106 When DOWNCASE is non-nil, expand downcased TAGS."
14107 (if org-group-tags
14108 (let* ((case-fold-search t)
14109 (stable org-mode-syntax-table)
14110 (tal (or org-tag-groups-alist-for-agenda
14111 org-tag-groups-alist))
14112 (tal (if downcased (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 (string-match
14119 (concat "\\(?1:[+-]?\\)\\(?2:\\<" (regexp-opt tml) "\\>\\)")
14120 rtnmatch))
14121 (let* ((dir (match-string 1 rtnmatch))
14122 (tag (match-string 2 rtnmatch))
14123 (tag (if downcased (downcase tag) tag)))
14124 (setq tml (delete tag tml))
14125 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14126 (setq rtnmatch
14127 (replace-match
14128 (concat dir "{" (regexp-opt rpl) "}") t t rtnmatch))))
14129 (if single-as-list
14130 (or (reverse rpl) (list rtnmatch))
14131 rtnmatch))
14132 (if single-as-list (list (if downcased (downcase match) match))
14133 match)))
14135 (defun org-op-to-function (op &optional stringp)
14136 "Turn an operator into the appropriate function."
14137 (setq op
14138 (cond
14139 ((equal op "<" ) '(< string< org-time<))
14140 ((equal op ">" ) '(> org-string> org-time>))
14141 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14142 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14143 ((member op '("=" "==")) '(= string= org-time=))
14144 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14145 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14147 (defun org<> (a b) (not (= a b)))
14148 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14149 (defun org-string>= (a b) (not (string< a b)))
14150 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14151 (defun org-string<> (a b) (not (string= a b)))
14152 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14153 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< 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) (org<> a b)))
14158 (defun org-2ft (s)
14159 "Convert S to a floating point time.
14160 If S is already a number, just return it. If it is a string, parse
14161 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14162 (cond
14163 ((numberp s) s)
14164 ((stringp s)
14165 (condition-case nil
14166 (float-time (apply 'encode-time (org-parse-time-string s)))
14167 (error 0.)))
14168 (t 0.)))
14170 (defun org-time-today ()
14171 "Time in seconds today at 0:00.
14172 Returns the float number of seconds since the beginning of the
14173 epoch to the beginning of today (00:00)."
14174 (float-time (apply 'encode-time
14175 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14177 (defun org-matcher-time (s)
14178 "Interpret a time comparison value."
14179 (save-match-data
14180 (cond
14181 ((string= s "<now>") (float-time))
14182 ((string= s "<today>") (org-time-today))
14183 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14184 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14185 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14186 (+ (org-time-today)
14187 (* (string-to-number (match-string 1 s))
14188 (cdr (assoc (match-string 2 s)
14189 '(("d" . 86400.0) ("w" . 604800.0)
14190 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14191 (t (org-2ft s)))))
14193 (defun org-match-any-p (re list)
14194 "Does re match any element of list?"
14195 (setq list (mapcar (lambda (x) (string-match re x)) list))
14196 (delq nil list))
14198 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14199 (defvar org-tags-overlay (make-overlay 1 1))
14200 (org-detach-overlay org-tags-overlay)
14202 (defun org-get-local-tags-at (&optional pos)
14203 "Get a list of tags defined in the current headline."
14204 (org-get-tags-at pos 'local))
14206 (defun org-get-local-tags ()
14207 "Get a list of tags defined in the current headline."
14208 (org-get-tags-at nil 'local))
14210 (defun org-get-tags-at (&optional pos local)
14211 "Get a list of all headline tags applicable at POS.
14212 POS defaults to point. If tags are inherited, the list contains
14213 the targets in the same sequence as the headlines appear, i.e.
14214 the tags of the current headline come last.
14215 When LOCAL is non-nil, only return tags from the current headline,
14216 ignore inherited ones."
14217 (interactive)
14218 (if (and org-trust-scanner-tags
14219 (or (not pos) (equal pos (point)))
14220 (not local))
14221 org-scanner-tags
14222 (let (tags ltags lastpos parent)
14223 (save-excursion
14224 (save-restriction
14225 (widen)
14226 (goto-char (or pos (point)))
14227 (save-match-data
14228 (catch 'done
14229 (condition-case nil
14230 (progn
14231 (org-back-to-heading t)
14232 (while (not (equal lastpos (point)))
14233 (setq lastpos (point))
14234 (when (looking-at
14235 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14236 (setq ltags (org-split-string
14237 (org-match-string-no-properties 1) ":"))
14238 (when parent
14239 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14240 (setq tags (append
14241 (if parent
14242 (org-remove-uninherited-tags ltags)
14243 ltags)
14244 tags)))
14245 (or org-use-tag-inheritance (throw 'done t))
14246 (if local (throw 'done t))
14247 (or (org-up-heading-safe) (error nil))
14248 (setq parent t)))
14249 (error nil)))))
14250 (if local
14251 tags
14252 (reverse (delete-dups
14253 (reverse (append
14254 (org-remove-uninherited-tags
14255 org-file-tags) tags)))))))))
14257 (defun org-add-prop-inherited (s)
14258 (add-text-properties 0 (length s) '(inherited t) s)
14261 (defun org-toggle-tag (tag &optional onoff)
14262 "Toggle the tag TAG for the current line.
14263 If ONOFF is `on' or `off', don't toggle but set to this state."
14264 (let (res current)
14265 (save-excursion
14266 (org-back-to-heading t)
14267 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14268 (point-at-eol) t)
14269 (progn
14270 (setq current (match-string 1))
14271 (replace-match ""))
14272 (setq current ""))
14273 (setq current (nreverse (org-split-string current ":")))
14274 (cond
14275 ((eq onoff 'on)
14276 (setq res t)
14277 (or (member tag current) (push tag current)))
14278 ((eq onoff 'off)
14279 (or (not (member tag current)) (setq current (delete tag current))))
14280 (t (if (member tag current)
14281 (setq current (delete tag current))
14282 (setq res t)
14283 (push tag current))))
14284 (end-of-line 1)
14285 (if current
14286 (progn
14287 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14288 (org-set-tags nil t))
14289 (delete-horizontal-space))
14290 (run-hooks 'org-after-tags-change-hook))
14291 res))
14293 (defun org-align-tags-here (to-col)
14294 ;; Assumes that this is a headline
14295 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14296 (beginning-of-line 1)
14297 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14298 (< pos (match-beginning 2)))
14299 (progn
14300 (setq tags-l (- (match-end 2) (match-beginning 2)))
14301 (goto-char (match-beginning 1))
14302 (insert " ")
14303 (delete-region (point) (1+ (match-beginning 2)))
14304 (setq ncol (max (current-column)
14305 (1+ col)
14306 (if (> to-col 0)
14307 to-col
14308 (- (abs to-col) tags-l))))
14309 (setq p (point))
14310 (insert (make-string (- ncol (current-column)) ?\ ))
14311 (setq ncol (current-column))
14312 (when indent-tabs-mode (tabify p (point-at-eol)))
14313 (org-move-to-column (min ncol col) t))
14314 (goto-char pos))))
14316 (defun org-set-tags-command (&optional arg just-align)
14317 "Call the set-tags command for the current entry."
14318 (interactive "P")
14319 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14320 (org-set-tags arg just-align)
14321 (save-excursion
14322 (unless (and (org-region-active-p)
14323 org-loop-over-headlines-in-active-region)
14324 (org-back-to-heading t))
14325 (org-set-tags arg just-align))))
14327 (defun org-set-tags-to (data)
14328 "Set the tags of the current entry to DATA, replacing the current tags.
14329 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14330 If DATA is nil or the empty string, any tags will be removed."
14331 (interactive "sTags: ")
14332 (setq data
14333 (cond
14334 ((eq data nil) "")
14335 ((equal data "") "")
14336 ((stringp data)
14337 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14338 ":"))
14339 ((listp data)
14340 (concat ":" (mapconcat 'identity data ":") ":"))))
14341 (when data
14342 (save-excursion
14343 (org-back-to-heading t)
14344 (when (looking-at org-complex-heading-regexp)
14345 (if (match-end 5)
14346 (progn
14347 (goto-char (match-beginning 5))
14348 (insert data)
14349 (delete-region (point) (point-at-eol))
14350 (org-set-tags nil 'align))
14351 (goto-char (point-at-eol))
14352 (insert " " data)
14353 (org-set-tags nil 'align)))
14354 (beginning-of-line 1)
14355 (if (looking-at ".*?\\([ \t]+\\)$")
14356 (delete-region (match-beginning 1) (match-end 1))))))
14358 (defun org-align-all-tags ()
14359 "Align the tags i all headings."
14360 (interactive)
14361 (save-excursion
14362 (or (ignore-errors (org-back-to-heading t))
14363 (outline-next-heading))
14364 (if (org-at-heading-p)
14365 (org-set-tags t)
14366 (message "No headings"))))
14368 (defvar org-indent-indentation-per-level)
14369 (defun org-set-tags (&optional arg just-align)
14370 "Set the tags for the current headline.
14371 With prefix ARG, realign all tags in headings in the current buffer."
14372 (interactive "P")
14373 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14374 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14375 'region-start-level 'region))
14376 org-loop-over-headlines-in-active-region)
14377 (org-map-entries
14378 ;; We don't use ARG and JUST-ALIGN here these args are not
14379 ;; useful when looping over headlines
14380 `(org-set-tags)
14381 org-loop-over-headlines-in-active-region
14382 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14383 (let* ((re org-outline-regexp-bol)
14384 (current (unless arg (org-get-tags-string)))
14385 (col (current-column))
14386 (org-setting-tags t)
14387 table current-tags inherited-tags ; computed below when needed
14388 tags p0 c0 c1 rpl di tc level)
14389 (if arg
14390 (save-excursion
14391 (goto-char (point-min))
14392 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14393 (while (re-search-forward re nil t)
14394 (org-set-tags nil t)
14395 (end-of-line 1)))
14396 (message "All tags realigned to column %d" org-tags-column))
14397 (if just-align
14398 (setq tags current)
14399 ;; Get a new set of tags from the user
14400 (save-excursion
14401 (setq table (append org-tag-persistent-alist
14402 (or org-tag-alist (org-get-buffer-tags))
14403 (and
14404 org-complete-tags-always-offer-all-agenda-tags
14405 (org-global-tags-completion-table
14406 (org-agenda-files))))
14407 org-last-tags-completion-table table
14408 current-tags (org-split-string current ":")
14409 inherited-tags (nreverse
14410 (nthcdr (length current-tags)
14411 (nreverse (org-get-tags-at))))
14412 tags
14413 (if (or (eq t org-use-fast-tag-selection)
14414 (and org-use-fast-tag-selection
14415 (delq nil (mapcar 'cdr table))))
14416 (org-fast-tag-selection
14417 current-tags inherited-tags table
14418 (if org-fast-tag-selection-include-todo
14419 org-todo-key-alist))
14420 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14421 (org-trim
14422 (org-icompleting-read "Tags: "
14423 'org-tags-completion-function
14424 nil nil current 'org-tags-history))))))
14425 (while (string-match "[-+&]+" tags)
14426 ;; No boolean logic, just a list
14427 (setq tags (replace-match ":" t t tags))))
14429 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14431 (if org-tags-sort-function
14432 (setq tags (mapconcat 'identity
14433 (sort (org-split-string
14434 tags (org-re "[^[:alnum:]_@#%]+"))
14435 org-tags-sort-function) ":")))
14437 (if (string-match "\\`[\t ]*\\'" tags)
14438 (setq tags "")
14439 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14440 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14442 ;; Insert new tags at the correct column
14443 (beginning-of-line 1)
14444 (setq level (or (and (looking-at org-outline-regexp)
14445 (- (match-end 0) (point) 1))
14447 (cond
14448 ((and (equal current "") (equal tags "")))
14449 ((re-search-forward
14450 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14451 (point-at-eol) t)
14452 (if (equal tags "")
14453 (setq rpl "")
14454 (goto-char (match-beginning 0))
14455 (setq c0 (current-column)
14456 ;; compute offset for the case of org-indent-mode active
14457 di (if org-indent-mode
14458 (* (1- org-indent-indentation-per-level) (1- level))
14460 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14461 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14462 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14463 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14464 (replace-match rpl t t)
14465 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14466 tags)
14467 (t (error "Tags alignment failed")))
14468 (org-move-to-column col)
14469 (unless just-align
14470 (run-hooks 'org-after-tags-change-hook))))))
14472 (defun org-change-tag-in-region (beg end tag off)
14473 "Add or remove TAG for each entry in the region.
14474 This works in the agenda, and also in an org-mode buffer."
14475 (interactive
14476 (list (region-beginning) (region-end)
14477 (let ((org-last-tags-completion-table
14478 (if (derived-mode-p 'org-mode)
14479 (org-get-buffer-tags)
14480 (org-global-tags-completion-table))))
14481 (org-icompleting-read
14482 "Tag: " 'org-tags-completion-function nil nil nil
14483 'org-tags-history))
14484 (progn
14485 (message "[s]et or [r]emove? ")
14486 (equal (read-char-exclusive) ?r))))
14487 (if (fboundp 'deactivate-mark) (deactivate-mark))
14488 (let ((agendap (equal major-mode 'org-agenda-mode))
14489 l1 l2 m buf pos newhead (cnt 0))
14490 (goto-char end)
14491 (setq l2 (1- (org-current-line)))
14492 (goto-char beg)
14493 (setq l1 (org-current-line))
14494 (loop for l from l1 to l2 do
14495 (org-goto-line l)
14496 (setq m (get-text-property (point) 'org-hd-marker))
14497 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14498 (and agendap m))
14499 (setq buf (if agendap (marker-buffer m) (current-buffer))
14500 pos (if agendap m (point)))
14501 (with-current-buffer buf
14502 (save-excursion
14503 (save-restriction
14504 (goto-char pos)
14505 (setq cnt (1+ cnt))
14506 (org-toggle-tag tag (if off 'off 'on))
14507 (setq newhead (org-get-heading)))))
14508 (and agendap (org-agenda-change-all-lines newhead m))))
14509 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14511 (defun org-tags-completion-function (string predicate &optional flag)
14512 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14513 (confirm (lambda (x) (stringp (car x)))))
14514 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14515 (setq s1 (match-string 1 string)
14516 s2 (match-string 2 string))
14517 (setq s1 "" s2 string))
14518 (cond
14519 ((eq flag nil)
14520 ;; try completion
14521 (setq rtn (try-completion s2 ctable confirm))
14522 (if (stringp rtn)
14523 (setq rtn
14524 (concat s1 s2 (substring rtn (length s2))
14525 (if (and org-add-colon-after-tag-completion
14526 (assoc rtn ctable))
14527 ":" ""))))
14528 rtn)
14529 ((eq flag t)
14530 ;; all-completions
14531 (all-completions s2 ctable confirm))
14532 ((eq flag 'lambda)
14533 ;; exact match?
14534 (assoc s2 ctable)))))
14536 (defun org-fast-tag-insert (kwd tags face &optional end)
14537 "Insert KDW, and the TAGS, the latter with face FACE.
14538 Also insert END."
14539 (insert (format "%-12s" (concat kwd ":"))
14540 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14541 (or end "")))
14543 (defun org-fast-tag-show-exit (flag)
14544 (save-excursion
14545 (org-goto-line 3)
14546 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14547 (replace-match ""))
14548 (when flag
14549 (end-of-line 1)
14550 (org-move-to-column (- (window-width) 19) t)
14551 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14553 (defun org-set-current-tags-overlay (current prefix)
14554 "Add an overlay to CURRENT tag with PREFIX."
14555 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14556 (if (featurep 'xemacs)
14557 (org-overlay-display org-tags-overlay (concat prefix s)
14558 'secondary-selection)
14559 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14560 (org-overlay-display org-tags-overlay (concat prefix s)))))
14562 (defvar org-last-tag-selection-key nil)
14563 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14564 "Fast tag selection with single keys.
14565 CURRENT is the current list of tags in the headline, INHERITED is the
14566 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14567 possibly with grouping information. TODO-TABLE is a similar table with
14568 TODO keywords, should these have keys assigned to them.
14569 If the keys are nil, a-z are automatically assigned.
14570 Returns the new tags string, or nil to not change the current settings."
14571 (let* ((fulltable (append table todo-table))
14572 (maxlen (apply 'max (mapcar
14573 (lambda (x)
14574 (if (stringp (car x)) (string-width (car x)) 0))
14575 fulltable)))
14576 (buf (current-buffer))
14577 (expert (eq org-fast-tag-selection-single-key 'expert))
14578 (buffer-tags nil)
14579 (fwidth (+ maxlen 3 1 3))
14580 (ncol (/ (- (window-width) 4) fwidth))
14581 (i-face 'org-done)
14582 (c-face 'org-todo)
14583 tg cnt e c char c1 c2 ntable tbl rtn
14584 ov-start ov-end ov-prefix
14585 (exit-after-next org-fast-tag-selection-single-key)
14586 (done-keywords org-done-keywords)
14587 groups ingroup)
14588 (save-excursion
14589 (beginning-of-line 1)
14590 (if (looking-at
14591 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14592 (setq ov-start (match-beginning 1)
14593 ov-end (match-end 1)
14594 ov-prefix "")
14595 (setq ov-start (1- (point-at-eol))
14596 ov-end (1+ ov-start))
14597 (skip-chars-forward "^\n\r")
14598 (setq ov-prefix
14599 (concat
14600 (buffer-substring (1- (point)) (point))
14601 (if (> (current-column) org-tags-column)
14603 (make-string (- org-tags-column (current-column)) ?\ ))))))
14604 (move-overlay org-tags-overlay ov-start ov-end)
14605 (save-window-excursion
14606 (if expert
14607 (set-buffer (get-buffer-create " *Org tags*"))
14608 (delete-other-windows)
14609 (split-window-vertically)
14610 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14611 (erase-buffer)
14612 (org-set-local 'org-done-keywords done-keywords)
14613 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14614 (org-fast-tag-insert "Current" current c-face "\n\n")
14615 (org-fast-tag-show-exit exit-after-next)
14616 (org-set-current-tags-overlay current ov-prefix)
14617 (setq tbl fulltable char ?a cnt 0)
14618 (while (setq e (pop tbl))
14619 (cond
14620 ((equal (car e) :startgroup)
14621 (push '() groups) (setq ingroup t)
14622 (when (not (= cnt 0))
14623 (setq cnt 0)
14624 (insert "\n"))
14625 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14626 ((equal (car e) :endgroup)
14627 (setq ingroup nil cnt 0)
14628 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14629 ((equal e '(:newline))
14630 (when (not (= cnt 0))
14631 (setq cnt 0)
14632 (insert "\n")
14633 (setq e (car tbl))
14634 (while (equal (car tbl) '(:newline))
14635 (insert "\n")
14636 (setq tbl (cdr tbl)))))
14637 ((equal e '(:grouptags)) nil)
14639 (setq tg (copy-sequence (car e)) c2 nil)
14640 (if (cdr e)
14641 (setq c (cdr e))
14642 ;; automatically assign a character.
14643 (setq c1 (string-to-char
14644 (downcase (substring
14645 tg (if (= (string-to-char tg) ?@) 1 0)))))
14646 (if (or (rassoc c1 ntable) (rassoc c1 table))
14647 (while (or (rassoc char ntable) (rassoc char table))
14648 (setq char (1+ char)))
14649 (setq c2 c1))
14650 (setq c (or c2 char)))
14651 (if ingroup (push tg (car groups)))
14652 (setq tg (org-add-props tg nil 'face
14653 (cond
14654 ((not (assoc tg table))
14655 (org-get-todo-face tg))
14656 ((member tg current) c-face)
14657 ((member tg inherited) i-face))))
14658 (if (equal (caar tbl) :grouptags)
14659 (org-add-props tg nil 'face 'org-tag-group))
14660 (if (and (= cnt 0) (not ingroup)) (insert " "))
14661 (insert "[" c "] " tg (make-string
14662 (- fwidth 4 (length tg)) ?\ ))
14663 (push (cons tg c) ntable)
14664 (when (= (setq cnt (1+ cnt)) ncol)
14665 (insert "\n")
14666 (if ingroup (insert " "))
14667 (setq cnt 0)))))
14668 (setq ntable (nreverse ntable))
14669 (insert "\n")
14670 (goto-char (point-min))
14671 (if (not expert) (org-fit-window-to-buffer))
14672 (setq rtn
14673 (catch 'exit
14674 (while t
14675 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14676 (if (not groups) "no " "")
14677 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14678 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14679 (setq org-last-tag-selection-key c)
14680 (cond
14681 ((= c ?\r) (throw 'exit t))
14682 ((= c ?!)
14683 (setq groups (not groups))
14684 (goto-char (point-min))
14685 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14686 ((= c ?\C-c)
14687 (if (not expert)
14688 (org-fast-tag-show-exit
14689 (setq exit-after-next (not exit-after-next)))
14690 (setq expert nil)
14691 (delete-other-windows)
14692 (set-window-buffer (split-window-vertically) " *Org tags*")
14693 (org-switch-to-buffer-other-window " *Org tags*")
14694 (org-fit-window-to-buffer)))
14695 ((or (= c ?\C-g)
14696 (and (= c ?q) (not (rassoc c ntable))))
14697 (org-detach-overlay org-tags-overlay)
14698 (setq quit-flag t))
14699 ((= c ?\ )
14700 (setq current nil)
14701 (if exit-after-next (setq exit-after-next 'now)))
14702 ((= c ?\t)
14703 (condition-case nil
14704 (setq tg (org-icompleting-read
14705 "Tag: "
14706 (or buffer-tags
14707 (with-current-buffer buf
14708 (org-get-buffer-tags)))))
14709 (quit (setq tg "")))
14710 (when (string-match "\\S-" tg)
14711 (add-to-list 'buffer-tags (list tg))
14712 (if (member tg current)
14713 (setq current (delete tg current))
14714 (push tg current)))
14715 (if exit-after-next (setq exit-after-next 'now)))
14716 ((setq e (rassoc c todo-table) tg (car e))
14717 (with-current-buffer buf
14718 (save-excursion (org-todo tg)))
14719 (if exit-after-next (setq exit-after-next 'now)))
14720 ((setq e (rassoc c ntable) tg (car e))
14721 (if (member tg current)
14722 (setq current (delete tg current))
14723 (loop for g in groups do
14724 (if (member tg g)
14725 (mapc (lambda (x)
14726 (setq current (delete x current)))
14727 g)))
14728 (push tg current))
14729 (if exit-after-next (setq exit-after-next 'now))))
14731 ;; Create a sorted list
14732 (setq current
14733 (sort current
14734 (lambda (a b)
14735 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14736 (if (eq exit-after-next 'now) (throw 'exit t))
14737 (goto-char (point-min))
14738 (beginning-of-line 2)
14739 (delete-region (point) (point-at-eol))
14740 (org-fast-tag-insert "Current" current c-face)
14741 (org-set-current-tags-overlay current ov-prefix)
14742 (while (re-search-forward
14743 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14744 (setq tg (match-string 1))
14745 (add-text-properties
14746 (match-beginning 1) (match-end 1)
14747 (list 'face
14748 (cond
14749 ((member tg current) c-face)
14750 ((member tg inherited) i-face)
14751 (t (get-text-property (match-beginning 1) 'face))))))
14752 (goto-char (point-min)))))
14753 (org-detach-overlay org-tags-overlay)
14754 (if rtn
14755 (mapconcat 'identity current ":")
14756 nil))))
14758 (defun org-get-tags-string ()
14759 "Get the TAGS string in the current headline."
14760 (unless (org-at-heading-p t)
14761 (error "Not on a heading"))
14762 (save-excursion
14763 (beginning-of-line 1)
14764 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14765 (org-match-string-no-properties 1)
14766 "")))
14768 (defun org-get-tags ()
14769 "Get the list of tags specified in the current headline."
14770 (org-split-string (org-get-tags-string) ":"))
14772 (defun org-get-buffer-tags ()
14773 "Get a table of all tags used in the buffer, for completion."
14774 (let (tags)
14775 (save-excursion
14776 (goto-char (point-min))
14777 (while (re-search-forward
14778 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14779 (when (equal (char-after (point-at-bol 0)) ?*)
14780 (mapc (lambda (x) (add-to-list 'tags x))
14781 (org-split-string (org-match-string-no-properties 1) ":")))))
14782 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14783 (mapcar 'list tags)))
14785 ;;;; The mapping API
14787 (defun org-map-entries (func &optional match scope &rest skip)
14788 "Call FUNC at each headline selected by MATCH in SCOPE.
14790 FUNC is a function or a lisp form. The function will be called without
14791 arguments, with the cursor positioned at the beginning of the headline.
14792 The return values of all calls to the function will be collected and
14793 returned as a list.
14795 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14796 does not need to preserve point. After evaluation, the cursor will be
14797 moved to the end of the line (presumably of the headline of the
14798 processed entry) and search continues from there. Under some
14799 circumstances, this may not produce the wanted results. For example,
14800 if you have removed (e.g. archived) the current (sub)tree it could
14801 mean that the next entry will be skipped entirely. In such cases, you
14802 can specify the position from where search should continue by making
14803 FUNC set the variable `org-map-continue-from' to the desired buffer
14804 position.
14806 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14807 Only headlines that are matched by this query will be considered during
14808 the iteration. When MATCH is nil or t, all headlines will be
14809 visited by the iteration.
14811 SCOPE determines the scope of this command. It can be any of:
14813 nil The current buffer, respecting the restriction if any
14814 tree The subtree started with the entry at point
14815 region The entries within the active region, if any
14816 region-start-level
14817 The entries within the active region, but only those at
14818 the same level than the first one.
14819 file The current buffer, without restriction
14820 file-with-archives
14821 The current buffer, and any archives associated with it
14822 agenda All agenda files
14823 agenda-with-archives
14824 All agenda files with any archive files associated with them
14825 \(file1 file2 ...)
14826 If this is a list, all files in the list will be scanned
14828 The remaining args are treated as settings for the skipping facilities of
14829 the scanner. The following items can be given here:
14831 archive skip trees with the archive tag
14832 comment skip trees with the COMMENT keyword
14833 function or Emacs Lisp form:
14834 will be used as value for `org-agenda-skip-function', so
14835 whenever the function returns a position, FUNC will not be
14836 called for that entry and search will continue from the
14837 position returned
14839 If your function needs to retrieve the tags including inherited tags
14840 at the *current* entry, you can use the value of the variable
14841 `org-scanner-tags' which will be much faster than getting the value
14842 with `org-get-tags-at'. If your function gets properties with
14843 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14844 to t around the call to `org-entry-properties' to get the same speedup.
14845 Note that if your function moves around to retrieve tags and properties at
14846 a *different* entry, you cannot use these techniques."
14847 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14848 (not (org-region-active-p)))
14849 (let* ((org-agenda-archives-mode nil) ; just to make sure
14850 (org-agenda-skip-archived-trees (memq 'archive skip))
14851 (org-agenda-skip-comment-trees (memq 'comment skip))
14852 (org-agenda-skip-function
14853 (car (org-delete-all '(comment archive) skip)))
14854 (org-tags-match-list-sublevels t)
14855 (start-level (eq scope 'region-start-level))
14856 matcher file res
14857 org-todo-keywords-for-agenda
14858 org-done-keywords-for-agenda
14859 org-todo-keyword-alist-for-agenda
14860 org-drawers-for-agenda
14861 org-tag-alist-for-agenda
14862 todo-only)
14864 (cond
14865 ((eq match t) (setq matcher t))
14866 ((eq match nil) (setq matcher t))
14867 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14869 (save-window-excursion
14870 (save-restriction
14871 (cond ((eq scope 'tree)
14872 (org-back-to-heading t)
14873 (org-narrow-to-subtree)
14874 (setq scope nil))
14875 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14876 (org-region-active-p))
14877 ;; If needed, set start-level to a string like "2"
14878 (when start-level
14879 (save-excursion
14880 (goto-char (region-beginning))
14881 (unless (org-at-heading-p) (outline-next-heading))
14882 (setq start-level (org-current-level))))
14883 (narrow-to-region (region-beginning)
14884 (save-excursion
14885 (goto-char (region-end))
14886 (unless (and (bolp) (org-at-heading-p))
14887 (outline-next-heading))
14888 (point)))
14889 (setq scope nil)))
14891 (if (not scope)
14892 (progn
14893 (org-agenda-prepare-buffers
14894 (list (buffer-file-name (current-buffer))))
14895 (setq res (org-scan-tags func matcher todo-only start-level)))
14896 ;; Get the right scope
14897 (cond
14898 ((and scope (listp scope) (symbolp (car scope)))
14899 (setq scope (eval scope)))
14900 ((eq scope 'agenda)
14901 (setq scope (org-agenda-files t)))
14902 ((eq scope 'agenda-with-archives)
14903 (setq scope (org-agenda-files t))
14904 (setq scope (org-add-archive-files scope)))
14905 ((eq scope 'file)
14906 (setq scope (list (buffer-file-name))))
14907 ((eq scope 'file-with-archives)
14908 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14909 (org-agenda-prepare-buffers scope)
14910 (while (setq file (pop scope))
14911 (with-current-buffer (org-find-base-buffer-visiting file)
14912 (save-excursion
14913 (save-restriction
14914 (widen)
14915 (goto-char (point-min))
14916 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14917 res)))
14919 ;;;; Properties
14921 ;;; Setting and retrieving properties
14923 (defconst org-special-properties
14924 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14925 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14926 "The special properties valid in Org-mode.
14928 These are properties that are not defined in the property drawer,
14929 but in some other way.")
14931 (defconst org-default-properties
14932 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14933 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14934 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14935 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14936 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14937 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14938 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14939 "Some properties that are used by Org-mode for various purposes.
14940 Being in this list makes sure that they are offered for completion.")
14942 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14943 "Regular expression matching the first line of a property drawer.")
14945 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14946 "Regular expression matching the last line of a property drawer.")
14948 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14949 "Regular expression matching the first line of a property drawer.")
14951 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14952 "Regular expression matching the first line of a property drawer.")
14954 (defconst org-property-drawer-re
14955 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14956 org-property-end-re "\\)\n?")
14957 "Matches an entire property drawer.")
14959 (defconst org-clock-drawer-re
14960 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14961 org-property-end-re "\\)\n?")
14962 "Matches an entire clock drawer.")
14964 (defsubst org-re-property (property)
14965 "Return a regexp matching a PROPERTY line.
14966 Match group 1 will be set to the value."
14967 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14969 (defsubst org-re-property-keyword (property)
14970 "Return a regexp matching a PROPERTY line, possibly with no
14971 value for the property."
14972 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14974 (defun org-property-action ()
14975 "Do an action on properties."
14976 (interactive)
14977 (let (c)
14978 (org-at-property-p)
14979 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14980 (setq c (read-char-exclusive))
14981 (cond
14982 ((equal c ?s)
14983 (call-interactively 'org-set-property))
14984 ((equal c ?d)
14985 (call-interactively 'org-delete-property))
14986 ((equal c ?D)
14987 (call-interactively 'org-delete-property-globally))
14988 ((equal c ?c)
14989 (call-interactively 'org-compute-property-at-point))
14990 (t (error "No such property action %c" c)))))
14992 (defun org-inc-effort ()
14993 "Increment the value of the effort property in the current entry."
14994 (interactive)
14995 (org-set-effort nil t))
14997 (defvar org-clock-effort) ;; Defined in org-clock.el
14998 (defvar org-clock-current-task) ;; Defined in org-clock.el
14999 (defun org-set-effort (&optional value increment)
15000 "Set the effort property of the current entry.
15001 With numerical prefix arg, use the nth allowed value, 0 stands for the
15002 10th allowed value.
15004 When INCREMENT is non-nil, set the property to the next allowed value."
15005 (interactive "P")
15006 (if (equal value 0) (setq value 10))
15007 (let* ((completion-ignore-case t)
15008 (prop org-effort-property)
15009 (cur (org-entry-get nil prop))
15010 (allowed (org-property-get-allowed-values nil prop 'table))
15011 (existing (mapcar 'list (org-property-values prop)))
15012 (heading (nth 4 (org-heading-components)))
15014 (val (cond
15015 ((stringp value) value)
15016 ((and allowed (integerp value))
15017 (or (car (nth (1- value) allowed))
15018 (car (org-last allowed))))
15019 ((and allowed increment)
15020 (or (caadr (member (list cur) allowed))
15021 (error "Allowed effort values are not set")))
15022 (allowed
15023 (message "Select 1-9,0, [RET%s]: %s"
15024 (if cur (concat "=" cur) "")
15025 (mapconcat 'car allowed " "))
15026 (setq rpl (read-char-exclusive))
15027 (if (equal rpl ?\r)
15029 (setq rpl (- rpl ?0))
15030 (if (equal rpl 0) (setq rpl 10))
15031 (if (and (> rpl 0) (<= rpl (length allowed)))
15032 (car (nth (1- rpl) allowed))
15033 (org-completing-read "Effort: " allowed nil))))
15035 (let (org-completion-use-ido org-completion-use-iswitchb)
15036 (org-completing-read
15037 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15038 (concat "[" cur "]") "")
15039 ": ")
15040 existing nil nil "" nil cur))))))
15041 (unless (equal (org-entry-get nil prop) val)
15042 (org-entry-put nil prop val))
15043 (save-excursion
15044 (org-back-to-heading t)
15045 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15046 (when (string= heading org-clock-current-task)
15047 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15048 (org-clock-update-mode-line))
15049 (message "%s is now %s" prop val)))
15051 (defun org-at-property-p ()
15052 "Is cursor inside a property drawer?"
15053 (save-excursion
15054 (beginning-of-line 1)
15055 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15056 (save-match-data ;; Used by calling procedures
15057 (let ((p (point))
15058 (range (unless (org-before-first-heading-p)
15059 (org-get-property-block))))
15060 (and range (<= (car range) p) (< p (cdr range))))))))
15062 (defun org-get-property-block (&optional beg end force)
15063 "Return the (beg . end) range of the body of the property drawer.
15064 BEG and END are the beginning and end of the current subtree, or of
15065 the part before the first headline. If they are not given, they will
15066 be found. If the drawer does not exist and FORCE is non-nil, create
15067 the drawer."
15068 (catch 'exit
15069 (save-excursion
15070 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15071 (progn (org-back-to-heading t) (point))))
15072 (end (or end (and (not (outline-next-heading)) (point-max))
15073 (point))))
15074 (goto-char beg)
15075 (if (re-search-forward org-property-start-re end t)
15076 (setq beg (1+ (match-end 0)))
15077 (if force
15078 (save-excursion
15079 (org-insert-property-drawer)
15080 (setq end (progn (outline-next-heading) (point))))
15081 (throw 'exit nil))
15082 (goto-char beg)
15083 (if (re-search-forward org-property-start-re end t)
15084 (setq beg (1+ (match-end 0)))))
15085 (if (re-search-forward org-property-end-re end t)
15086 (setq end (match-beginning 0))
15087 (or force (throw 'exit nil))
15088 (goto-char beg)
15089 (setq end beg)
15090 (org-indent-line)
15091 (insert ":END:\n"))
15092 (cons beg end)))))
15094 (defun org-entry-properties (&optional pom which specific)
15095 "Get all properties of the entry at point-or-marker POM.
15096 This includes the TODO keyword, the tags, time strings for deadline,
15097 scheduled, and clocking, and any additional properties defined in the
15098 entry. The return value is an alist, keys may occur multiple times
15099 if the property key was used several times.
15100 POM may also be nil, in which case the current entry is used.
15101 If WHICH is nil or `all', get all properties. If WHICH is
15102 `special' or `standard', only get that subclass. If WHICH
15103 is a string only get exactly this property. SPECIFIC can be a string, the
15104 specific property we are interested in. Specifying it can speed
15105 things up because then unnecessary parsing is avoided."
15106 (setq which (or which 'all))
15107 (org-with-point-at pom
15108 (let ((clockstr (substring org-clock-string 0 -1))
15109 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15110 (case-fold-search nil)
15111 beg end range props sum-props key key1 value string clocksum clocksumt)
15112 (save-excursion
15113 (when (condition-case nil
15114 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15115 (error nil))
15116 (setq beg (point))
15117 (setq sum-props (get-text-property (point) 'org-summaries))
15118 (setq clocksum (get-text-property (point) :org-clock-minutes)
15119 clocksumt (get-text-property (point) :org-clock-minutes-today))
15120 (outline-next-heading)
15121 (setq end (point))
15122 (when (memq which '(all special))
15123 ;; Get the special properties, like TODO and tags
15124 (goto-char beg)
15125 (when (and (or (not specific) (string= specific "TODO"))
15126 (looking-at org-todo-line-regexp) (match-end 2))
15127 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15128 (when (and (or (not specific) (string= specific "PRIORITY"))
15129 (looking-at org-priority-regexp))
15130 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15131 (when (or (not specific) (string= specific "FILE"))
15132 (push (cons "FILE" buffer-file-name) props))
15133 (when (and (or (not specific) (string= specific "TAGS"))
15134 (setq value (org-get-tags-string))
15135 (string-match "\\S-" value))
15136 (push (cons "TAGS" value) props))
15137 (when (and (or (not specific) (string= specific "ALLTAGS"))
15138 (setq value (org-get-tags-at)))
15139 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15140 ":"))
15141 props))
15142 (when (or (not specific) (string= specific "BLOCKED"))
15143 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15144 (when (or (not specific)
15145 (member specific
15146 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15147 "TIMESTAMP" "TIMESTAMP_IA")))
15148 (catch 'match
15149 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15150 (setq key (if (match-end 1)
15151 (substring (org-match-string-no-properties 1)
15152 0 -1))
15153 string (if (equal key clockstr)
15154 (org-trim
15155 (buffer-substring-no-properties
15156 (match-beginning 3) (goto-char
15157 (point-at-eol))))
15158 (substring (org-match-string-no-properties 3)
15159 1 -1)))
15160 ;; Get the correct property name from the key. This is
15161 ;; necessary if the user has configured time keywords.
15162 (setq key1 (concat key ":"))
15163 (cond
15164 ((not key)
15165 (setq key
15166 (if (= (char-after (match-beginning 3)) ?\[)
15167 "TIMESTAMP_IA" "TIMESTAMP")))
15168 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15169 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15170 ((equal key1 org-closed-string) (setq key "CLOSED"))
15171 ((equal key1 org-clock-string) (setq key "CLOCK")))
15172 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15173 (progn
15174 (push (cons key string) props)
15175 ;; no need to search further if match is found
15176 (throw 'match t))
15177 (when (or (equal key "CLOCK") (not (assoc key props)))
15178 (push (cons key string) props)))))))
15180 (when (memq which '(all standard))
15181 ;; Get the standard properties, like :PROP: ...
15182 (setq range (org-get-property-block beg end))
15183 (when range
15184 (goto-char (car range))
15185 (while (re-search-forward
15186 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15187 (cdr range) t)
15188 (setq key (org-match-string-no-properties 1)
15189 value (org-trim (or (org-match-string-no-properties 2) "")))
15190 (unless (member key excluded)
15191 (push (cons key (or value "")) props)))))
15192 (if clocksum
15193 (push (cons "CLOCKSUM"
15194 (org-columns-number-to-string (/ (float clocksum) 60.)
15195 'add_times))
15196 props))
15197 (if clocksumt
15198 (push (cons "CLOCKSUM_T"
15199 (org-columns-number-to-string (/ (float clocksumt) 60.)
15200 'add_times))
15201 props))
15202 (unless (assoc "CATEGORY" props)
15203 (push (cons "CATEGORY" (org-get-category)) props))
15204 (append sum-props (nreverse props)))))))
15206 (defun org-entry-get (pom property &optional inherit literal-nil)
15207 "Get value of PROPERTY for entry or content at point-or-marker POM.
15208 If INHERIT is non-nil and the entry does not have the property,
15209 then also check higher levels of the hierarchy.
15210 If INHERIT is the symbol `selective', use inheritance only if the setting
15211 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15212 If the property is present but empty, the return value is the empty string.
15213 If the property is not present at all, nil is returned.
15215 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15216 do not interpret it as the list atom nil. This is used for inheritance
15217 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15218 (org-with-point-at pom
15219 (if (and inherit (if (eq inherit 'selective)
15220 (org-property-inherit-p property)
15222 (org-entry-get-with-inheritance property literal-nil)
15223 (if (member property org-special-properties)
15224 ;; We need a special property. Use `org-entry-properties' to
15225 ;; retrieve it, but specify the wanted property
15226 (cdr (assoc property (org-entry-properties nil 'special property)))
15227 (let ((range (org-get-property-block)))
15228 (when (and range (not (eq (car range) (cdr range))))
15229 (let* ((props (list (or (assoc property org-file-properties)
15230 (assoc property org-global-properties)
15231 (assoc property org-global-properties-fixed))))
15232 (ap (lambda (key)
15233 (when (re-search-forward
15234 (org-re-property key) (cdr range) t)
15235 (setq props
15236 (org-update-property-plist
15238 (if (match-end 1)
15239 (org-match-string-no-properties 1) "")
15240 props)))))
15241 val)
15242 (goto-char (car range))
15243 (funcall ap property)
15244 (goto-char (car range))
15245 (while (funcall ap (concat property "+")))
15246 (setq val (cdr (assoc property props)))
15247 (when val (if literal-nil val (org-not-nil val))))))))))
15249 (defun org-property-or-variable-value (var &optional inherit)
15250 "Check if there is a property fixing the value of VAR.
15251 If yes, return this value. If not, return the current value of the variable."
15252 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15253 (if (and prop (stringp prop) (string-match "\\S-" prop))
15254 (read prop)
15255 (symbol-value var))))
15257 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15258 "Delete the property PROPERTY from entry at point-or-marker POM.
15259 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15260 an empty drawer to delete."
15261 (org-with-point-at pom
15262 (if (member property org-special-properties)
15263 nil ; cannot delete these properties.
15264 (let ((range (org-get-property-block)))
15265 (if (and range
15266 (goto-char (car range))
15267 (re-search-forward
15268 (org-re-property property)
15269 (cdr range) t))
15270 (progn
15271 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15272 (and delete-empty-drawer
15273 (org-remove-empty-drawer-at
15274 delete-empty-drawer (car range)))
15276 nil)))))
15278 ;; Multi-values properties are properties that contain multiple values
15279 ;; These values are assumed to be single words, separated by whitespace.
15280 (defun org-entry-add-to-multivalued-property (pom property value)
15281 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15282 (let* ((old (org-entry-get pom property))
15283 (values (and old (org-split-string old "[ \t]"))))
15284 (setq value (org-entry-protect-space value))
15285 (unless (member value values)
15286 (setq values (append values (list value)))
15287 (org-entry-put pom property
15288 (mapconcat 'identity values " ")))))
15290 (defun org-entry-remove-from-multivalued-property (pom property value)
15291 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15292 (let* ((old (org-entry-get pom property))
15293 (values (and old (org-split-string old "[ \t]"))))
15294 (setq value (org-entry-protect-space value))
15295 (when (member value values)
15296 (setq values (delete value values))
15297 (org-entry-put pom property
15298 (mapconcat 'identity values " ")))))
15300 (defun org-entry-member-in-multivalued-property (pom property value)
15301 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15302 (let* ((old (org-entry-get pom property))
15303 (values (and old (org-split-string old "[ \t]"))))
15304 (setq value (org-entry-protect-space value))
15305 (member value values)))
15307 (defun org-entry-get-multivalued-property (pom property)
15308 "Return a list of values in a multivalued property."
15309 (let* ((value (org-entry-get pom property))
15310 (values (and value (org-split-string value "[ \t]"))))
15311 (mapcar 'org-entry-restore-space values)))
15313 (defun org-entry-put-multivalued-property (pom property &rest values)
15314 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15315 VALUES should be a list of strings. Spaces will be protected."
15316 (org-entry-put pom property
15317 (mapconcat 'org-entry-protect-space values " "))
15318 (let* ((value (org-entry-get pom property))
15319 (values (and value (org-split-string value "[ \t]"))))
15320 (mapcar 'org-entry-restore-space values)))
15322 (defun org-entry-protect-space (s)
15323 "Protect spaces and newline in string S."
15324 (while (string-match " " s)
15325 (setq s (replace-match "%20" t t s)))
15326 (while (string-match "\n" s)
15327 (setq s (replace-match "%0A" t t s)))
15330 (defun org-entry-restore-space (s)
15331 "Restore spaces and newline in string S."
15332 (while (string-match "%20" s)
15333 (setq s (replace-match " " t t s)))
15334 (while (string-match "%0A" s)
15335 (setq s (replace-match "\n" t t s)))
15338 (defvar org-entry-property-inherited-from (make-marker)
15339 "Marker pointing to the entry from where a property was inherited.
15340 Each call to `org-entry-get-with-inheritance' will set this marker to the
15341 location of the entry where the inheritance search matched. If there was
15342 no match, the marker will point nowhere.
15343 Note that also `org-entry-get' calls this function, if the INHERIT flag
15344 is set.")
15346 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15347 "Get PROPERTY of entry or content at point, search higher levels if needed.
15348 The search will stop at the first ancestor which has the property defined.
15349 If the value found is \"nil\", return nil to show that the property
15350 should be considered as undefined (this is the meaning of nil here).
15351 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15352 (move-marker org-entry-property-inherited-from nil)
15353 (let (tmp)
15354 (save-excursion
15355 (save-restriction
15356 (widen)
15357 (catch 'ex
15358 (while t
15359 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15360 (or (ignore-errors (org-back-to-heading t))
15361 (goto-char (point-min)))
15362 (move-marker org-entry-property-inherited-from (point))
15363 (throw 'ex tmp))
15364 (or (ignore-errors (org-up-heading-safe))
15365 (throw 'ex nil))))))
15366 (setq tmp (or tmp
15367 (cdr (assoc property org-file-properties))
15368 (cdr (assoc property org-global-properties))
15369 (cdr (assoc property org-global-properties-fixed))))
15370 (if literal-nil tmp (org-not-nil tmp))))
15372 (defvar org-property-changed-functions nil
15373 "Hook called when the value of a property has changed.
15374 Each hook function should accept two arguments, the name of the property
15375 and the new value.")
15377 (defun org-entry-put (pom property value)
15378 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15379 (org-with-point-at pom
15380 (org-back-to-heading t)
15381 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15382 range)
15383 (cond
15384 ((equal property "TODO")
15385 (when (and (stringp value) (string-match "\\S-" value)
15386 (not (member value org-todo-keywords-1)))
15387 (error "\"%s\" is not a valid TODO state" value))
15388 (if (or (not value)
15389 (not (string-match "\\S-" value)))
15390 (setq value 'none))
15391 (org-todo value)
15392 (org-set-tags nil 'align))
15393 ((equal property "PRIORITY")
15394 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15395 (string-to-char value) ?\ ))
15396 (org-set-tags nil 'align))
15397 ((equal property "CLOCKSUM")
15398 (if (not (re-search-forward
15399 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15400 (error "Cannot find a clock log")
15401 (goto-char (- (match-end 1) 2))
15402 (cond
15403 ((eq value 'earlier) (org-timestamp-down))
15404 ((eq value 'later) (org-timestamp-up)))
15405 (org-clock-sum-current-item)))
15406 ((equal property "SCHEDULED")
15407 (if (re-search-forward org-scheduled-time-regexp end t)
15408 (cond
15409 ((eq value 'earlier) (org-timestamp-change -1 'day))
15410 ((eq value 'later) (org-timestamp-change 1 'day))
15411 (t (call-interactively 'org-schedule)))
15412 (call-interactively 'org-schedule)))
15413 ((equal property "DEADLINE")
15414 (if (re-search-forward org-deadline-time-regexp end t)
15415 (cond
15416 ((eq value 'earlier) (org-timestamp-change -1 'day))
15417 ((eq value 'later) (org-timestamp-change 1 'day))
15418 (t (call-interactively 'org-deadline)))
15419 (call-interactively 'org-deadline)))
15420 ((member property org-special-properties)
15421 (error "The %s property can not yet be set with `org-entry-put'"
15422 property))
15423 (t ; a non-special property
15424 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15425 (setq range (org-get-property-block beg end 'force))
15426 (goto-char (car range))
15427 (if (re-search-forward
15428 (org-re-property-keyword property) (cdr range) t)
15429 (progn
15430 (delete-region (match-beginning 0) (match-end 0))
15431 (goto-char (match-beginning 0)))
15432 (goto-char (cdr range))
15433 (insert "\n")
15434 (backward-char 1)
15435 (org-indent-line))
15436 (insert ":" property ":")
15437 (and value (insert " " value))
15438 (org-indent-line)))))
15439 (run-hook-with-args 'org-property-changed-functions property value)))
15441 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15442 "Get all property keys in the current buffer.
15443 With INCLUDE-SPECIALS, also list the special properties that reflect things
15444 like tags and TODO state.
15445 With INCLUDE-DEFAULTS, also include properties that has special meaning
15446 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15447 and others.
15448 With INCLUDE-COLUMNS, also include property names given in COLUMN
15449 formats in the current buffer."
15450 (let (rtn range cfmt s p)
15451 (save-excursion
15452 (save-restriction
15453 (widen)
15454 (goto-char (point-min))
15455 (while (re-search-forward org-property-start-re nil t)
15456 (setq range (org-get-property-block))
15457 (goto-char (car range))
15458 (while (re-search-forward
15459 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15460 (cdr range) t)
15461 (add-to-list 'rtn (org-match-string-no-properties 1)))
15462 (outline-next-heading))))
15464 (when include-specials
15465 (setq rtn (append org-special-properties rtn)))
15467 (when include-defaults
15468 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15469 (add-to-list 'rtn org-effort-property))
15471 (when include-columns
15472 (save-excursion
15473 (save-restriction
15474 (widen)
15475 (goto-char (point-min))
15476 (while (re-search-forward
15477 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15478 nil t)
15479 (setq cfmt (match-string 2) s 0)
15480 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15481 cfmt s)
15482 (setq s (match-end 0)
15483 p (match-string 1 cfmt))
15484 (unless (or (equal p "ITEM")
15485 (member p org-special-properties))
15486 (add-to-list 'rtn (match-string 1 cfmt))))))))
15488 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15490 (defun org-property-values (key)
15491 "Return a list of all values of property KEY in the current buffer."
15492 (save-excursion
15493 (save-restriction
15494 (widen)
15495 (goto-char (point-min))
15496 (let ((re (org-re-property key))
15497 values)
15498 (while (re-search-forward re nil t)
15499 (add-to-list 'values (org-trim (match-string 1))))
15500 (delete "" values)))))
15502 (defun org-insert-property-drawer ()
15503 "Insert a property drawer into the current entry."
15504 (org-back-to-heading t)
15505 (looking-at org-outline-regexp)
15506 (let ((indent (if org-adapt-indentation
15507 (- (match-end 0) (match-beginning 0))
15509 (beg (point))
15510 (re (concat "^[ \t]*" org-keyword-time-regexp))
15511 end hiddenp)
15512 (outline-next-heading)
15513 (setq end (point))
15514 (goto-char beg)
15515 (while (re-search-forward re end t))
15516 (setq hiddenp (outline-invisible-p))
15517 (end-of-line 1)
15518 (and (equal (char-after) ?\n) (forward-char 1))
15519 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15520 (if (member (match-string 1) '("CLOCK:" ":END:"))
15521 ;; just skip this line
15522 (beginning-of-line 2)
15523 ;; Drawer start, find the end
15524 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15525 (beginning-of-line 1)))
15526 (org-skip-over-state-notes)
15527 (skip-chars-backward " \t\n\r")
15528 (if (eq (char-before) ?*) (forward-char 1))
15529 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15530 (beginning-of-line 0)
15531 (org-indent-to-column indent)
15532 (beginning-of-line 2)
15533 (org-indent-to-column indent)
15534 (beginning-of-line 0)
15535 (if hiddenp
15536 (save-excursion
15537 (org-back-to-heading t)
15538 (hide-entry))
15539 (org-flag-drawer t))))
15541 (defun org-insert-drawer (&optional arg drawer)
15542 "Insert a drawer at point.
15544 Optional argument DRAWER, when non-nil, is a string representing
15545 drawer's name. Otherwise, the user is prompted for a name.
15547 If a region is active, insert the drawer around that region
15548 instead.
15550 Point is left between drawer's boundaries."
15551 (interactive "P")
15552 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15553 "LOGBOOK"))
15554 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15555 ;; internally by Org. They are meant to be inserted
15556 ;; automatically.
15557 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15558 ;; Remove system drawers from list. Note: For some reason,
15559 ;; `org-completing-read' ignores the predicate while
15560 ;; `completing-read' handles it fine.
15561 (drawer (if arg "PROPERTIES"
15562 (or drawer
15563 (completing-read
15564 "Drawer: " org-drawers
15565 (lambda (d) (not (member d system-drawers))))))))
15566 (cond
15567 ;; With C-u, fall back on `org-insert-property-drawer'
15568 (arg (org-insert-property-drawer))
15569 ;; With an active region, insert a drawer at point.
15570 ((not (org-region-active-p))
15571 (progn
15572 (unless (bolp) (insert "\n"))
15573 (insert (format ":%s:\n\n:END:\n" drawer))
15574 (forward-line -2)))
15575 ;; Otherwise, insert the drawer at point
15577 (let ((rbeg (region-beginning))
15578 (rend (copy-marker (region-end))))
15579 (unwind-protect
15580 (progn
15581 (goto-char rbeg)
15582 (beginning-of-line)
15583 (when (save-excursion
15584 (re-search-forward org-outline-regexp-bol rend t))
15585 (error "Drawers cannot contain headlines"))
15586 ;; Position point at the beginning of the first
15587 ;; non-blank line in region. Insert drawer's opening
15588 ;; there, then indent it.
15589 (org-skip-whitespace)
15590 (beginning-of-line)
15591 (insert ":" drawer ":\n")
15592 (forward-line -1)
15593 (indent-for-tab-command)
15594 ;; Move point to the beginning of the first blank line
15595 ;; after the last non-blank line in region. Insert
15596 ;; drawer's closing, then indent it.
15597 (goto-char rend)
15598 (skip-chars-backward " \r\t\n")
15599 (insert "\n:END:")
15600 (deactivate-mark t)
15601 (indent-for-tab-command)
15602 (unless (eolp) (insert "\n")))
15603 ;; Clear marker, whatever the outcome of insertion is.
15604 (set-marker rend nil)))))))
15606 (defvar org-property-set-functions-alist nil
15607 "Property set function alist.
15608 Each entry should have the following format:
15610 (PROPERTY . READ-FUNCTION)
15612 The read function will be called with the same argument as
15613 `org-completing-read'.")
15615 (defun org-set-property-function (property)
15616 "Get the function that should be used to set PROPERTY.
15617 This is computed according to `org-property-set-functions-alist'."
15618 (or (cdr (assoc property org-property-set-functions-alist))
15619 'org-completing-read))
15621 (defun org-read-property-value (property)
15622 "Read PROPERTY value from user."
15623 (let* ((completion-ignore-case t)
15624 (allowed (org-property-get-allowed-values nil property 'table))
15625 (cur (org-entry-get nil property))
15626 (prompt (concat property " value"
15627 (if (and cur (string-match "\\S-" cur))
15628 (concat " [" cur "]") "") ": "))
15629 (set-function (org-set-property-function property))
15630 (val (if allowed
15631 (funcall set-function prompt allowed nil
15632 (not (get-text-property 0 'org-unrestricted
15633 (caar allowed))))
15634 (let (org-completion-use-ido org-completion-use-iswitchb)
15635 (funcall set-function prompt
15636 (mapcar 'list (org-property-values property))
15637 nil nil "" nil cur)))))
15638 (if (equal val "")
15640 val)))
15642 (defvar org-last-set-property nil)
15643 (defvar org-last-set-property-value nil)
15644 (defun org-read-property-name ()
15645 "Read a property name."
15646 (let* ((completion-ignore-case t)
15647 (keys (org-buffer-property-keys nil t t))
15648 (default-prop (or (save-excursion
15649 (save-match-data
15650 (beginning-of-line)
15651 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15652 (null (string= (match-string 1) "END"))
15653 (match-string 1))))
15654 org-last-set-property))
15655 (property (org-icompleting-read
15656 (concat "Property"
15657 (if default-prop (concat " [" default-prop "]") "")
15658 ": ")
15659 (mapcar 'list keys)
15660 nil nil nil nil
15661 default-prop)))
15662 (if (member property keys)
15663 property
15664 (or (cdr (assoc (downcase property)
15665 (mapcar (lambda (x) (cons (downcase x) x))
15666 keys)))
15667 property))))
15669 (defun org-set-property-and-value (use-last)
15670 "Allow to set [PROPERTY]: [value] direction from prompt.
15671 When use-default, don't even ask, just use the last
15672 \"[PROPERTY]: [value]\" string from the history."
15673 (interactive "P")
15674 (let* ((completion-ignore-case t)
15675 (pv (or (and use-last org-last-set-property-value)
15676 (org-completing-read
15677 "Enter a \"[Property]: [value]\" pair: "
15678 nil nil nil nil nil
15679 org-last-set-property-value)))
15680 prop val)
15681 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15682 (setq prop (match-string 1 pv)
15683 val (match-string 2 pv))
15684 (org-set-property prop val))))
15686 (defun org-set-property (property value)
15687 "In the current entry, set PROPERTY to VALUE.
15688 When called interactively, this will prompt for a property name, offering
15689 completion on existing and default properties. And then it will prompt
15690 for a value, offering completion either on allowed values (via an inherited
15691 xxx_ALL property) or on existing values in other instances of this property
15692 in the current file."
15693 (interactive (list nil nil))
15694 (let* ((property (or property (org-read-property-name)))
15695 (value (or value (org-read-property-value property)))
15696 (fn (cdr (assoc property org-properties-postprocess-alist))))
15697 (setq org-last-set-property property)
15698 (setq org-last-set-property-value (concat property ": " value))
15699 ;; Possibly postprocess the inserted value:
15700 (when fn (setq value (funcall fn value)))
15701 (unless (equal (org-entry-get nil property) value)
15702 (org-entry-put nil property value))))
15704 (defun org-delete-property (property &optional delete-empty-drawer)
15705 "In the current entry, delete PROPERTY.
15706 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15707 an empty drawer to delete."
15708 (interactive
15709 (let* ((completion-ignore-case t)
15710 (prop (org-icompleting-read "Property: "
15711 (org-entry-properties nil 'standard))))
15712 (list prop)))
15713 (message "Property %s %s" property
15714 (if (org-entry-delete nil property delete-empty-drawer)
15715 "deleted"
15716 "was not present in the entry")))
15718 (defun org-delete-property-globally (property)
15719 "Remove PROPERTY globally, from all entries."
15720 (interactive
15721 (let* ((completion-ignore-case t)
15722 (prop (org-icompleting-read
15723 "Globally remove property: "
15724 (mapcar 'list (org-buffer-property-keys)))))
15725 (list prop)))
15726 (save-excursion
15727 (save-restriction
15728 (widen)
15729 (goto-char (point-min))
15730 (let ((cnt 0))
15731 (while (re-search-forward
15732 (org-re-property property)
15733 nil t)
15734 (setq cnt (1+ cnt))
15735 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15736 (message "Property \"%s\" removed from %d entries" property cnt)))))
15738 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15740 (defun org-compute-property-at-point ()
15741 "Compute the property at point.
15742 This looks for an enclosing column format, extracts the operator and
15743 then applies it to the property in the column format's scope."
15744 (interactive)
15745 (unless (org-at-property-p)
15746 (error "Not at a property"))
15747 (let ((prop (org-match-string-no-properties 2)))
15748 (org-columns-get-format-and-top-level)
15749 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15750 (error "No operator defined for property %s" prop))
15751 (org-columns-compute prop)))
15753 (defvar org-property-allowed-value-functions nil
15754 "Hook for functions supplying allowed values for a specific property.
15755 The functions must take a single argument, the name of the property, and
15756 return a flat list of allowed values. If \":ETC\" is one of
15757 the values, this means that these values are intended as defaults for
15758 completion, but that other values should be allowed too.
15759 The functions must return nil if they are not responsible for this
15760 property.")
15762 (defun org-property-get-allowed-values (pom property &optional table)
15763 "Get allowed values for the property PROPERTY.
15764 When TABLE is non-nil, return an alist that can directly be used for
15765 completion."
15766 (let (vals)
15767 (cond
15768 ((equal property "TODO")
15769 (setq vals (org-with-point-at pom
15770 (append org-todo-keywords-1 '("")))))
15771 ((equal property "PRIORITY")
15772 (let ((n org-lowest-priority))
15773 (while (>= n org-highest-priority)
15774 (push (char-to-string n) vals)
15775 (setq n (1- n)))))
15776 ((member property org-special-properties))
15777 ((setq vals (run-hook-with-args-until-success
15778 'org-property-allowed-value-functions property)))
15780 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15781 (when (and vals (string-match "\\S-" vals))
15782 (setq vals (car (read-from-string (concat "(" vals ")"))))
15783 (setq vals (mapcar (lambda (x)
15784 (cond ((stringp x) x)
15785 ((numberp x) (number-to-string x))
15786 ((symbolp x) (symbol-name x))
15787 (t "???")))
15788 vals)))))
15789 (when (member ":ETC" vals)
15790 (setq vals (remove ":ETC" vals))
15791 (org-add-props (car vals) '(org-unrestricted t)))
15792 (if table (mapcar 'list vals) vals)))
15794 (defun org-property-previous-allowed-value (&optional previous)
15795 "Switch to the next allowed value for this property."
15796 (interactive)
15797 (org-property-next-allowed-value t))
15799 (defun org-property-next-allowed-value (&optional previous)
15800 "Switch to the next allowed value for this property."
15801 (interactive)
15802 (unless (org-at-property-p)
15803 (error "Not at a property"))
15804 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15805 (key (match-string 2))
15806 (value (match-string 3))
15807 (allowed (or (org-property-get-allowed-values (point) key)
15808 (and (member value '("[ ]" "[-]" "[X]"))
15809 '("[ ]" "[X]"))))
15810 (heading (save-match-data (nth 4 (org-heading-components))))
15811 nval)
15812 (unless allowed
15813 (error "Allowed values for this property have not been defined"))
15814 (if previous (setq allowed (reverse allowed)))
15815 (if (member value allowed)
15816 (setq nval (car (cdr (member value allowed)))))
15817 (setq nval (or nval (car allowed)))
15818 (if (equal nval value)
15819 (error "Only one allowed value for this property"))
15820 (org-at-property-p)
15821 (replace-match (concat " :" key ": " nval) t t)
15822 (org-indent-line)
15823 (beginning-of-line 1)
15824 (skip-chars-forward " \t")
15825 (when (equal prop org-effort-property)
15826 (save-excursion
15827 (org-back-to-heading t)
15828 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15829 (when (string= org-clock-current-task heading)
15830 (setq org-clock-effort nval)
15831 (org-clock-update-mode-line)))
15832 (run-hook-with-args 'org-property-changed-functions key nval)))
15834 (defun org-find-olp (path &optional this-buffer)
15835 "Return a marker pointing to the entry at outline path OLP.
15836 If anything goes wrong, throw an error.
15837 You can wrap this call to catch the error like this:
15839 (condition-case msg
15840 (org-mobile-locate-entry (match-string 4))
15841 (error (nth 1 msg)))
15843 The return value will then be either a string with the error message,
15844 or a marker if everything is OK.
15846 If THIS-BUFFER is set, the outline path does not contain a file,
15847 only headings."
15848 (let* ((file (if this-buffer buffer-file-name (pop path)))
15849 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15850 (level 1)
15851 (lmin 1)
15852 (lmax 1)
15853 limit re end found pos heading cnt flevel)
15854 (unless buffer (error "File not found :%s" file))
15855 (with-current-buffer buffer
15856 (save-excursion
15857 (save-restriction
15858 (widen)
15859 (setq limit (point-max))
15860 (goto-char (point-min))
15861 (while (setq heading (pop path))
15862 (setq re (format org-complex-heading-regexp-format
15863 (regexp-quote heading)))
15864 (setq cnt 0 pos (point))
15865 (while (re-search-forward re end t)
15866 (setq level (- (match-end 1) (match-beginning 1)))
15867 (if (and (>= level lmin) (<= level lmax))
15868 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15869 (when (= cnt 0) (error "Heading not found on level %d: %s"
15870 lmax heading))
15871 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15872 lmax heading))
15873 (goto-char found)
15874 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15875 (setq end (save-excursion (org-end-of-subtree t t))))
15876 (when (org-at-heading-p)
15877 (point-marker)))))))
15879 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15880 "Find node HEADING in BUFFER.
15881 Return a marker to the heading if it was found, or nil if not.
15882 If POS-ONLY is set, return just the position instead of a marker.
15884 The heading text must match exact, but it may have a TODO keyword,
15885 a priority cookie and tags in the standard locations."
15886 (with-current-buffer (or buffer (current-buffer))
15887 (save-excursion
15888 (save-restriction
15889 (widen)
15890 (goto-char (point-min))
15891 (let (case-fold-search)
15892 (if (re-search-forward
15893 (format org-complex-heading-regexp-format
15894 (regexp-quote heading)) nil t)
15895 (if pos-only
15896 (match-beginning 0)
15897 (move-marker (make-marker) (match-beginning 0)))))))))
15899 (defun org-find-exact-heading-in-directory (heading &optional dir)
15900 "Find Org node headline HEADING in all .org files in directory DIR.
15901 When the target headline is found, return a marker to this location."
15902 (let ((files (directory-files (or dir default-directory)
15903 nil "\\`[^.#].*\\.org\\'"))
15904 file visiting m buffer)
15905 (catch 'found
15906 (while (setq file (pop files))
15907 (message "trying %s" file)
15908 (setq visiting (org-find-base-buffer-visiting file))
15909 (setq buffer (or visiting (find-file-noselect file)))
15910 (setq m (org-find-exact-headline-in-buffer
15911 heading buffer))
15912 (when (and (not m) (not visiting)) (kill-buffer buffer))
15913 (and m (throw 'found m))))))
15915 (defun org-find-entry-with-id (ident)
15916 "Locate the entry that contains the ID property with exact value IDENT.
15917 IDENT can be a string, a symbol or a number, this function will search for
15918 the string representation of it.
15919 Return the position where this entry starts, or nil if there is no such entry."
15920 (interactive "sID: ")
15921 (let ((id (cond
15922 ((stringp ident) ident)
15923 ((symbol-name ident) (symbol-name ident))
15924 ((numberp ident) (number-to-string ident))
15925 (t (error "IDENT %s must be a string, symbol or number" ident))))
15926 (case-fold-search nil))
15927 (save-excursion
15928 (save-restriction
15929 (widen)
15930 (goto-char (point-min))
15931 (when (re-search-forward
15932 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15933 nil t)
15934 (org-back-to-heading t)
15935 (point))))))
15937 ;;;; Timestamps
15939 (defvar org-last-changed-timestamp nil)
15940 (defvar org-last-inserted-timestamp nil
15941 "The last time stamp inserted with `org-insert-time-stamp'.")
15942 (defvar org-time-was-given) ; dynamically scoped parameter
15943 (defvar org-end-time-was-given) ; dynamically scoped parameter
15944 (defvar org-ts-what) ; dynamically scoped parameter
15946 (defun org-time-stamp (arg &optional inactive)
15947 "Prompt for a date/time and insert a time stamp.
15948 If the user specifies a time like HH:MM or if this command is
15949 called with at least one prefix argument, the time stamp contains
15950 the date and the time. Otherwise, only the date is be included.
15952 All parts of a date not specified by the user is filled in from
15953 the current date/time. So if you just press return without
15954 typing anything, the time stamp will represent the current
15955 date/time.
15957 If there is already a timestamp at the cursor, it will be
15958 modified.
15960 With two universal prefix arguments, insert an active timestamp
15961 with the current time without prompting the user."
15962 (interactive "P")
15963 (let* ((ts nil)
15964 (default-time
15965 ;; Default time is either today, or, when entering a range,
15966 ;; the range start.
15967 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15968 (save-excursion
15969 (re-search-backward
15970 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15971 (- (point) 20) t)))
15972 (apply 'encode-time (org-parse-time-string (match-string 1)))
15973 (current-time)))
15974 (default-input (and ts (org-get-compact-tod ts)))
15975 (repeater (save-excursion
15976 (save-match-data
15977 (beginning-of-line)
15978 (when (re-search-forward
15979 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15980 (save-excursion (progn (end-of-line) (point))) t)
15981 (match-string 0)))))
15982 org-time-was-given org-end-time-was-given time)
15983 (cond
15984 ((and (org-at-timestamp-p t)
15985 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15986 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15987 (insert "--")
15988 (setq time (let ((this-command this-command))
15989 (org-read-date arg 'totime nil nil
15990 default-time default-input inactive)))
15991 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15992 ((org-at-timestamp-p t)
15993 (setq time (let ((this-command this-command))
15994 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15995 (when (org-at-timestamp-p t) ; just to get the match data
15996 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15997 (replace-match "")
15998 (setq org-last-changed-timestamp
15999 (org-insert-time-stamp
16000 time (or org-time-was-given arg)
16001 inactive nil nil (list org-end-time-was-given)))
16002 (when repeater (goto-char (1- (point))) (insert " " repeater)
16003 (setq org-last-changed-timestamp
16004 (concat (substring org-last-inserted-timestamp 0 -1)
16005 " " repeater ">"))))
16006 (message "Timestamp updated"))
16007 ((equal arg '(16))
16008 (org-insert-time-stamp (current-time) t))
16010 (setq time (let ((this-command this-command))
16011 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16012 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16013 nil nil (list org-end-time-was-given))))))
16015 ;; FIXME: can we use this for something else, like computing time differences?
16016 (defun org-get-compact-tod (s)
16017 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16018 (let* ((t1 (match-string 1 s))
16019 (h1 (string-to-number (match-string 2 s)))
16020 (m1 (string-to-number (match-string 3 s)))
16021 (t2 (and (match-end 4) (match-string 5 s)))
16022 (h2 (and t2 (string-to-number (match-string 6 s))))
16023 (m2 (and t2 (string-to-number (match-string 7 s))))
16024 dh dm)
16025 (if (not t2)
16027 (setq dh (- h2 h1) dm (- m2 m1))
16028 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16029 (concat t1 "+" (number-to-string dh)
16030 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16032 (defun org-time-stamp-inactive (&optional arg)
16033 "Insert an inactive time stamp.
16034 An inactive time stamp is enclosed in square brackets instead of angle
16035 brackets. It is inactive in the sense that it does not trigger agenda entries,
16036 does not link to the calendar and cannot be changed with the S-cursor keys.
16037 So these are more for recording a certain time/date."
16038 (interactive "P")
16039 (org-time-stamp arg 'inactive))
16041 (defvar org-date-ovl (make-overlay 1 1))
16042 (overlay-put org-date-ovl 'face 'org-date-selected)
16043 (org-detach-overlay org-date-ovl)
16045 (defvar org-ans1) ; dynamically scoped parameter
16046 (defvar org-ans2) ; dynamically scoped parameter
16048 (defvar org-plain-time-of-day-regexp) ; defined below
16050 (defvar org-overriding-default-time nil) ; dynamically scoped
16051 (defvar org-read-date-overlay nil)
16052 (defvar org-dcst nil) ; dynamically scoped
16053 (defvar org-read-date-history nil)
16054 (defvar org-read-date-final-answer nil)
16055 (defvar org-read-date-analyze-futurep nil)
16056 (defvar org-read-date-analyze-forced-year nil)
16057 (defvar org-read-date-inactive)
16059 (defvar org-read-date-minibuffer-local-map
16060 (let ((map (make-sparse-keymap)))
16061 (set-keymap-parent map minibuffer-local-map)
16062 (org-defkey map (kbd ".")
16063 (lambda () (interactive)
16064 (org-eval-in-calendar '(calendar-goto-today))))
16065 (org-defkey map [(meta shift left)]
16066 (lambda () (interactive)
16067 (org-eval-in-calendar '(calendar-backward-month 1))))
16068 (org-defkey map [(meta shift right)]
16069 (lambda () (interactive)
16070 (org-eval-in-calendar '(calendar-forward-month 1))))
16071 (org-defkey map [(meta shift up)]
16072 (lambda () (interactive)
16073 (org-eval-in-calendar '(calendar-backward-year 1))))
16074 (org-defkey map [(meta shift down)]
16075 (lambda () (interactive)
16076 (org-eval-in-calendar '(calendar-forward-year 1))))
16077 (org-defkey map [?\e (shift left)]
16078 (lambda () (interactive)
16079 (org-eval-in-calendar '(calendar-backward-month 1))))
16080 (org-defkey map [?\e (shift right)]
16081 (lambda () (interactive)
16082 (org-eval-in-calendar '(calendar-forward-month 1))))
16083 (org-defkey map [?\e (shift up)]
16084 (lambda () (interactive)
16085 (org-eval-in-calendar '(calendar-backward-year 1))))
16086 (org-defkey map [?\e (shift down)]
16087 (lambda () (interactive)
16088 (org-eval-in-calendar '(calendar-forward-year 1))))
16089 (org-defkey map [(shift up)]
16090 (lambda () (interactive)
16091 (org-eval-in-calendar '(calendar-backward-week 1))))
16092 (org-defkey map [(shift down)]
16093 (lambda () (interactive)
16094 (org-eval-in-calendar '(calendar-forward-week 1))))
16095 (org-defkey map [(shift left)]
16096 (lambda () (interactive)
16097 (org-eval-in-calendar '(calendar-backward-day 1))))
16098 (org-defkey map [(shift right)]
16099 (lambda () (interactive)
16100 (org-eval-in-calendar '(calendar-forward-day 1))))
16101 (org-defkey map "!"
16102 (lambda () (interactive)
16103 (org-eval-in-calendar '(diary-view-entries))
16104 (message "")))
16105 (org-defkey map ">"
16106 (lambda () (interactive)
16107 (org-eval-in-calendar '(scroll-calendar-left 1))))
16108 (org-defkey map "<"
16109 (lambda () (interactive)
16110 (org-eval-in-calendar '(scroll-calendar-right 1))))
16111 (org-defkey map "\C-v"
16112 (lambda () (interactive)
16113 (org-eval-in-calendar
16114 '(calendar-scroll-left-three-months 1))))
16115 (org-defkey map "\M-v"
16116 (lambda () (interactive)
16117 (org-eval-in-calendar
16118 '(calendar-scroll-right-three-months 1))))
16119 map)
16120 "Keymap for minibuffer commands when using `org-read-date'.")
16122 (defun org-read-date (&optional org-with-time to-time from-string prompt
16123 default-time default-input inactive)
16124 "Read a date, possibly a time, and make things smooth for the user.
16125 The prompt will suggest to enter an ISO date, but you can also enter anything
16126 which will at least partially be understood by `parse-time-string'.
16127 Unrecognized parts of the date will default to the current day, month, year,
16128 hour and minute. If this command is called to replace a timestamp at point,
16129 or to enter the second timestamp of a range, the default time is taken
16130 from the existing stamp. Furthermore, the command prefers the future,
16131 so if you are giving a date where the year is not given, and the day-month
16132 combination is already past in the current year, it will assume you
16133 mean next year. For details, see the manual. A few examples:
16135 3-2-5 --> 2003-02-05
16136 feb 15 --> currentyear-02-15
16137 2/15 --> currentyear-02-15
16138 sep 12 9 --> 2009-09-12
16139 12:45 --> today 12:45
16140 22 sept 0:34 --> currentyear-09-22 0:34
16141 12 --> currentyear-currentmonth-12
16142 Fri --> nearest Friday (today or later)
16143 etc.
16145 Furthermore you can specify a relative date by giving, as the *first* thing
16146 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16147 change in days weeks, months, years.
16148 With a single plus or minus, the date is relative to today. With a double
16149 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16150 +4d --> four days from today
16151 +4 --> same as above
16152 +2w --> two weeks from today
16153 ++5 --> five days from default date
16155 The function understands only English month and weekday abbreviations.
16157 While prompting, a calendar is popped up - you can also select the
16158 date with the mouse (button 1). The calendar shows a period of three
16159 months. To scroll it to other months, use the keys `>' and `<'.
16160 If you don't like the calendar, turn it off with
16161 \(setq org-read-date-popup-calendar nil)
16163 With optional argument TO-TIME, the date will immediately be converted
16164 to an internal time.
16165 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16166 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16167 still enter a time, and this function will inform the calling routine
16168 about this change. The calling routine may then choose to change the
16169 format used to insert the time stamp into the buffer to include the time.
16170 With optional argument FROM-STRING, read from this string instead from
16171 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16172 the time/date that is used for everything that is not specified by the
16173 user."
16174 (require 'parse-time)
16175 (let* ((org-time-stamp-rounding-minutes
16176 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16177 (org-dcst org-display-custom-times)
16178 (ct (org-current-time))
16179 (org-def (or org-overriding-default-time default-time ct))
16180 (org-defdecode (decode-time org-def))
16181 (dummy (progn
16182 (when (< (nth 2 org-defdecode) org-extend-today-until)
16183 (setcar (nthcdr 2 org-defdecode) -1)
16184 (setcar (nthcdr 1 org-defdecode) 59)
16185 (setq org-def (apply 'encode-time org-defdecode)
16186 org-defdecode (decode-time org-def)))))
16187 (mouse-autoselect-window nil) ; Don't let the mouse jump
16188 (calendar-frame-setup nil)
16189 (calendar-setup nil)
16190 (calendar-move-hook nil)
16191 (calendar-view-diary-initially-flag nil)
16192 (calendar-view-holidays-initially-flag nil)
16193 (timestr (format-time-string
16194 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16195 (prompt (concat (if prompt (concat prompt " ") "")
16196 (format "Date+time [%s]: " timestr)))
16197 ans (org-ans0 "") org-ans1 org-ans2 final)
16199 (cond
16200 (from-string (setq ans from-string))
16201 (org-read-date-popup-calendar
16202 (save-excursion
16203 (save-window-excursion
16204 (calendar)
16205 (org-eval-in-calendar '(setq cursor-type nil) t)
16206 (unwind-protect
16207 (progn
16208 (calendar-forward-day (- (time-to-days org-def)
16209 (calendar-absolute-from-gregorian
16210 (calendar-current-date))))
16211 (org-eval-in-calendar nil t)
16212 (let* ((old-map (current-local-map))
16213 (map (copy-keymap calendar-mode-map))
16214 (minibuffer-local-map
16215 (copy-keymap org-read-date-minibuffer-local-map)))
16216 (org-defkey map (kbd "RET") 'org-calendar-select)
16217 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16218 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16219 (unwind-protect
16220 (progn
16221 (use-local-map map)
16222 (setq org-read-date-inactive inactive)
16223 (add-hook 'post-command-hook 'org-read-date-display)
16224 (setq org-ans0 (read-string prompt default-input
16225 'org-read-date-history nil))
16226 ;; org-ans0: from prompt
16227 ;; org-ans1: from mouse click
16228 ;; org-ans2: from calendar motion
16229 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16230 (remove-hook 'post-command-hook 'org-read-date-display)
16231 (use-local-map old-map)
16232 (when org-read-date-overlay
16233 (delete-overlay org-read-date-overlay)
16234 (setq org-read-date-overlay nil)))))
16235 (bury-buffer "*Calendar*")))))
16237 (t ; Naked prompt only
16238 (unwind-protect
16239 (setq ans (read-string prompt default-input
16240 'org-read-date-history timestr))
16241 (when org-read-date-overlay
16242 (delete-overlay org-read-date-overlay)
16243 (setq org-read-date-overlay nil)))))
16245 (setq final (org-read-date-analyze ans org-def org-defdecode))
16247 (when org-read-date-analyze-forced-year
16248 (message "Year was forced into %s"
16249 (if org-read-date-force-compatible-dates
16250 "compatible range (1970-2037)"
16251 "range representable on this machine"))
16252 (ding))
16254 ;; One round trip to get rid of 34th of August and stuff like that....
16255 (setq final (decode-time (apply 'encode-time final)))
16257 (setq org-read-date-final-answer ans)
16259 (if to-time
16260 (apply 'encode-time final)
16261 (if (and (boundp 'org-time-was-given) org-time-was-given)
16262 (format "%04d-%02d-%02d %02d:%02d"
16263 (nth 5 final) (nth 4 final) (nth 3 final)
16264 (nth 2 final) (nth 1 final))
16265 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16267 (defvar org-def)
16268 (defvar org-defdecode)
16269 (defvar org-with-time)
16270 (defun org-read-date-display ()
16271 "Display the current date prompt interpretation in the minibuffer."
16272 (when org-read-date-display-live
16273 (when org-read-date-overlay
16274 (delete-overlay org-read-date-overlay))
16275 (when (minibufferp (current-buffer))
16276 (save-excursion
16277 (end-of-line 1)
16278 (while (not (equal (buffer-substring
16279 (max (point-min) (- (point) 4)) (point))
16280 " "))
16281 (insert " ")))
16282 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16283 " " (or org-ans1 org-ans2)))
16284 (org-end-time-was-given nil)
16285 (f (org-read-date-analyze ans org-def org-defdecode))
16286 (fmts (if org-dcst
16287 org-time-stamp-custom-formats
16288 org-time-stamp-formats))
16289 (fmt (if (or org-with-time
16290 (and (boundp 'org-time-was-given) org-time-was-given))
16291 (cdr fmts)
16292 (car fmts)))
16293 (txt (format-time-string fmt (apply 'encode-time f)))
16294 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16295 (txt (concat "=> " txt)))
16296 (when (and org-end-time-was-given
16297 (string-match org-plain-time-of-day-regexp txt))
16298 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16299 org-end-time-was-given
16300 (substring txt (match-end 0)))))
16301 (when org-read-date-analyze-futurep
16302 (setq txt (concat txt " (=>F)")))
16303 (setq org-read-date-overlay
16304 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16305 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16307 (defun org-read-date-analyze (ans org-def org-defdecode)
16308 "Analyze the combined answer of the date prompt."
16309 ;; FIXME: cleanup and comment
16310 (let ((nowdecode (decode-time (current-time)))
16311 delta deltan deltaw deltadef year month day
16312 hour minute second wday pm h2 m2 tl wday1
16313 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16314 (setq org-read-date-analyze-futurep nil
16315 org-read-date-analyze-forced-year nil)
16316 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16317 (setq ans "+0"))
16319 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16320 (setq ans (replace-match "" t t ans)
16321 deltan (car delta)
16322 deltaw (nth 1 delta)
16323 deltadef (nth 2 delta)))
16325 ;; Check if there is an iso week date in there. If yes, store the
16326 ;; info and postpone interpreting it until the rest of the parsing
16327 ;; is done.
16328 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16329 (setq iso-year (if (match-end 1)
16330 (org-small-year-to-year
16331 (string-to-number (match-string 1 ans))))
16332 iso-weekday (if (match-end 3)
16333 (string-to-number (match-string 3 ans)))
16334 iso-week (string-to-number (match-string 2 ans)))
16335 (setq ans (replace-match "" t t ans)))
16337 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16338 (when (string-match
16339 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16340 (setq year (if (match-end 2)
16341 (string-to-number (match-string 2 ans))
16342 (progn (setq kill-year t)
16343 (string-to-number (format-time-string "%Y"))))
16344 month (string-to-number (match-string 3 ans))
16345 day (string-to-number (match-string 4 ans)))
16346 (if (< year 100) (setq year (+ 2000 year)))
16347 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16348 t nil ans)))
16350 ;; Help matching dotted european dates
16351 (when (string-match
16352 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16353 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16354 (setq kill-year t)
16355 (string-to-number (format-time-string "%Y")))
16356 day (string-to-number (match-string 1 ans))
16357 month (string-to-number (match-string 2 ans))
16358 ans (replace-match (format "%04d-%02d-%02d" year month day)
16359 t nil ans)))
16361 ;; Help matching american dates, like 5/30 or 5/30/7
16362 (when (string-match
16363 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16364 (setq year (if (match-end 4)
16365 (string-to-number (match-string 4 ans))
16366 (progn (setq kill-year t)
16367 (string-to-number (format-time-string "%Y"))))
16368 month (string-to-number (match-string 1 ans))
16369 day (string-to-number (match-string 2 ans)))
16370 (if (< year 100) (setq year (+ 2000 year)))
16371 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16372 t nil ans)))
16373 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16374 ;; If there is a time with am/pm, and *no* time without it, we convert
16375 ;; so that matching will be successful.
16376 (loop for i from 1 to 2 do ; twice, for end time as well
16377 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16378 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16379 (setq hour (string-to-number (match-string 1 ans))
16380 minute (if (match-end 3)
16381 (string-to-number (match-string 3 ans))
16383 pm (equal ?p
16384 (string-to-char (downcase (match-string 4 ans)))))
16385 (if (and (= hour 12) (not pm))
16386 (setq hour 0)
16387 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16388 (setq ans (replace-match (format "%02d:%02d" hour minute)
16389 t t ans))))
16391 ;; Check if a time range is given as a duration
16392 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16393 (setq hour (string-to-number (match-string 1 ans))
16394 h2 (+ hour (string-to-number (match-string 3 ans)))
16395 minute (string-to-number (match-string 2 ans))
16396 m2 (+ minute (if (match-end 5) (string-to-number
16397 (match-string 5 ans))0)))
16398 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16399 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16400 t t ans)))
16402 ;; Check if there is a time range
16403 (when (boundp 'org-end-time-was-given)
16404 (setq org-time-was-given nil)
16405 (when (and (string-match org-plain-time-of-day-regexp ans)
16406 (match-end 8))
16407 (setq org-end-time-was-given (match-string 8 ans))
16408 (setq ans (concat (substring ans 0 (match-beginning 7))
16409 (substring ans (match-end 7))))))
16411 (setq tl (parse-time-string ans)
16412 day (or (nth 3 tl) (nth 3 org-defdecode))
16413 month (or (nth 4 tl)
16414 (if (and org-read-date-prefer-future
16415 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16416 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16417 (nth 4 org-defdecode)))
16418 year (or (and (not kill-year) (nth 5 tl))
16419 (if (and org-read-date-prefer-future
16420 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16421 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16422 (nth 5 org-defdecode)))
16423 hour (or (nth 2 tl) (nth 2 org-defdecode))
16424 minute (or (nth 1 tl) (nth 1 org-defdecode))
16425 second (or (nth 0 tl) 0)
16426 wday (nth 6 tl))
16428 (when (and (eq org-read-date-prefer-future 'time)
16429 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16430 (equal day (nth 3 nowdecode))
16431 (equal month (nth 4 nowdecode))
16432 (equal year (nth 5 nowdecode))
16433 (nth 2 tl)
16434 (or (< (nth 2 tl) (nth 2 nowdecode))
16435 (and (= (nth 2 tl) (nth 2 nowdecode))
16436 (nth 1 tl)
16437 (< (nth 1 tl) (nth 1 nowdecode)))))
16438 (setq day (1+ day)
16439 futurep t))
16441 ;; Special date definitions below
16442 (cond
16443 (iso-week
16444 ;; There was an iso week
16445 (require 'cal-iso)
16446 (setq futurep nil)
16447 (setq year (or iso-year year)
16448 day (or iso-weekday wday 1)
16449 wday nil ; to make sure that the trigger below does not match
16450 iso-date (calendar-gregorian-from-absolute
16451 (calendar-absolute-from-iso
16452 (list iso-week day year))))
16453 ; FIXME: Should we also push ISO weeks into the future?
16454 ; (when (and org-read-date-prefer-future
16455 ; (not iso-year)
16456 ; (< (calendar-absolute-from-gregorian iso-date)
16457 ; (time-to-days (current-time))))
16458 ; (setq year (1+ year)
16459 ; iso-date (calendar-gregorian-from-absolute
16460 ; (calendar-absolute-from-iso
16461 ; (list iso-week day year)))))
16462 (setq month (car iso-date)
16463 year (nth 2 iso-date)
16464 day (nth 1 iso-date)))
16465 (deltan
16466 (setq futurep nil)
16467 (unless deltadef
16468 (let ((now (decode-time (current-time))))
16469 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16470 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16471 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16472 ((equal deltaw "m") (setq month (+ month deltan)))
16473 ((equal deltaw "y") (setq year (+ year deltan)))))
16474 ((and wday (not (nth 3 tl)))
16475 ;; Weekday was given, but no day, so pick that day in the week
16476 ;; on or after the derived date.
16477 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16478 (unless (equal wday wday1)
16479 (setq day (+ day (% (- wday wday1 -7) 7))))))
16480 (if (and (boundp 'org-time-was-given)
16481 (nth 2 tl))
16482 (setq org-time-was-given t))
16483 (if (< year 100) (setq year (+ 2000 year)))
16484 ;; Check of the date is representable
16485 (if org-read-date-force-compatible-dates
16486 (progn
16487 (if (< year 1970)
16488 (setq year 1970 org-read-date-analyze-forced-year t))
16489 (if (> year 2037)
16490 (setq year 2037 org-read-date-analyze-forced-year t)))
16491 (condition-case nil
16492 (ignore (encode-time second minute hour day month year))
16493 (error
16494 (setq year (nth 5 org-defdecode))
16495 (setq org-read-date-analyze-forced-year t))))
16496 (setq org-read-date-analyze-futurep futurep)
16497 (list second minute hour day month year)))
16499 (defvar parse-time-weekdays)
16500 (defun org-read-date-get-relative (s today default)
16501 "Check string S for special relative date string.
16502 TODAY and DEFAULT are internal times, for today and for a default.
16503 Return shift list (N what def-flag)
16504 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16505 N is the number of WHATs to shift.
16506 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16507 the DEFAULT date rather than TODAY."
16508 (require 'parse-time)
16509 (when (and
16510 (string-match
16511 (concat
16512 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16513 "\\([0-9]+\\)?"
16514 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16515 "\\([ \t]\\|$\\)") s)
16516 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16517 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16518 (string-to-char (substring (match-string 1 s) -1))
16519 ?+))
16520 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16521 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16522 (what (if (match-end 3) (match-string 3 s) "d"))
16523 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16524 (date (if rel default today))
16525 (wday (nth 6 (decode-time date)))
16526 delta)
16527 (if wday1
16528 (progn
16529 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16530 (if (= dir ?-) (setq delta (- delta 7)))
16531 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16532 (list delta "d" rel))
16533 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16535 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16536 "Turn a user-specified date into the internal representation.
16537 The internal representation needed by the calendar is (month day year).
16538 This is a wrapper to handle the brain-dead convention in calendar that
16539 user function argument order change dependent on argument order."
16540 (if (boundp 'calendar-date-style)
16541 (cond
16542 ((eq calendar-date-style 'american)
16543 (list arg1 arg2 arg3))
16544 ((eq calendar-date-style 'european)
16545 (list arg2 arg1 arg3))
16546 ((eq calendar-date-style 'iso)
16547 (list arg2 arg3 arg1)))
16548 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16549 (if (org-bound-and-true-p european-calendar-style)
16550 (list arg2 arg1 arg3)
16551 (list arg1 arg2 arg3)))))
16553 (defun org-eval-in-calendar (form &optional keepdate)
16554 "Eval FORM in the calendar window and return to current window.
16555 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16556 otherwise stick to the current value of `org-ans2'."
16557 (let ((sf (selected-frame))
16558 (sw (selected-window)))
16559 (select-window (get-buffer-window "*Calendar*" t))
16560 (eval form)
16561 (when (and (not keepdate) (calendar-cursor-to-date))
16562 (let* ((date (calendar-cursor-to-date))
16563 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16564 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16565 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16566 (select-window sw)
16567 (org-select-frame-set-input-focus sf)))
16569 (defun org-calendar-select ()
16570 "Return to `org-read-date' with the date currently selected.
16571 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16572 (interactive)
16573 (when (calendar-cursor-to-date)
16574 (let* ((date (calendar-cursor-to-date))
16575 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16576 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16577 (if (active-minibuffer-window) (exit-minibuffer))))
16579 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16580 "Insert a date stamp for the date given by the internal TIME.
16581 WITH-HM means use the stamp format that includes the time of the day.
16582 INACTIVE means use square brackets instead of angular ones, so that the
16583 stamp will not contribute to the agenda.
16584 PRE and POST are optional strings to be inserted before and after the
16585 stamp.
16586 The command returns the inserted time stamp."
16587 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16588 stamp)
16589 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16590 (insert-before-markers (or pre ""))
16591 (when (listp extra)
16592 (setq extra (car extra))
16593 (if (and (stringp extra)
16594 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16595 (setq extra (format "-%02d:%02d"
16596 (string-to-number (match-string 1 extra))
16597 (string-to-number (match-string 2 extra))))
16598 (setq extra nil)))
16599 (when extra
16600 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16601 (insert-before-markers (setq stamp (format-time-string fmt time)))
16602 (insert-before-markers (or post ""))
16603 (setq org-last-inserted-timestamp stamp)))
16605 (defun org-toggle-time-stamp-overlays ()
16606 "Toggle the use of custom time stamp formats."
16607 (interactive)
16608 (setq org-display-custom-times (not org-display-custom-times))
16609 (unless org-display-custom-times
16610 (let ((p (point-min)) (bmp (buffer-modified-p)))
16611 (while (setq p (next-single-property-change p 'display))
16612 (if (and (get-text-property p 'display)
16613 (eq (get-text-property p 'face) 'org-date))
16614 (remove-text-properties
16615 p (setq p (next-single-property-change p 'display))
16616 '(display t))))
16617 (set-buffer-modified-p bmp)))
16618 (if (featurep 'xemacs)
16619 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16620 (org-restart-font-lock)
16621 (setq org-table-may-need-update t)
16622 (if org-display-custom-times
16623 (message "Time stamps are overlaid with custom format")
16624 (message "Time stamp overlays removed")))
16626 (defun org-display-custom-time (beg end)
16627 "Overlay modified time stamp format over timestamp between BEG and END."
16628 (let* ((ts (buffer-substring beg end))
16629 t1 w1 with-hm tf time str w2 (off 0))
16630 (save-match-data
16631 (setq t1 (org-parse-time-string ts t))
16632 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16633 (setq off (- (match-end 0) (match-beginning 0)))))
16634 (setq end (- end off))
16635 (setq w1 (- end beg)
16636 with-hm (and (nth 1 t1) (nth 2 t1))
16637 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16638 time (org-fix-decoded-time t1)
16639 str (org-add-props
16640 (format-time-string
16641 (substring tf 1 -1) (apply 'encode-time time))
16642 nil 'mouse-face 'highlight)
16643 w2 (length str))
16644 (if (not (= w2 w1))
16645 (add-text-properties (1+ beg) (+ 2 beg)
16646 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16647 (if (featurep 'xemacs)
16648 (progn
16649 (put-text-property beg end 'invisible t)
16650 (put-text-property beg end 'end-glyph (make-glyph str)))
16651 (put-text-property beg end 'display str))))
16653 (defun org-translate-time (string)
16654 "Translate all timestamps in STRING to custom format.
16655 But do this only if the variable `org-display-custom-times' is set."
16656 (when org-display-custom-times
16657 (save-match-data
16658 (let* ((start 0)
16659 (re org-ts-regexp-both)
16660 t1 with-hm inactive tf time str beg end)
16661 (while (setq start (string-match re string start))
16662 (setq beg (match-beginning 0)
16663 end (match-end 0)
16664 t1 (save-match-data
16665 (org-parse-time-string (substring string beg end) t))
16666 with-hm (and (nth 1 t1) (nth 2 t1))
16667 inactive (equal (substring string beg (1+ beg)) "[")
16668 tf (funcall (if with-hm 'cdr 'car)
16669 org-time-stamp-custom-formats)
16670 time (org-fix-decoded-time t1)
16671 str (format-time-string
16672 (concat
16673 (if inactive "[" "<") (substring tf 1 -1)
16674 (if inactive "]" ">"))
16675 (apply 'encode-time time))
16676 string (replace-match str t t string)
16677 start (+ start (length str)))))))
16678 string)
16680 (defun org-fix-decoded-time (time)
16681 "Set 0 instead of nil for the first 6 elements of time.
16682 Don't touch the rest."
16683 (let ((n 0))
16684 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16686 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16688 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16689 "Difference between TIMESTAMP-STRING and now in days.
16690 If SECONDS is non-nil, return the difference in seconds."
16691 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16692 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16693 (funcall fdiff (current-time)))))
16695 (defun org-deadline-close (timestamp-string &optional ndays)
16696 "Is the time in TIMESTAMP-STRING close to the current date?"
16697 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16698 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16699 (not (org-entry-is-done-p))))
16701 (defun org-get-wdays (ts &optional delay zero-delay)
16702 "Get the deadline lead time appropriate for timestring TS.
16703 When DELAY is non-nil, get the delay time for scheduled items
16704 instead of the deadline lead time. When ZERO-DELAY is non-nil
16705 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16706 don't try to find the delay cookie in the scheduled timestamp."
16707 (let ((tv (if delay org-scheduled-delay-days
16708 org-deadline-warning-days)))
16709 (cond
16710 ((or (and delay (< tv 0))
16711 (and delay zero-delay (<= tv 0))
16712 (and (not delay) (<= tv 0)))
16713 ;; Enforce this value no matter what
16714 (- tv))
16715 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16716 ;; lead time is specified.
16717 (floor (* (string-to-number (match-string 1 ts))
16718 (cdr (assoc (match-string 2 ts)
16719 '(("d" . 1) ("w" . 7)
16720 ("m" . 30.4) ("y" . 365.25)
16721 ("h" . 0.041667)))))))
16722 ;; go for the default.
16723 (t tv))))
16725 (defun org-calendar-select-mouse (ev)
16726 "Return to `org-read-date' with the date currently selected.
16727 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16728 (interactive "e")
16729 (mouse-set-point ev)
16730 (when (calendar-cursor-to-date)
16731 (let* ((date (calendar-cursor-to-date))
16732 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16733 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16734 (if (active-minibuffer-window) (exit-minibuffer))))
16736 (defun org-check-deadlines (ndays)
16737 "Check if there are any deadlines due or past due.
16738 A deadline is considered due if it happens within `org-deadline-warning-days'
16739 days from today's date. If the deadline appears in an entry marked DONE,
16740 it is not shown. The prefix arg NDAYS can be used to test that many
16741 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16742 (interactive "P")
16743 (let* ((org-warn-days
16744 (cond
16745 ((equal ndays '(4)) 100000)
16746 (ndays (prefix-numeric-value ndays))
16747 (t (abs org-deadline-warning-days))))
16748 (case-fold-search nil)
16749 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16750 (callback
16751 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16753 (message "%d deadlines past-due or due within %d days"
16754 (org-occur regexp nil callback)
16755 org-warn-days)))
16757 (defsubst org-re-timestamp (type)
16758 "Return a regexp for timestamp TYPE.
16759 Allowed values for TYPE are:
16761 all: all timestamps
16762 active: only active timestamps (<...>)
16763 inactive: only inactive timestamps ([...])
16764 scheduled: only scheduled timestamps
16765 deadline: only deadline timestamps
16766 closed: only closed time-stamps
16768 When TYPE is nil, fall back on returning a regexp that matches
16769 both scheduled and deadline timestamps."
16770 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16771 ((eq type 'active) org-ts-regexp)
16772 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16773 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16774 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16775 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16776 ((eq type 'scheduled-or-deadline)
16777 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16779 (defun org-check-before-date (date)
16780 "Check if there are deadlines or scheduled entries before DATE."
16781 (interactive (list (org-read-date)))
16782 (let ((case-fold-search nil)
16783 (regexp (org-re-timestamp org-ts-type))
16784 (callback
16785 (lambda () (time-less-p
16786 (org-time-string-to-time (match-string 1))
16787 (org-time-string-to-time date)))))
16788 (message "%d entries before %s"
16789 (org-occur regexp nil callback) date)))
16791 (defun org-check-after-date (date)
16792 "Check if there are deadlines or scheduled entries after DATE."
16793 (interactive (list (org-read-date)))
16794 (let ((case-fold-search nil)
16795 (regexp (org-re-timestamp org-ts-type))
16796 (callback
16797 (lambda () (not
16798 (time-less-p
16799 (org-time-string-to-time (match-string 1))
16800 (org-time-string-to-time date))))))
16801 (message "%d entries after %s"
16802 (org-occur regexp nil callback) date)))
16804 (defun org-check-dates-range (start-date end-date)
16805 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16806 (interactive (list (org-read-date nil nil nil "Range starts")
16807 (org-read-date nil nil nil "Range end")))
16808 (let ((case-fold-search nil)
16809 (regexp (org-re-timestamp org-ts-type))
16810 (callback
16811 (lambda ()
16812 (let ((match (match-string 1)))
16813 (and
16814 (not (time-less-p
16815 (org-time-string-to-time match)
16816 (org-time-string-to-time start-date)))
16817 (time-less-p
16818 (org-time-string-to-time match)
16819 (org-time-string-to-time end-date)))))))
16820 (message "%d entries between %s and %s"
16821 (org-occur regexp nil callback) start-date end-date)))
16823 (defun org-evaluate-time-range (&optional to-buffer)
16824 "Evaluate a time range by computing the difference between start and end.
16825 Normally the result is just printed in the echo area, but with prefix arg
16826 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16827 If the time range is actually in a table, the result is inserted into the
16828 next column.
16829 For time difference computation, a year is assumed to be exactly 365
16830 days in order to avoid rounding problems."
16831 (interactive "P")
16833 (org-clock-update-time-maybe)
16834 (save-excursion
16835 (unless (org-at-date-range-p t)
16836 (goto-char (point-at-bol))
16837 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16838 (if (not (org-at-date-range-p t))
16839 (error "Not at a time-stamp range, and none found in current line")))
16840 (let* ((ts1 (match-string 1))
16841 (ts2 (match-string 2))
16842 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16843 (match-end (match-end 0))
16844 (time1 (org-time-string-to-time ts1))
16845 (time2 (org-time-string-to-time ts2))
16846 (t1 (org-float-time time1))
16847 (t2 (org-float-time time2))
16848 (diff (abs (- t2 t1)))
16849 (negative (< (- t2 t1) 0))
16850 ;; (ys (floor (* 365 24 60 60)))
16851 (ds (* 24 60 60))
16852 (hs (* 60 60))
16853 (fy "%dy %dd %02d:%02d")
16854 (fy1 "%dy %dd")
16855 (fd "%dd %02d:%02d")
16856 (fd1 "%dd")
16857 (fh "%02d:%02d")
16858 y d h m align)
16859 (if havetime
16860 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16862 d (floor (/ diff ds)) diff (mod diff ds)
16863 h (floor (/ diff hs)) diff (mod diff hs)
16864 m (floor (/ diff 60)))
16865 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16867 d (floor (+ (/ diff ds) 0.5))
16868 h 0 m 0))
16869 (if (not to-buffer)
16870 (message "%s" (org-make-tdiff-string y d h m))
16871 (if (org-at-table-p)
16872 (progn
16873 (goto-char match-end)
16874 (setq align t)
16875 (and (looking-at " *|") (goto-char (match-end 0))))
16876 (goto-char match-end))
16877 (if (looking-at
16878 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16879 (replace-match ""))
16880 (if negative (insert " -"))
16881 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16882 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16883 (insert " " (format fh h m))))
16884 (if align (org-table-align))
16885 (message "Time difference inserted")))))
16887 (defun org-make-tdiff-string (y d h m)
16888 (let ((fmt "")
16889 (l nil))
16890 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16891 l (push y l)))
16892 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16893 l (push d l)))
16894 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16895 l (push h l)))
16896 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16897 l (push m l)))
16898 (apply 'format fmt (nreverse l))))
16900 (defun org-time-string-to-time (s &optional buffer pos)
16901 "Convert a timestamp string into internal time."
16902 (condition-case errdata
16903 (apply 'encode-time (org-parse-time-string s))
16904 (error (error "Bad timestamp `%s'%s\nError was: %s"
16905 s (if (not (and buffer pos))
16907 (format " at %d in buffer `%s'" pos buffer))
16908 (cdr errdata)))))
16910 (defun org-time-string-to-seconds (s)
16911 "Convert a timestamp string to a number of seconds."
16912 (org-float-time (org-time-string-to-time s)))
16914 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16915 "Convert a time stamp to an absolute day number.
16916 If there is a specifier for a cyclic time stamp, get the closest
16917 date to DAYNR.
16918 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16919 The variable `date' is bound by the calendar when this is called."
16920 (cond
16921 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16922 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16923 daynr
16924 (+ daynr 1000)))
16925 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16926 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16927 (time-to-days (current-time))) (match-string 0 s)
16928 prefer show-all))
16929 (t (time-to-days
16930 (condition-case errdata
16931 (apply 'encode-time (org-parse-time-string s))
16932 (error (error "Bad timestamp `%s'%s\nError was: %s"
16933 s (if (not (and buffer pos))
16935 (format " at %d in buffer `%s'" pos buffer))
16936 (cdr errdata))))))))
16938 (defun org-days-to-iso-week (days)
16939 "Return the iso week number."
16940 (require 'cal-iso)
16941 (car (calendar-iso-from-absolute days)))
16943 (defun org-small-year-to-year (year)
16944 "Convert 2-digit years into 4-digit years.
16945 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16946 The year 2000 cannot be abbreviated. Any year larger than 99
16947 is returned unchanged."
16948 (if (< year 38)
16949 (setq year (+ 2000 year))
16950 (if (< year 100)
16951 (setq year (+ 1900 year))))
16952 year)
16954 (defun org-time-from-absolute (d)
16955 "Return the time corresponding to date D.
16956 D may be an absolute day number, or a calendar-type list (month day year)."
16957 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16958 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16960 (defun org-calendar-holiday ()
16961 "List of holidays, for Diary display in Org-mode."
16962 (require 'holidays)
16963 (let ((hl (funcall
16964 (if (fboundp 'calendar-check-holidays)
16965 'calendar-check-holidays 'check-calendar-holidays) date)))
16966 (if hl (mapconcat 'identity hl "; "))))
16968 (defun org-diary-sexp-entry (sexp entry date)
16969 "Process a SEXP diary ENTRY for DATE."
16970 (require 'diary-lib)
16971 (let ((result (if calendar-debug-sexp
16972 (let ((stack-trace-on-error t))
16973 (eval (car (read-from-string sexp))))
16974 (condition-case nil
16975 (eval (car (read-from-string sexp)))
16976 (error
16977 (beep)
16978 (message "Bad sexp at line %d in %s: %s"
16979 (org-current-line)
16980 (buffer-file-name) sexp)
16981 (sleep-for 2))))))
16982 (cond ((stringp result) (split-string result "; "))
16983 ((and (consp result)
16984 (not (consp (cdr result)))
16985 (stringp (cdr result))) (cdr result))
16986 ((and (consp result)
16987 (stringp (car result))) result)
16988 (result entry))))
16990 (defun org-diary-to-ical-string (frombuf)
16991 "Get iCalendar entries from diary entries in buffer FROMBUF.
16992 This uses the icalendar.el library."
16993 (let* ((tmpdir (if (featurep 'xemacs)
16994 (temp-directory)
16995 temporary-file-directory))
16996 (tmpfile (make-temp-name
16997 (expand-file-name "orgics" tmpdir)))
16998 buf rtn b e)
16999 (with-current-buffer frombuf
17000 (icalendar-export-region (point-min) (point-max) tmpfile)
17001 (setq buf (find-buffer-visiting tmpfile))
17002 (set-buffer buf)
17003 (goto-char (point-min))
17004 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17005 (setq b (match-beginning 0)))
17006 (goto-char (point-max))
17007 (if (re-search-backward "^END:VEVENT" nil t)
17008 (setq e (match-end 0)))
17009 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17010 (kill-buffer buf)
17011 (delete-file tmpfile)
17012 rtn))
17014 (defun org-closest-date (start current change prefer show-all)
17015 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17016 When PREFER is `past', return a date that is either CURRENT or past.
17017 When PREFER is `future', return a date that is either CURRENT or future.
17018 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17019 ;; Make the proper lists from the dates
17020 (catch 'exit
17021 (let ((a1 '(("h" . hour)
17022 ("d" . day)
17023 ("w" . week)
17024 ("m" . month)
17025 ("y" . year)))
17026 (shour (nth 2 (org-parse-time-string start)))
17027 dn dw sday cday n1 n2 n0
17028 d m y y1 y2 date1 date2 nmonths nm ny m2)
17030 (setq start (org-date-to-gregorian start)
17031 current (org-date-to-gregorian
17032 (if show-all
17033 current
17034 (time-to-days (current-time))))
17035 sday (calendar-absolute-from-gregorian start)
17036 cday (calendar-absolute-from-gregorian current))
17038 (if (<= cday sday) (throw 'exit sday))
17040 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17041 (setq dn (string-to-number (match-string 1 change))
17042 dw (cdr (assoc (match-string 2 change) a1)))
17043 (error "Invalid change specifier: %s" change))
17044 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17045 (cond
17046 ((eq dw 'hour)
17047 (let ((missing-hours
17048 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17049 dn)))
17050 (setq n1 (if (zerop missing-hours) cday
17051 (- cday (1+ (floor (/ missing-hours 24)))))
17052 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17053 ((eq dw 'day)
17054 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17055 n2 (+ n1 dn)))
17056 ((eq dw 'year)
17057 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17058 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17059 (setq date1 (list m d y1)
17060 n1 (calendar-absolute-from-gregorian date1)
17061 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17062 n2 (calendar-absolute-from-gregorian date2)))
17063 ((eq dw 'month)
17064 ;; approx number of month between the two dates
17065 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17066 ;; How often does dn fit in there?
17067 (setq d (nth 1 start) m (car start) y (nth 2 start)
17068 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17069 m (+ m nm)
17070 ny (floor (/ m 12))
17071 y (+ y ny)
17072 m (- m (* ny 12)))
17073 (while (> m 12) (setq m (- m 12) y (1+ y)))
17074 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17075 (setq m2 (+ m dn) y2 y)
17076 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17077 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17078 (while (<= n2 cday)
17079 (setq n1 n2 m m2 y y2)
17080 (setq m2 (+ m dn) y2 y)
17081 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17082 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17083 ;; Make sure n1 is the earlier date
17084 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17085 (if show-all
17086 (cond
17087 ((eq prefer 'past) (if (= cday n2) n2 n1))
17088 ((eq prefer 'future) (if (= cday n1) n1 n2))
17089 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17090 (cond
17091 ((eq prefer 'past) (if (= cday n2) n2 n1))
17092 ((eq prefer 'future) (if (= cday n1) n1 n2))
17093 (t (if (= cday n1) n1 n2)))))))
17095 (defun org-date-to-gregorian (date)
17096 "Turn any specification of DATE into a Gregorian date for the calendar."
17097 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17098 ((and (listp date) (= (length date) 3)) date)
17099 ((stringp date)
17100 (setq date (org-parse-time-string date))
17101 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17102 ((listp date)
17103 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17105 (defun org-parse-time-string (s &optional nodefault)
17106 "Parse the standard Org-mode time string.
17107 This should be a lot faster than the normal `parse-time-string'.
17108 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17109 hour and minute fields will be nil if not given."
17110 (cond ((string-match org-ts-regexp0 s)
17111 (list 0
17112 (if (or (match-beginning 8) (not nodefault))
17113 (string-to-number (or (match-string 8 s) "0")))
17114 (if (or (match-beginning 7) (not nodefault))
17115 (string-to-number (or (match-string 7 s) "0")))
17116 (string-to-number (match-string 4 s))
17117 (string-to-number (match-string 3 s))
17118 (string-to-number (match-string 2 s))
17119 nil nil nil))
17120 ((string-match "^<[^>]+>$" s)
17121 (decode-time (seconds-to-time (org-matcher-time s))))
17122 (t (error "Not a standard Org-mode time string: %s" s))))
17124 (defun org-timestamp-up (&optional arg)
17125 "Increase the date item at the cursor by one.
17126 If the cursor is on the year, change the year. If it is on the month,
17127 the day or the time, change that.
17128 With prefix ARG, change by that many units."
17129 (interactive "p")
17130 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17132 (defun org-timestamp-down (&optional arg)
17133 "Decrease the date item at the cursor by one.
17134 If the cursor is on the year, change the year. If it is on the month,
17135 the day or the time, change that.
17136 With prefix ARG, change by that many units."
17137 (interactive "p")
17138 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17140 (defun org-timestamp-up-day (&optional arg)
17141 "Increase the date in the time stamp by one day.
17142 With prefix ARG, change that many days."
17143 (interactive "p")
17144 (if (and (not (org-at-timestamp-p t))
17145 (org-at-heading-p))
17146 (org-todo 'up)
17147 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17149 (defun org-timestamp-down-day (&optional arg)
17150 "Decrease 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 'down)
17156 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17158 (defun org-at-timestamp-p (&optional inactive-ok)
17159 "Determine if the cursor is in or at a timestamp."
17160 (interactive)
17161 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17162 (pos (point))
17163 (ans (or (looking-at tsr)
17164 (save-excursion
17165 (skip-chars-backward "^[<\n\r\t")
17166 (if (> (point) (point-min)) (backward-char 1))
17167 (and (looking-at tsr)
17168 (> (- (match-end 0) pos) -1))))))
17169 (and ans
17170 (boundp 'org-ts-what)
17171 (setq org-ts-what
17172 (cond
17173 ((= pos (match-beginning 0)) 'bracket)
17174 ;; Point is considered to be "on the bracket" whether
17175 ;; it's really on it or right after it.
17176 ((= pos (1- (match-end 0))) 'bracket)
17177 ((= pos (match-end 0)) 'after)
17178 ((org-pos-in-match-range pos 2) 'year)
17179 ((org-pos-in-match-range pos 3) 'month)
17180 ((org-pos-in-match-range pos 7) 'hour)
17181 ((org-pos-in-match-range pos 8) 'minute)
17182 ((or (org-pos-in-match-range pos 4)
17183 (org-pos-in-match-range pos 5)) 'day)
17184 ((and (> pos (or (match-end 8) (match-end 5)))
17185 (< pos (match-end 0)))
17186 (- pos (or (match-end 8) (match-end 5))))
17187 (t 'day))))
17188 ans))
17190 (defun org-toggle-timestamp-type ()
17191 "Toggle the type (<active> or [inactive]) of a time stamp."
17192 (interactive)
17193 (when (org-at-timestamp-p t)
17194 (let ((beg (match-beginning 0)) (end (match-end 0))
17195 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17196 (save-excursion
17197 (goto-char beg)
17198 (while (re-search-forward "[][<>]" end t)
17199 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17200 t t)))
17201 (message "Timestamp is now %sactive"
17202 (if (equal (char-after beg) ?<) "" "in")))))
17204 (defun org-at-clock-log-p nil
17205 "Is the cursor on the clock log line?"
17206 (save-excursion
17207 (move-beginning-of-line 1)
17208 (looking-at "^[ \t]*CLOCK:")))
17210 (defvar org-clock-history) ; defined in org-clock.el
17211 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17212 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17213 "Change the date in the time stamp at point.
17214 The date will be changed by N times WHAT. WHAT can be `day', `month',
17215 `year', `minute', `second'. If WHAT is not given, the cursor position
17216 in the timestamp determines what will be changed.
17217 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17218 (let ((origin (point)) origin-cat
17219 with-hm inactive
17220 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17221 org-ts-what
17222 extra rem
17223 ts time time0 fixnext clrgx)
17224 (if (not (org-at-timestamp-p t))
17225 (error "Not at a timestamp"))
17226 (if (and (not what) (eq org-ts-what 'bracket))
17227 (org-toggle-timestamp-type)
17228 ;; Point isn't on brackets. Remember the part of the time-stamp
17229 ;; the point was in. Indeed, size of time-stamps may change,
17230 ;; but point must be kept in the same category nonetheless.
17231 (setq origin-cat org-ts-what)
17232 (if (and (not what) (not (eq org-ts-what 'day))
17233 org-display-custom-times
17234 (get-text-property (point) 'display)
17235 (not (get-text-property (1- (point)) 'display)))
17236 (setq org-ts-what 'day))
17237 (setq org-ts-what (or what org-ts-what)
17238 inactive (= (char-after (match-beginning 0)) ?\[)
17239 ts (match-string 0))
17240 (replace-match "")
17241 (when (string-match
17242 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17244 (setq extra (match-string 1 ts))
17245 (if suppress-tmp-delay
17246 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17247 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17248 (setq with-hm t))
17249 (setq time0 (org-parse-time-string ts))
17250 (when (and updown
17251 (eq org-ts-what 'minute)
17252 (not current-prefix-arg))
17253 ;; This looks like s-up and s-down. Change by one rounding step.
17254 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17255 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17256 (setcar (cdr time0) (+ (nth 1 time0)
17257 (if (> n 0) (- rem) (- dm rem))))))
17258 (setq time
17259 (encode-time (or (car time0) 0)
17260 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17261 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17262 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17263 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17264 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17265 (nthcdr 6 time0)))
17266 (when (and (member org-ts-what '(hour minute))
17267 extra
17268 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17269 (setq extra (org-modify-ts-extra
17270 extra
17271 (if (eq org-ts-what 'hour) 2 5)
17272 n dm)))
17273 (when (integerp org-ts-what)
17274 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17275 (if (eq what 'calendar)
17276 (let ((cal-date (org-get-date-from-calendar)))
17277 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17278 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17279 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17280 (setcar time0 (or (car time0) 0))
17281 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17282 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17283 (setq time (apply 'encode-time time0))))
17284 ;; Insert the new time-stamp, and ensure point stays in the same
17285 ;; category as before (i.e. not after the last position in that
17286 ;; category).
17287 (let ((pos (point)))
17288 ;; Stay before inserted string. `save-excursion' is of no use.
17289 (setq org-last-changed-timestamp
17290 (org-insert-time-stamp time with-hm inactive nil nil extra))
17291 (goto-char pos))
17292 (save-match-data
17293 (looking-at org-ts-regexp3)
17294 (goto-char (cond
17295 ;; `day' category ends before `hour' if any, or at
17296 ;; the end of the day name.
17297 ((eq origin-cat 'day)
17298 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17299 ((eq origin-cat 'hour) (min (match-end 7) origin))
17300 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17301 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17302 ;; `year' and `month' have both fixed size: point
17303 ;; couldn't have moved into another part.
17304 (t origin))))
17305 ;; Update clock if on a CLOCK line.
17306 (org-clock-update-time-maybe)
17307 ;; Maybe adjust the closest clock in `org-clock-history'
17308 (when org-clock-adjust-closest
17309 (if (not (and (org-at-clock-log-p)
17310 (< 1 (length (delq nil (mapcar 'marker-position
17311 org-clock-history))))))
17312 (message "No clock to adjust")
17313 (cond ((save-excursion ; fix previous clock?
17314 (re-search-backward org-ts-regexp0 nil t)
17315 (org-looking-back (concat org-clock-string " \\[")))
17316 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17317 ((save-excursion ; fix next clock?
17318 (re-search-backward org-ts-regexp0 nil t)
17319 (looking-at (concat org-ts-regexp0 "\\] =>")))
17320 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17321 (save-window-excursion
17322 ;; Find closest clock to point, adjust the previous/next one in history
17323 (let* ((p (save-excursion (org-back-to-heading t)))
17324 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17325 (clfixnth
17326 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17327 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17328 (if (not clfixpos)
17329 (message "No clock to adjust")
17330 (save-excursion
17331 (org-goto-marker-or-bmk clfixpos)
17332 (org-show-subtree)
17333 (when (re-search-forward clrgx nil t)
17334 (goto-char (match-beginning 1))
17335 (let (org-clock-adjust-closest)
17336 (org-timestamp-change n org-ts-what updown))
17337 (message "Clock adjusted in %s for heading: %s"
17338 (file-name-nondirectory (buffer-file-name))
17339 (org-get-heading t t)))))))))
17340 ;; Try to recenter the calendar window, if any.
17341 (if (and org-calendar-follow-timestamp-change
17342 (get-buffer-window "*Calendar*" t)
17343 (memq org-ts-what '(day month year)))
17344 (org-recenter-calendar (time-to-days time))))))
17346 (defun org-modify-ts-extra (s pos n dm)
17347 "Change the different parts of the lead-time and repeat fields in timestamp."
17348 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17349 ng h m new rem)
17350 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17351 (cond
17352 ((or (org-pos-in-match-range pos 2)
17353 (org-pos-in-match-range pos 3))
17354 (setq m (string-to-number (match-string 3 s))
17355 h (string-to-number (match-string 2 s)))
17356 (if (org-pos-in-match-range pos 2)
17357 (setq h (+ h n))
17358 (setq n (* dm (org-no-warnings (signum n))))
17359 (when (not (= 0 (setq rem (% m dm))))
17360 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17361 (setq m (+ m n)))
17362 (if (< m 0) (setq m (+ m 60) h (1- h)))
17363 (if (> m 59) (setq m (- m 60) h (1+ h)))
17364 (setq h (min 24 (max 0 h)))
17365 (setq ng 1 new (format "-%02d:%02d" h m)))
17366 ((org-pos-in-match-range pos 6)
17367 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17368 ((org-pos-in-match-range pos 5)
17369 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17371 ((org-pos-in-match-range pos 9)
17372 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17373 ((org-pos-in-match-range pos 8)
17374 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17376 (when ng
17377 (setq s (concat
17378 (substring s 0 (match-beginning ng))
17380 (substring s (match-end ng))))))
17383 (defun org-recenter-calendar (date)
17384 "If the calendar is visible, recenter it to DATE."
17385 (let ((cwin (get-buffer-window "*Calendar*" t)))
17386 (when cwin
17387 (let ((calendar-move-hook nil))
17388 (with-selected-window cwin
17389 (calendar-goto-date (if (listp date) date
17390 (calendar-gregorian-from-absolute date))))))))
17392 (defun org-goto-calendar (&optional arg)
17393 "Go to the Emacs calendar at the current date.
17394 If there is a time stamp in the current line, go to that date.
17395 A prefix ARG can be used to force the current date."
17396 (interactive "P")
17397 (let ((tsr org-ts-regexp) diff
17398 (calendar-move-hook nil)
17399 (calendar-view-holidays-initially-flag nil)
17400 (calendar-view-diary-initially-flag nil))
17401 (if (or (org-at-timestamp-p)
17402 (save-excursion
17403 (beginning-of-line 1)
17404 (looking-at (concat ".*" tsr))))
17405 (let ((d1 (time-to-days (current-time)))
17406 (d2 (time-to-days
17407 (org-time-string-to-time (match-string 1)))))
17408 (setq diff (- d2 d1))))
17409 (calendar)
17410 (calendar-goto-today)
17411 (if (and diff (not arg)) (calendar-forward-day diff))))
17413 (defun org-get-date-from-calendar ()
17414 "Return a list (month day year) of date at point in calendar."
17415 (with-current-buffer "*Calendar*"
17416 (save-match-data
17417 (calendar-cursor-to-date))))
17419 (defun org-date-from-calendar ()
17420 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17421 If there is already a time stamp at the cursor position, update it."
17422 (interactive)
17423 (if (org-at-timestamp-p t)
17424 (org-timestamp-change 0 'calendar)
17425 (let ((cal-date (org-get-date-from-calendar)))
17426 (org-insert-time-stamp
17427 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17429 (defcustom org-effort-durations
17430 `(("h" . 60)
17431 ("d" . ,(* 60 8))
17432 ("w" . ,(* 60 8 5))
17433 ("m" . ,(* 60 8 5 4))
17434 ("y" . ,(* 60 8 5 40)))
17435 "Conversion factor to minutes for an effort modifier.
17437 Each entry has the form (MODIFIER . MINUTES).
17439 In an effort string, a number followed by MODIFIER is multiplied
17440 by the specified number of MINUTES to obtain an effort in
17441 minutes.
17443 For example, if the value of this variable is ((\"hours\" . 60)), then an
17444 effort string \"2hours\" is equivalent to 120 minutes."
17445 :group 'org-agenda
17446 :version "24.1"
17447 :type '(alist :key-type (string :tag "Modifier")
17448 :value-type (number :tag "Minutes")))
17450 (defun org-minutes-to-clocksum-string (m)
17451 "Format number of minutes as a clocksum string.
17452 The format is determined by `org-time-clocksum-format',
17453 `org-time-clocksum-use-fractional' and
17454 `org-time-clocksum-fractional-format' and
17455 `org-time-clocksum-use-effort-durations'."
17456 (let ((clocksum "")
17457 (m (round m)) ; Don't allow fractions of minutes
17458 h d w mo y fmt n)
17459 (setq h (if org-time-clocksum-use-effort-durations
17460 (cdr (assoc "h" org-effort-durations)) 60)
17461 d (if org-time-clocksum-use-effort-durations
17462 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17463 w (if org-time-clocksum-use-effort-durations
17464 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17465 mo (if org-time-clocksum-use-effort-durations
17466 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17467 y (if org-time-clocksum-use-effort-durations
17468 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17469 ;; fractional format
17470 (if org-time-clocksum-use-fractional
17471 (cond
17472 ;; single format string
17473 ((stringp org-time-clocksum-fractional-format)
17474 (format org-time-clocksum-fractional-format (/ m (float h))))
17475 ;; choice of fractional formats for different time units
17476 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17477 (> (/ (truncate m) (* y d h)) 0))
17478 (format fmt (/ m (* y d (float h)))))
17479 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17480 (> (/ (truncate m) (* mo d h)) 0))
17481 (format fmt (/ m (* mo d (float h)))))
17482 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17483 (> (/ (truncate m) (* w d h)) 0))
17484 (format fmt (/ m (* w d (float h)))))
17485 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17486 (> (/ (truncate m) (* d h)) 0))
17487 (format fmt (/ m (* d (float h)))))
17488 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17489 (> (/ (truncate m) h) 0))
17490 (format fmt (/ m (float h))))
17491 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17492 (format fmt m))
17493 ;; fall back to smallest time unit with a format
17494 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17495 (format fmt (/ m (float h))))
17496 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17497 (format fmt (/ m (* d (float h)))))
17498 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17499 (format fmt (/ m (* w d (float h)))))
17500 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17501 (format fmt (/ m (* mo d (float h)))))
17502 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17503 (format fmt (/ m (* y d (float h))))))
17504 ;; standard (non-fractional) format, with single format string
17505 (if (stringp org-time-clocksum-format)
17506 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17507 ;; separate formats components
17508 (and (setq fmt (plist-get org-time-clocksum-format :years))
17509 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17510 (plist-get org-time-clocksum-format :require-years))
17511 (setq clocksum (concat clocksum (format fmt n))
17512 m (- m (* n y d h))))
17513 (and (setq fmt (plist-get org-time-clocksum-format :months))
17514 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17515 (plist-get org-time-clocksum-format :require-months))
17516 (setq clocksum (concat clocksum (format fmt n))
17517 m (- m (* n mo d h))))
17518 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17519 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17520 (plist-get org-time-clocksum-format :require-weeks))
17521 (setq clocksum (concat clocksum (format fmt n))
17522 m (- m (* n w d h))))
17523 (and (setq fmt (plist-get org-time-clocksum-format :days))
17524 (or (> (setq n (/ (truncate m) (* d h))) 0)
17525 (plist-get org-time-clocksum-format :require-days))
17526 (setq clocksum (concat clocksum (format fmt n))
17527 m (- m (* n d h))))
17528 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17529 (or (> (setq n (/ (truncate m) h)) 0)
17530 (plist-get org-time-clocksum-format :require-hours))
17531 (setq clocksum (concat clocksum (format fmt n))
17532 m (- m (* n h))))
17533 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17534 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17535 (setq clocksum (concat clocksum (format fmt m))))
17536 ;; return formatted time duration
17537 clocksum))))
17539 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17540 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17541 "Org mode version 8.0")
17543 (defun org-hours-to-clocksum-string (n)
17544 (org-minutes-to-clocksum-string (* n 60)))
17546 (defun org-hh:mm-string-to-minutes (s)
17547 "Convert a string H:MM to a number of minutes.
17548 If the string is just a number, interpret it as minutes.
17549 In fact, the first hh:mm or number in the string will be taken,
17550 there can be extra stuff in the string.
17551 If no number is found, the return value is 0."
17552 (cond
17553 ((integerp s) s)
17554 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17555 (+ (* (string-to-number (match-string 1 s)) 60)
17556 (string-to-number (match-string 2 s))))
17557 ((string-match "\\([0-9]+\\)" s)
17558 (string-to-number (match-string 1 s)))
17559 (t 0)))
17561 (defcustom org-image-actual-width t
17562 "Should we use the actual width of images when inlining them?
17564 When set to `t', always use the image width.
17566 When set to a number, use imagemagick (when available) to set
17567 the image's width to this value.
17569 When set to a number in a list, try to get the width from any
17570 #+ATTR.* keyword if it matches a width specification like
17572 #+ATTR_HTML: :width 300px
17574 and fall back on that number if none is found.
17576 When set to nil, try to get the width from an #+ATTR.* keyword
17577 and fall back on the original width if none is found.
17579 This requires Emacs >= 24.1, build with imagemagick support."
17580 :group 'org-appearance
17581 :version "24.4"
17582 :package-version '(Org . "8.0")
17583 :type '(choice
17584 (const :tag "Use the image width" t)
17585 (integer :tag "Use a number of pixels")
17586 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17587 (const :tag "Use #+ATTR* or don't resize" nil)))
17589 (defcustom org-agenda-inhibit-startup nil
17590 "Inhibit startup when preparing agenda buffers.
17591 When this variable is `t' (the default), the initialization of
17592 the Org agenda buffers is inhibited: e.g. the visibility state
17593 is not set, the tables are not re-aligned, etc."
17594 :type 'boolean
17595 :version "24.3"
17596 :group 'org-agenda)
17598 (defun org-duration-string-to-minutes (s &optional output-to-string)
17599 "Convert a duration string S to minutes.
17601 A bare number is interpreted as minutes, modifiers can be set by
17602 customizing `org-effort-durations' (which see).
17604 Entries containing a colon are interpreted as H:MM by
17605 `org-hh:mm-string-to-minutes'."
17606 (let ((result 0)
17607 (re (concat "\\([0-9.]+\\) *\\("
17608 (regexp-opt (mapcar 'car org-effort-durations))
17609 "\\)")))
17610 (while (string-match re s)
17611 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17612 (string-to-number (match-string 1 s))))
17613 (setq s (replace-match "" nil t s)))
17614 (setq result (floor result))
17615 (incf result (org-hh:mm-string-to-minutes s))
17616 (if output-to-string (number-to-string result) result)))
17618 ;;;; Files
17620 (defun org-save-all-org-buffers ()
17621 "Save all Org-mode buffers without user confirmation."
17622 (interactive)
17623 (message "Saving all Org-mode buffers...")
17624 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17625 (when (featurep 'org-id) (org-id-locations-save))
17626 (message "Saving all Org-mode buffers... done"))
17628 (defun org-revert-all-org-buffers ()
17629 "Revert all Org-mode buffers.
17630 Prompt for confirmation when there are unsaved changes.
17631 Be sure you know what you are doing before letting this function
17632 overwrite your changes.
17634 This function is useful in a setup where one tracks org files
17635 with a version control system, to revert on one machine after pulling
17636 changes from another. I believe the procedure must be like this:
17638 1. M-x org-save-all-org-buffers
17639 2. Pull changes from the other machine, resolve conflicts
17640 3. M-x org-revert-all-org-buffers"
17641 (interactive)
17642 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17643 (error "Abort"))
17644 (save-excursion
17645 (save-window-excursion
17646 (mapc
17647 (lambda (b)
17648 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17649 (with-current-buffer b buffer-file-name))
17650 (org-pop-to-buffer-same-window b)
17651 (revert-buffer t 'no-confirm)))
17652 (buffer-list))
17653 (when (and (featurep 'org-id) org-id-track-globally)
17654 (org-id-locations-load)))))
17656 ;;;; Agenda files
17658 ;;;###autoload
17659 (defun org-switchb (&optional arg)
17660 "Switch between Org buffers.
17661 With one prefix argument, restrict available buffers to files.
17662 With two prefix arguments, restrict available buffers to agenda files.
17664 Defaults to `iswitchb' for buffer name completion.
17665 Set `org-completion-use-ido' to make it use ido instead."
17666 (interactive "P")
17667 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17668 ((equal arg '(16)) (org-buffer-list 'agenda))
17669 (t (org-buffer-list))))
17670 (org-completion-use-iswitchb org-completion-use-iswitchb)
17671 (org-completion-use-ido org-completion-use-ido))
17672 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17673 (setq org-completion-use-iswitchb t))
17674 (org-pop-to-buffer-same-window
17675 (org-icompleting-read "Org buffer: "
17676 (mapcar 'list (mapcar 'buffer-name blist))
17677 nil t))))
17679 ;;; Define some older names previously used for this functionality
17680 ;;;###autoload
17681 (defalias 'org-ido-switchb 'org-switchb)
17682 ;;;###autoload
17683 (defalias 'org-iswitchb 'org-switchb)
17685 (defun org-buffer-list (&optional predicate exclude-tmp)
17686 "Return a list of Org buffers.
17687 PREDICATE can be `export', `files' or `agenda'.
17689 export restrict the list to Export buffers.
17690 files restrict the list to buffers visiting Org files.
17691 agenda restrict the list to buffers visiting agenda files.
17693 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17694 (let* ((bfn nil)
17695 (agenda-files (and (eq predicate 'agenda)
17696 (mapcar 'file-truename (org-agenda-files t))))
17697 (filter
17698 (cond
17699 ((eq predicate 'files)
17700 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17701 ((eq predicate 'export)
17702 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17703 ((eq predicate 'agenda)
17704 (lambda (b)
17705 (with-current-buffer b
17706 (and (derived-mode-p 'org-mode)
17707 (setq bfn (buffer-file-name b))
17708 (member (file-truename bfn) agenda-files)))))
17709 (t (lambda (b) (with-current-buffer b
17710 (or (derived-mode-p 'org-mode)
17711 (string-match "\*Org .*Export"
17712 (buffer-name b)))))))))
17713 (delq nil
17714 (mapcar
17715 (lambda(b)
17716 (if (and (funcall filter b)
17717 (or (not exclude-tmp)
17718 (not (string-match "tmp" (buffer-name b)))))
17720 nil))
17721 (buffer-list)))))
17723 (defun org-agenda-files (&optional unrestricted archives)
17724 "Get the list of agenda files.
17725 Optional UNRESTRICTED means return the full list even if a restriction
17726 is currently in place.
17727 When ARCHIVES is t, include all archive files that are really being
17728 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17729 `org-agenda-archives-mode' is t."
17730 (let ((files
17731 (cond
17732 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17733 ((stringp org-agenda-files) (org-read-agenda-file-list))
17734 ((listp org-agenda-files) org-agenda-files)
17735 (t (error "Invalid value of `org-agenda-files'")))))
17736 (setq files (apply 'append
17737 (mapcar (lambda (f)
17738 (if (file-directory-p f)
17739 (directory-files
17740 f t org-agenda-file-regexp)
17741 (list f)))
17742 files)))
17743 (when org-agenda-skip-unavailable-files
17744 (setq files (delq nil
17745 (mapcar (function
17746 (lambda (file)
17747 (and (file-readable-p file) file)))
17748 files))))
17749 (when (or (eq archives t)
17750 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17751 (setq files (org-add-archive-files files)))
17752 files))
17754 (defun org-agenda-file-p (&optional file)
17755 "Return non-nil, if FILE is an agenda file.
17756 If FILE is omitted, use the file associated with the current
17757 buffer."
17758 (member (or file (buffer-file-name))
17759 (org-agenda-files t)))
17761 (defun org-edit-agenda-file-list ()
17762 "Edit the list of agenda files.
17763 Depending on setup, this either uses customize to edit the variable
17764 `org-agenda-files', or it visits the file that is holding the list. In the
17765 latter case, the buffer is set up in a way that saving it automatically kills
17766 the buffer and restores the previous window configuration."
17767 (interactive)
17768 (if (stringp org-agenda-files)
17769 (let ((cw (current-window-configuration)))
17770 (find-file org-agenda-files)
17771 (org-set-local 'org-window-configuration cw)
17772 (org-add-hook 'after-save-hook
17773 (lambda ()
17774 (set-window-configuration
17775 (prog1 org-window-configuration
17776 (kill-buffer (current-buffer))))
17777 (org-install-agenda-files-menu)
17778 (message "New agenda file list installed"))
17779 nil 'local)
17780 (message "%s" (substitute-command-keys
17781 "Edit list and finish with \\[save-buffer]")))
17782 (customize-variable 'org-agenda-files)))
17784 (defun org-store-new-agenda-file-list (list)
17785 "Set new value for the agenda file list and save it correctly."
17786 (if (stringp org-agenda-files)
17787 (let ((fe (org-read-agenda-file-list t)) b u)
17788 (while (setq b (find-buffer-visiting org-agenda-files))
17789 (kill-buffer b))
17790 (with-temp-file org-agenda-files
17791 (insert
17792 (mapconcat
17793 (lambda (f) ;; Keep un-expanded entries.
17794 (if (setq u (assoc f fe))
17795 (cdr u)
17797 list "\n")
17798 "\n")))
17799 (let ((org-mode-hook nil) (org-inhibit-startup t)
17800 (org-insert-mode-line-in-empty-file nil))
17801 (setq org-agenda-files list)
17802 (customize-save-variable 'org-agenda-files org-agenda-files))))
17804 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17805 "Read the list of agenda files from a file.
17806 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17807 filenames, used by `org-store-new-agenda-file-list' to write back
17808 un-expanded file names."
17809 (when (file-directory-p org-agenda-files)
17810 (error "`org-agenda-files' cannot be a single directory"))
17811 (when (stringp org-agenda-files)
17812 (with-temp-buffer
17813 (insert-file-contents org-agenda-files)
17814 (mapcar
17815 (lambda (f)
17816 (let ((e (expand-file-name (substitute-in-file-name f)
17817 org-directory)))
17818 (if pair-with-expansion
17819 (cons e f)
17820 e)))
17821 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17823 ;;;###autoload
17824 (defun org-cycle-agenda-files ()
17825 "Cycle through the files in `org-agenda-files'.
17826 If the current buffer visits an agenda file, find the next one in the list.
17827 If the current buffer does not, find the first agenda file."
17828 (interactive)
17829 (let* ((fs (org-agenda-files t))
17830 (files (append fs (list (car fs))))
17831 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17832 file)
17833 (unless files (error "No agenda files"))
17834 (catch 'exit
17835 (while (setq file (pop files))
17836 (if (equal (file-truename file) tcf)
17837 (when (car files)
17838 (find-file (car files))
17839 (throw 'exit t))))
17840 (find-file (car fs)))
17841 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17843 (defun org-agenda-file-to-front (&optional to-end)
17844 "Move/add the current file to the top of the agenda file list.
17845 If the file is not present in the list, it is added to the front. If it is
17846 present, it is moved there. With optional argument TO-END, add/move to the
17847 end of the list."
17848 (interactive "P")
17849 (let ((org-agenda-skip-unavailable-files nil)
17850 (file-alist (mapcar (lambda (x)
17851 (cons (file-truename x) x))
17852 (org-agenda-files t)))
17853 (ctf (file-truename
17854 (or buffer-file-name
17855 (error "Please save the current buffer to a file"))))
17856 x had)
17857 (setq x (assoc ctf file-alist) had x)
17859 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17860 (if to-end
17861 (setq file-alist (append (delq x file-alist) (list x)))
17862 (setq file-alist (cons x (delq x file-alist))))
17863 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17864 (org-install-agenda-files-menu)
17865 (message "File %s to %s of agenda file list"
17866 (if had "moved" "added") (if to-end "end" "front"))))
17868 (defun org-remove-file (&optional file)
17869 "Remove current file from the list of files in variable `org-agenda-files'.
17870 These are the files which are being checked for agenda entries.
17871 Optional argument FILE means use this file instead of the current."
17872 (interactive)
17873 (let* ((org-agenda-skip-unavailable-files nil)
17874 (file (or file buffer-file-name
17875 (error "Current buffer does not visit a file")))
17876 (true-file (file-truename file))
17877 (afile (abbreviate-file-name file))
17878 (files (delq nil (mapcar
17879 (lambda (x)
17880 (if (equal true-file
17881 (file-truename x))
17882 nil x))
17883 (org-agenda-files t)))))
17884 (if (not (= (length files) (length (org-agenda-files t))))
17885 (progn
17886 (org-store-new-agenda-file-list files)
17887 (org-install-agenda-files-menu)
17888 (message "Removed file: %s" afile))
17889 (message "File was not in list: %s (not removed)" afile))))
17891 (defun org-file-menu-entry (file)
17892 (vector file (list 'find-file file) t))
17894 (defun org-check-agenda-file (file)
17895 "Make sure FILE exists. If not, ask user what to do."
17896 (when (not (file-exists-p file))
17897 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17898 (abbreviate-file-name file))
17899 (let ((r (downcase (read-char-exclusive))))
17900 (cond
17901 ((equal r ?r)
17902 (org-remove-file file)
17903 (throw 'nextfile t))
17904 (t (error "Abort"))))))
17906 (defun org-get-agenda-file-buffer (file)
17907 "Get a buffer visiting FILE. If the buffer needs to be created, add
17908 it to the list of buffers which might be released later."
17909 (let ((buf (org-find-base-buffer-visiting file)))
17910 (if buf
17911 buf ; just return it
17912 ;; Make a new buffer and remember it
17913 (setq buf (find-file-noselect file))
17914 (if buf (push buf org-agenda-new-buffers))
17915 buf)))
17917 (defun org-release-buffers (blist)
17918 "Release all buffers in list, asking the user for confirmation when needed.
17919 When a buffer is unmodified, it is just killed. When modified, it is saved
17920 \(if the user agrees) and then killed."
17921 (let (buf file)
17922 (while (setq buf (pop blist))
17923 (setq file (buffer-file-name buf))
17924 (when (and (buffer-modified-p buf)
17925 file
17926 (y-or-n-p (format "Save file %s? " file)))
17927 (with-current-buffer buf (save-buffer)))
17928 (kill-buffer buf))))
17930 (defun org-agenda-prepare-buffers (files)
17931 "Create buffers for all agenda files, protect archived trees and comments."
17932 (interactive)
17933 (let ((pa '(:org-archived t))
17934 (pc '(:org-comment t))
17935 (pall '(:org-archived t :org-comment t))
17936 (inhibit-read-only t)
17937 (org-inhibit-startup org-agenda-inhibit-startup)
17938 (rea (concat ":" org-archive-tag ":"))
17939 file re)
17940 (setq org-tag-alist-for-agenda nil
17941 org-tag-groups-alist-for-agenda nil)
17942 (save-excursion
17943 (save-restriction
17944 (while (setq file (pop files))
17945 (catch 'nextfile
17946 (if (bufferp file)
17947 (set-buffer file)
17948 (org-check-agenda-file file)
17949 (set-buffer (org-get-agenda-file-buffer file)))
17950 (widen)
17951 (org-set-regexps-and-options-for-tags)
17952 (org-refresh-category-properties)
17953 (org-refresh-properties org-effort-property 'org-effort)
17954 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17955 (setq org-todo-keywords-for-agenda
17956 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17957 (setq org-done-keywords-for-agenda
17958 (append org-done-keywords-for-agenda org-done-keywords))
17959 (setq org-todo-keyword-alist-for-agenda
17960 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17961 (setq org-drawers-for-agenda
17962 (append org-drawers-for-agenda org-drawers))
17963 (unless (equal org-tag-alist-for-agenda org-tag-alist)
17964 (setq org-tag-alist-for-agenda
17965 (append org-tag-alist-for-agenda org-tag-alist)))
17966 (if org-group-tags
17967 (setq org-tag-groups-alist-for-agenda
17968 (org-uniquify-alist
17969 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
17970 (org-with-silent-modifications
17971 (save-excursion
17972 (remove-text-properties (point-min) (point-max) pall)
17973 (when org-agenda-skip-archived-trees
17974 (goto-char (point-min))
17975 (while (re-search-forward rea nil t)
17976 (if (org-at-heading-p t)
17977 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17978 (goto-char (point-min))
17979 (setq re (format org-heading-keyword-regexp-format
17980 org-comment-string))
17981 (while (re-search-forward re nil t)
17982 (add-text-properties
17983 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17984 (setq org-todo-keywords-for-agenda
17985 (org-uniquify org-todo-keywords-for-agenda))
17986 (setq org-todo-keyword-alist-for-agenda
17987 (org-uniquify org-todo-keyword-alist-for-agenda))))
17990 ;;;; CDLaTeX minor mode
17992 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17993 "Keymap for the minor `org-cdlatex-mode'.")
17995 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17996 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17997 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17998 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17999 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18001 (defvar org-cdlatex-texmathp-advice-is-done nil
18002 "Flag remembering if we have applied the advice to texmathp already.")
18004 (define-minor-mode org-cdlatex-mode
18005 "Toggle the minor `org-cdlatex-mode'.
18006 This mode supports entering LaTeX environment and math in LaTeX fragments
18007 in Org-mode.
18008 \\{org-cdlatex-mode-map}"
18009 nil " OCDL" nil
18010 (when org-cdlatex-mode
18011 (require 'cdlatex)
18012 (run-hooks 'cdlatex-mode-hook)
18013 (cdlatex-compute-tables))
18014 (unless org-cdlatex-texmathp-advice-is-done
18015 (setq org-cdlatex-texmathp-advice-is-done t)
18016 (defadvice texmathp (around org-math-always-on activate)
18017 "Always return t in org-mode buffers.
18018 This is because we want to insert math symbols without dollars even outside
18019 the LaTeX math segments. If Orgmode thinks that point is actually inside
18020 an embedded LaTeX fragment, let texmathp do its job.
18021 \\[org-cdlatex-mode-map]"
18022 (interactive)
18023 (let (p)
18024 (cond
18025 ((not (derived-mode-p 'org-mode)) ad-do-it)
18026 ((eq this-command 'cdlatex-math-symbol)
18027 (setq ad-return-value t
18028 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18030 (let ((p (org-inside-LaTeX-fragment-p)))
18031 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18032 (setq ad-return-value t
18033 texmathp-why '("Org-mode embedded math" . 0))
18034 (if p ad-do-it)))))))))
18036 (defun turn-on-org-cdlatex ()
18037 "Unconditionally turn on `org-cdlatex-mode'."
18038 (org-cdlatex-mode 1))
18040 (defun org-try-cdlatex-tab ()
18041 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18042 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18043 - inside a LaTeX fragment, or
18044 - after the first word in a line, where an abbreviation expansion could
18045 insert a LaTeX environment."
18046 (when org-cdlatex-mode
18047 (cond
18048 ;; Before any word on the line: No expansion possible.
18049 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18050 ;; Just after first word on the line: Expand it. Make sure it
18051 ;; cannot happen on headlines, though.
18052 ((save-excursion
18053 (skip-chars-backward "a-zA-Z0-9*")
18054 (skip-chars-backward " \t")
18055 (and (bolp) (not (org-at-heading-p))))
18056 (cdlatex-tab) t)
18057 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18059 (defun org-cdlatex-underscore-caret (&optional arg)
18060 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18061 Revert to the normal definition outside of these fragments."
18062 (interactive "P")
18063 (if (org-inside-LaTeX-fragment-p)
18064 (call-interactively 'cdlatex-sub-superscript)
18065 (let (org-cdlatex-mode)
18066 (call-interactively (key-binding (vector last-input-event))))))
18068 (defun org-cdlatex-math-modify (&optional arg)
18069 "Execute `cdlatex-math-modify' 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-math-modify)
18074 (let (org-cdlatex-mode)
18075 (call-interactively (key-binding (vector last-input-event))))))
18079 ;;;; LaTeX fragments
18081 (defvar org-latex-regexps
18082 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18083 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18084 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18085 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18086 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18087 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18088 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18089 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18090 "Regular expressions for matching embedded LaTeX.")
18092 (defun org-inside-LaTeX-fragment-p ()
18093 "Test if point is inside a LaTeX fragment.
18094 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18095 sequence appearing also before point.
18096 Even though the matchers for math are configurable, this function assumes
18097 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18098 delimiters are skipped when they have been removed by customization.
18099 The return value is nil, or a cons cell with the delimiter and the
18100 position of this delimiter.
18102 This function does a reasonably good job, but can locally be fooled by
18103 for example currency specifications. For example it will assume being in
18104 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18105 fragments that are properly closed, but during editing, we have to live
18106 with the uncertainty caused by missing closing delimiters. This function
18107 looks only before point, not after."
18108 (catch 'exit
18109 (let ((pos (point))
18110 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18111 (lim (progn
18112 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18113 (point)))
18114 dd-on str (start 0) m re)
18115 (goto-char pos)
18116 (when dodollar
18117 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18118 re (nth 1 (assoc "$" org-latex-regexps)))
18119 (while (string-match re str start)
18120 (cond
18121 ((= (match-end 0) (length str))
18122 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18123 ((= (match-end 0) (- (length str) 5))
18124 (throw 'exit nil))
18125 (t (setq start (match-end 0))))))
18126 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18127 (goto-char pos)
18128 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18129 (and (match-beginning 2) (throw 'exit nil))
18130 ;; count $$
18131 (while (re-search-backward "\\$\\$" lim t)
18132 (setq dd-on (not dd-on)))
18133 (goto-char pos)
18134 (if dd-on (cons "$$" m))))))
18136 (defun org-inside-latex-macro-p ()
18137 "Is point inside a LaTeX macro or its arguments?"
18138 (save-match-data
18139 (org-in-regexp
18140 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18142 (defvar org-latex-fragment-image-overlays nil
18143 "List of overlays carrying the images of latex fragments.")
18144 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18146 (defun org-remove-latex-fragment-image-overlays ()
18147 "Remove all overlays with LaTeX fragment images in current buffer."
18148 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18149 (setq org-latex-fragment-image-overlays nil))
18151 (defun org-preview-latex-fragment (&optional subtree)
18152 "Preview the LaTeX fragment at point, or all locally or globally.
18153 If the cursor is in a LaTeX fragment, create the image and overlay
18154 it over the source code. If there is no fragment at point, display
18155 all fragments in the current text, from one headline to the next. With
18156 prefix SUBTREE, display all fragments in the current subtree. With a
18157 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18158 the cursor is before the first headline,
18159 display all fragments in the buffer.
18160 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18161 (interactive "P")
18162 (unless buffer-file-name
18163 (error "Can't preview LaTeX fragment in a non-file buffer"))
18164 (org-remove-latex-fragment-image-overlays)
18165 (save-excursion
18166 (save-restriction
18167 (let (beg end at msg)
18168 (cond
18169 ((or (equal subtree '(16))
18170 (not (save-excursion
18171 (re-search-backward org-outline-regexp-bol nil t))))
18172 (setq beg (point-min) end (point-max)
18173 msg "Creating images for buffer...%s"))
18174 ((equal subtree '(4))
18175 (org-back-to-heading)
18176 (setq beg (point) end (org-end-of-subtree t)
18177 msg "Creating images for subtree...%s"))
18179 (if (setq at (org-inside-LaTeX-fragment-p))
18180 (goto-char (max (point-min) (- (cdr at) 2)))
18181 (org-back-to-heading))
18182 (setq beg (point) end (progn (outline-next-heading) (point))
18183 msg (if at "Creating image...%s"
18184 "Creating images for entry...%s"))))
18185 (message msg "")
18186 (narrow-to-region beg end)
18187 (goto-char beg)
18188 (org-format-latex
18189 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18190 (file-name-nondirectory
18191 buffer-file-name)))
18192 default-directory 'overlays msg at 'forbuffer
18193 org-latex-create-formula-image-program)
18194 (message msg "done. Use `C-c C-c' to remove images.")))))
18196 (defun org-format-latex (prefix &optional dir overlays msg at
18197 forbuffer processing-type)
18198 "Replace LaTeX fragments with links to an image, and produce images.
18199 Some of the options can be changed using the variable
18200 `org-format-latex-options'."
18201 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18202 (let* ((prefixnodir (file-name-nondirectory prefix))
18203 (absprefix (expand-file-name prefix dir))
18204 (todir (file-name-directory absprefix))
18205 (opt org-format-latex-options)
18206 (optnew org-format-latex-options)
18207 (matchers (plist-get opt :matchers))
18208 (re-list org-latex-regexps)
18209 (cnt 0) txt hash link beg end re e checkdir
18210 string
18211 m n block-type block linkfile movefile ov)
18212 ;; Check the different regular expressions
18213 (while (setq e (pop re-list))
18214 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18215 block (if block-type "\n\n" ""))
18216 (when (member m matchers)
18217 (goto-char (point-min))
18218 (while (re-search-forward re nil t)
18219 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18220 (or (not overlays)
18221 (not (eq (get-char-property (match-beginning n)
18222 'org-overlay-type)
18223 'org-latex-overlay))))
18224 (cond
18225 ((eq processing-type 'verbatim))
18226 ((eq processing-type 'mathjax)
18227 ;; Prepare for MathJax processing.
18228 (setq string (match-string n))
18229 (when (member m '("$" "$1"))
18230 (save-excursion
18231 (delete-region (match-beginning n) (match-end n))
18232 (goto-char (match-beginning n))
18233 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18234 ((or (eq processing-type 'dvipng)
18235 (eq processing-type 'imagemagick))
18236 ;; Process to an image.
18237 (setq txt (match-string n)
18238 beg (match-beginning n) end (match-end n)
18239 cnt (1+ cnt))
18240 (let ((face (face-at-point))
18241 (fg (plist-get opt :foreground))
18242 (bg (plist-get opt :background))
18243 ;; Ensure full list is printed.
18244 print-length print-level)
18245 (when forbuffer
18246 ;; Get the colors from the face at point.
18247 (goto-char beg)
18248 (when (eq fg 'auto)
18249 (setq fg (face-attribute face :foreground nil 'default)))
18250 (when (eq bg 'auto)
18251 (setq bg (face-attribute face :background nil 'default)))
18252 (setq optnew (copy-sequence opt))
18253 (plist-put optnew :foreground fg)
18254 (plist-put optnew :background bg))
18255 (setq hash (sha1 (prin1-to-string
18256 (list org-format-latex-header
18257 org-latex-default-packages-alist
18258 org-latex-packages-alist
18259 org-format-latex-options
18260 forbuffer txt fg bg)))
18261 linkfile (format "%s_%s.png" prefix hash)
18262 movefile (format "%s_%s.png" absprefix hash)))
18263 (setq link (concat block "[[file:" linkfile "]]" block))
18264 (if msg (message msg cnt))
18265 (goto-char beg)
18266 (unless checkdir ; Ensure the directory exists.
18267 (setq checkdir t)
18268 (or (file-directory-p todir) (make-directory todir t)))
18269 (unless (file-exists-p movefile)
18270 (org-create-formula-image
18271 txt movefile optnew forbuffer processing-type))
18272 (if overlays
18273 (progn
18274 (mapc (lambda (o)
18275 (if (eq (overlay-get o 'org-overlay-type)
18276 'org-latex-overlay)
18277 (delete-overlay o)))
18278 (overlays-in beg end))
18279 (setq ov (make-overlay beg end))
18280 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18281 (if (featurep 'xemacs)
18282 (progn
18283 (overlay-put ov 'invisible t)
18284 (overlay-put
18285 ov 'end-glyph
18286 (make-glyph (vector 'png :file movefile))))
18287 (overlay-put
18288 ov 'display
18289 (list 'image :type 'png :file movefile :ascent 'center)))
18290 (push ov org-latex-fragment-image-overlays)
18291 (goto-char end))
18292 (delete-region beg end)
18293 (insert (org-add-props link
18294 (list 'org-latex-src
18295 (replace-regexp-in-string
18296 "\"" "" txt)
18297 'org-latex-src-embed-type
18298 (if block-type 'paragraph 'character))))))
18299 ((eq processing-type 'mathml)
18300 ;; Process to MathML
18301 (unless (save-match-data (org-format-latex-mathml-available-p))
18302 (error "LaTeX to MathML converter not configured"))
18303 (setq txt (match-string n)
18304 beg (match-beginning n) end (match-end n)
18305 cnt (1+ cnt))
18306 (if msg (message msg cnt))
18307 (goto-char beg)
18308 (delete-region beg end)
18309 (insert (org-format-latex-as-mathml
18310 txt block-type prefix dir)))
18312 (error "Unknown conversion type %s for latex fragments"
18313 processing-type)))))))))
18315 (defun org-create-math-formula (latex-frag &optional mathml-file)
18316 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18317 Use `org-latex-to-mathml-convert-command'. If the conversion is
18318 sucessful, return the portion between \"<math...> </math>\"
18319 elements otherwise return nil. When MATHML-FILE is specified,
18320 write the results in to that file. When invoked as an
18321 interactive command, prompt for LATEX-FRAG, with initial value
18322 set to the current active region and echo the results for user
18323 inspection."
18324 (interactive (list (let ((frag (when (org-region-active-p)
18325 (buffer-substring-no-properties
18326 (region-beginning) (region-end)))))
18327 (read-string "LaTeX Fragment: " frag nil frag))))
18328 (unless latex-frag (error "Invalid latex-frag"))
18329 (let* ((tmp-in-file (file-relative-name
18330 (make-temp-name (expand-file-name "ltxmathml-in"))))
18331 (ignore (write-region latex-frag nil tmp-in-file))
18332 (tmp-out-file (file-relative-name
18333 (make-temp-name (expand-file-name "ltxmathml-out"))))
18334 (cmd (format-spec
18335 org-latex-to-mathml-convert-command
18336 `((?j . ,(shell-quote-argument
18337 (expand-file-name org-latex-to-mathml-jar-file)))
18338 (?I . ,(shell-quote-argument tmp-in-file))
18339 (?o . ,(shell-quote-argument tmp-out-file)))))
18340 mathml shell-command-output)
18341 (when (org-called-interactively-p 'any)
18342 (unless (org-format-latex-mathml-available-p)
18343 (error "LaTeX to MathML converter not configured")))
18344 (message "Running %s" cmd)
18345 (setq shell-command-output (shell-command-to-string cmd))
18346 (setq mathml
18347 (when (file-readable-p tmp-out-file)
18348 (with-current-buffer (find-file-noselect tmp-out-file t)
18349 (goto-char (point-min))
18350 (when (re-search-forward
18351 (concat
18352 (regexp-quote
18353 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18354 "\\(.\\|\n\\)*"
18355 (regexp-quote "</math>")) nil t)
18356 (prog1 (match-string 0) (kill-buffer))))))
18357 (cond
18358 (mathml
18359 (setq mathml
18360 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18361 (when mathml-file
18362 (write-region mathml nil mathml-file))
18363 (when (org-called-interactively-p 'any)
18364 (message mathml)))
18365 ((message "LaTeX to MathML conversion failed")
18366 (message shell-command-output)))
18367 (delete-file tmp-in-file)
18368 (when (file-exists-p tmp-out-file)
18369 (delete-file tmp-out-file))
18370 mathml))
18372 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18373 prefix &optional dir)
18374 "Use `org-create-math-formula' but check local cache first."
18375 (let* ((absprefix (expand-file-name prefix dir))
18376 (print-length nil) (print-level nil)
18377 (formula-id (concat
18378 "formula-"
18379 (sha1
18380 (prin1-to-string
18381 (list latex-frag
18382 org-latex-to-mathml-convert-command)))))
18383 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18384 (formula-cache-dir (file-name-directory formula-cache)))
18386 (unless (file-directory-p formula-cache-dir)
18387 (make-directory formula-cache-dir t))
18389 (unless (file-exists-p formula-cache)
18390 (org-create-math-formula latex-frag formula-cache))
18392 (if (file-exists-p formula-cache)
18393 ;; Successful conversion. Return the link to MathML file.
18394 (org-add-props
18395 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18396 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18397 'org-latex-src-embed-type (if latex-frag-type
18398 'paragraph 'character)))
18399 ;; Failed conversion. Return the LaTeX fragment verbatim
18400 latex-frag)))
18402 (defun org-create-formula-image (string tofile options buffer &optional type)
18403 "Create an image from LaTeX source using dvipng or convert.
18404 This function calls either `org-create-formula-image-with-dvipng'
18405 or `org-create-formula-image-with-imagemagick' depending on the
18406 value of `org-latex-create-formula-image-program' or on the value
18407 of the optional TYPE variable.
18409 Note: ultimately these two function should be combined as they
18410 share a good deal of logic."
18411 (org-check-external-command
18412 "latex" "needed to convert LaTeX fragments to images")
18413 (funcall
18414 (case (or type org-latex-create-formula-image-program)
18415 ('dvipng
18416 (org-check-external-command
18417 "dvipng" "needed to convert LaTeX fragments to images")
18418 #'org-create-formula-image-with-dvipng)
18419 ('imagemagick
18420 (org-check-external-command
18421 "convert" "you need to install imagemagick")
18422 #'org-create-formula-image-with-imagemagick)
18423 (t (error
18424 "invalid value of `org-latex-create-formula-image-program'")))
18425 string tofile options buffer))
18427 (declare-function org-export--get-global-options "ox" (&optional backend))
18428 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18429 (defun org-create-formula--latex-header ()
18430 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18431 (org-latex-guess-inputenc
18432 (org-splice-latex-header
18433 org-format-latex-header
18434 org-latex-default-packages-alist
18435 org-latex-packages-alist t
18436 (plist-get
18437 (org-combine-plists
18438 (org-export--get-global-options 'latex)
18439 (org-export--get-inbuffer-options 'latex))
18440 :latex-header))))
18442 ;; This function borrows from Ganesh Swami's latex2png.el
18443 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18444 "This calls dvipng."
18445 (require 'ox-latex)
18446 (let* ((tmpdir (if (featurep 'xemacs)
18447 (temp-directory)
18448 temporary-file-directory))
18449 (texfilebase (make-temp-name
18450 (expand-file-name "orgtex" tmpdir)))
18451 (texfile (concat texfilebase ".tex"))
18452 (dvifile (concat texfilebase ".dvi"))
18453 (pngfile (concat texfilebase ".png"))
18454 (fnh (if (featurep 'xemacs)
18455 (font-height (face-font 'default))
18456 (face-attribute 'default :height nil)))
18457 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18458 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18459 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18460 "Black"))
18461 (bg (or (plist-get options (if buffer :background :html-background))
18462 "Transparent")))
18463 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18464 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18465 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18466 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18467 (let ((latex-header (org-create-formula--latex-header)))
18468 (with-temp-file texfile
18469 (insert latex-header)
18470 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18471 (let ((dir default-directory))
18472 (condition-case nil
18473 (progn
18474 (cd tmpdir)
18475 (call-process "latex" nil nil nil texfile))
18476 (error nil))
18477 (cd dir))
18478 (if (not (file-exists-p dvifile))
18479 (progn (message "Failed to create dvi file from %s" texfile) nil)
18480 (condition-case nil
18481 (if (featurep 'xemacs)
18482 (call-process "dvipng" nil nil nil
18483 "-fg" fg "-bg" bg
18484 "-T" "tight"
18485 "-o" pngfile
18486 dvifile)
18487 (call-process "dvipng" nil nil nil
18488 "-fg" fg "-bg" bg
18489 "-D" dpi
18490 ;;"-x" scale "-y" scale
18491 "-T" "tight"
18492 "-o" pngfile
18493 dvifile))
18494 (error nil))
18495 (if (not (file-exists-p pngfile))
18496 (if org-format-latex-signal-error
18497 (error "Failed to create png file from %s" texfile)
18498 (message "Failed to create png file from %s" texfile)
18499 nil)
18500 ;; Use the requested file name and clean up
18501 (copy-file pngfile tofile 'replace)
18502 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18503 (if (file-exists-p (concat texfilebase e))
18504 (delete-file (concat texfilebase e))))
18505 pngfile))))
18507 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18508 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18509 "This calls convert, which is included into imagemagick."
18510 (require 'ox-latex)
18511 (let* ((tmpdir (if (featurep 'xemacs)
18512 (temp-directory)
18513 temporary-file-directory))
18514 (texfilebase (make-temp-name
18515 (expand-file-name "orgtex" tmpdir)))
18516 (texfile (concat texfilebase ".tex"))
18517 (pdffile (concat texfilebase ".pdf"))
18518 (pngfile (concat texfilebase ".png"))
18519 (fnh (if (featurep 'xemacs)
18520 (font-height (face-font 'default))
18521 (face-attribute 'default :height nil)))
18522 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18523 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18524 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18525 "black"))
18526 (bg (or (plist-get options (if buffer :background :html-background))
18527 "white")))
18528 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18529 (setq fg (org-latex-color-format fg)))
18530 (if (eq bg 'default) (setq bg (org-latex-color :background))
18531 (setq bg (org-latex-color-format
18532 (if (string= bg "Transparent") "white" bg))))
18533 (let ((latex-header (org-create-formula--latex-header)))
18534 (with-temp-file texfile
18535 (insert latex-header)
18536 (insert "\n\\begin{document}\n"
18537 "\\definecolor{fg}{rgb}{" fg "}\n"
18538 "\\definecolor{bg}{rgb}{" bg "}\n"
18539 "\n\\pagecolor{bg}\n"
18540 "\n{\\color{fg}\n"
18541 string
18542 "\n}\n"
18543 "\n\\end{document}\n")))
18544 (org-latex-compile texfile t)
18545 (if (not (file-exists-p pdffile))
18546 (progn (message "Failed to create pdf file from %s" texfile) nil)
18547 (condition-case nil
18548 (if (featurep 'xemacs)
18549 (call-process "convert" nil nil nil
18550 "-density" "96"
18551 "-trim"
18552 "-antialias"
18553 pdffile
18554 "-quality" "100"
18555 ;; "-sharpen" "0x1.0"
18556 pngfile)
18557 (call-process "convert" nil nil nil
18558 "-density" dpi
18559 "-trim"
18560 "-antialias"
18561 pdffile
18562 "-quality" "100"
18563 ;; "-sharpen" "0x1.0"
18564 pngfile))
18565 (error nil))
18566 (if (not (file-exists-p pngfile))
18567 (if org-format-latex-signal-error
18568 (error "Failed to create png file from %s" texfile)
18569 (message "Failed to create png file from %s" texfile)
18570 nil)
18571 ;; Use the requested file name and clean up
18572 (copy-file pngfile tofile 'replace)
18573 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18574 (if (file-exists-p (concat texfilebase e))
18575 (delete-file (concat texfilebase e))))
18576 pngfile))))
18578 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18579 "Fill a LaTeX header template TPL.
18580 In the template, the following place holders will be recognized:
18582 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18583 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18584 [PACKAGES] \\usepackage statements for PKG
18585 [NO-PACKAGES] do not include PKG
18586 [EXTRA] the string EXTRA
18587 [NO-EXTRA] do not include EXTRA
18589 For backward compatibility, if both the positive and the negative place
18590 holder is missing, the positive one (without the \"NO-\") will be
18591 assumed to be present at the end of the template.
18592 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18593 EXTRA is a string.
18594 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18595 (let (rpl (end ""))
18596 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18597 (setq rpl (if (or (match-end 1) (not def-pkg))
18598 "" (org-latex-packages-to-string def-pkg snippets-p t))
18599 tpl (replace-match rpl t t tpl))
18600 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18602 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18603 (setq rpl (if (or (match-end 1) (not pkg))
18604 "" (org-latex-packages-to-string pkg snippets-p t))
18605 tpl (replace-match rpl t t tpl))
18606 (if pkg (setq end
18607 (concat end "\n"
18608 (org-latex-packages-to-string pkg snippets-p)))))
18610 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18611 (setq rpl (if (or (match-end 1) (not extra))
18612 "" (concat extra "\n"))
18613 tpl (replace-match rpl t t tpl))
18614 (if (and extra (string-match "\\S-" extra))
18615 (setq end (concat end "\n" extra))))
18617 (if (string-match "\\S-" end)
18618 (concat tpl "\n" end)
18619 tpl)))
18621 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18622 "Turn an alist of packages into a string with the \\usepackage macros."
18623 (setq pkg (mapconcat (lambda(p)
18624 (cond
18625 ((stringp p) p)
18626 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18627 (format "%% Package %s omitted" (cadr p)))
18628 ((equal "" (car p))
18629 (format "\\usepackage{%s}" (cadr p)))
18631 (format "\\usepackage[%s]{%s}"
18632 (car p) (cadr p)))))
18634 "\n"))
18635 (if newline (concat pkg "\n") pkg))
18637 (defun org-dvipng-color (attr)
18638 "Return a RGB color specification for dvipng."
18639 (apply 'format "rgb %s %s %s"
18640 (mapcar 'org-normalize-color
18641 (if (featurep 'xemacs)
18642 (color-rgb-components
18643 (face-property 'default
18644 (cond ((eq attr :foreground) 'foreground)
18645 ((eq attr :background) 'background))))
18646 (color-values (face-attribute 'default attr nil))))))
18648 (defun org-dvipng-color-format (color-name)
18649 "Convert COLOR-NAME to a RGB color value for dvipng."
18650 (apply 'format "rgb %s %s %s"
18651 (mapcar 'org-normalize-color
18652 (color-values color-name))))
18654 (defun org-latex-color (attr)
18655 "Return a RGB color for the LaTeX color package."
18656 (apply 'format "%s,%s,%s"
18657 (mapcar 'org-normalize-color
18658 (if (featurep 'xemacs)
18659 (color-rgb-components
18660 (face-property 'default
18661 (cond ((eq attr :foreground) 'foreground)
18662 ((eq attr :background) 'background))))
18663 (color-values (face-attribute 'default attr nil))))))
18665 (defun org-latex-color-format (color-name)
18666 "Convert COLOR-NAME to a RGB color value."
18667 (apply 'format "%s,%s,%s"
18668 (mapcar 'org-normalize-color
18669 (color-values color-name))))
18671 (defun org-normalize-color (value)
18672 "Return string to be used as color value for an RGB component."
18673 (format "%g" (/ value 65535.0)))
18677 ;; Image display
18679 (defvar org-inline-image-overlays nil)
18680 (make-variable-buffer-local 'org-inline-image-overlays)
18682 (defun org-toggle-inline-images (&optional include-linked)
18683 "Toggle the display of inline images.
18684 INCLUDE-LINKED is passed to `org-display-inline-images'."
18685 (interactive "P")
18686 (if org-inline-image-overlays
18687 (progn
18688 (org-remove-inline-images)
18689 (message "Inline image display turned off"))
18690 (org-display-inline-images include-linked)
18691 (if (and (org-called-interactively-p)
18692 org-inline-image-overlays)
18693 (message "%d images displayed inline"
18694 (length org-inline-image-overlays))
18695 (message "No images to display inline"))))
18697 (defun org-redisplay-inline-images ()
18698 "Refresh the display of inline images."
18699 (interactive)
18700 (if (not org-inline-image-overlays)
18701 (org-toggle-inline-images)
18702 (org-toggle-inline-images)
18703 (org-toggle-inline-images)))
18705 (defun org-display-inline-images (&optional include-linked refresh beg end)
18706 "Display inline images.
18707 Normally only links without a description part are inlined, because this
18708 is how it will work for export. When INCLUDE-LINKED is set, also links
18709 with a description part will be inlined. This can be nice for a quick
18710 look at those images, but it does not reflect what exported files will look
18711 like.
18712 When REFRESH is set, refresh existing images between BEG and END.
18713 This will create new image displays only if necessary.
18714 BEG and END default to the buffer boundaries."
18715 (interactive "P")
18716 (unless refresh
18717 (org-remove-inline-images)
18718 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18719 (save-excursion
18720 (save-restriction
18721 (widen)
18722 (setq beg (or beg (point-min)) end (or end (point-max)))
18723 (goto-char beg)
18724 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18725 (substring (org-image-file-name-regexp) 0 -2)
18726 "\\)\\]" (if include-linked "" "\\]")))
18727 (case-fold-search t)
18728 old file ov img type attrwidth width)
18729 (while (re-search-forward re end t)
18730 (setq old (get-char-property-and-overlay (match-beginning 1)
18731 'org-image-overlay)
18732 file (expand-file-name
18733 (concat (or (match-string 3) "") (match-string 4))))
18734 (when (image-type-available-p 'imagemagick)
18735 (setq attrwidth (if (or (listp org-image-actual-width)
18736 (null org-image-actual-width))
18737 (save-excursion
18738 (save-match-data
18739 (when (re-search-backward
18740 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18741 (save-excursion
18742 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18743 (string-to-number (match-string 1))))))
18744 width (cond ((eq org-image-actual-width t) nil)
18745 ((null org-image-actual-width) attrwidth)
18746 ((numberp org-image-actual-width)
18747 org-image-actual-width)
18748 ((listp org-image-actual-width)
18749 (or attrwidth (car org-image-actual-width))))
18750 type (if width 'imagemagick)))
18751 (when (file-exists-p file)
18752 (if (and (car-safe old) refresh)
18753 (image-refresh (overlay-get (cdr old) 'display))
18754 (setq img (save-match-data (create-image file type nil :width width)))
18755 (when img
18756 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18757 (overlay-put ov 'display img)
18758 (overlay-put ov 'face 'default)
18759 (overlay-put ov 'org-image-overlay t)
18760 (overlay-put ov 'modification-hooks
18761 (list 'org-display-inline-remove-overlay))
18762 (push ov org-inline-image-overlays)))))))))
18764 (define-obsolete-function-alias
18765 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18767 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18768 "Remove inline-display overlay if a corresponding region is modified."
18769 (let ((inhibit-modification-hooks t))
18770 (when (and ov after)
18771 (delete ov org-inline-image-overlays)
18772 (delete-overlay ov))))
18774 (defun org-remove-inline-images ()
18775 "Remove inline display of images."
18776 (interactive)
18777 (mapc 'delete-overlay org-inline-image-overlays)
18778 (setq org-inline-image-overlays nil))
18780 ;;;; Key bindings
18782 ;; Outline functions from `outline-mode-prefix-map'
18783 ;; that can be remapped in Org:
18784 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18785 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18786 (define-key org-mode-map [remap outline-forward-same-level]
18787 'org-forward-heading-same-level)
18788 (define-key org-mode-map [remap outline-backward-same-level]
18789 'org-backward-heading-same-level)
18790 (define-key org-mode-map [remap show-branches]
18791 'org-kill-note-or-show-branches)
18792 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18793 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18794 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18796 ;; Outline functions from `outline-mode-prefix-map' that can not
18797 ;; be remapped in Org:
18799 ;; - the column "key binding" shows whether the Outline function is still
18800 ;; available in Org mode on the same key that it has been bound to in
18801 ;; Outline mode:
18802 ;; - "overridden": key used for a different functionality in Org mode
18803 ;; - else: key still bound to the same Outline function in Org mode
18805 ;; | Outline function | key binding | Org replacement |
18806 ;; |------------------------------------+-------------+-----------------------|
18807 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18808 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18809 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18810 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18811 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18812 ;; | `show-entry' | overridden | no replacement |
18813 ;; | `show-children' | `C-c C-i' | visibility cycling |
18814 ;; | `show-branches' | `C-c C-k' | still same function |
18815 ;; | `show-subtree' | overridden | visibility cycling |
18816 ;; | `show-all' | overridden | no replacement |
18817 ;; | `hide-subtree' | overridden | visibility cycling |
18818 ;; | `hide-body' | overridden | no replacement |
18819 ;; | `hide-entry' | overridden | visibility cycling |
18820 ;; | `hide-leaves' | overridden | no replacement |
18821 ;; | `hide-sublevels' | overridden | no replacement |
18822 ;; | `hide-other' | overridden | no replacement |
18824 ;; Make `C-c C-x' a prefix key
18825 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18827 ;; TAB key with modifiers
18828 (org-defkey org-mode-map "\C-i" 'org-cycle)
18829 (org-defkey org-mode-map [(tab)] 'org-cycle)
18830 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18831 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18832 ;; The following line is necessary under Suse GNU/Linux
18833 (unless (featurep 'xemacs)
18834 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18835 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18836 (define-key org-mode-map [backtab] 'org-shifttab)
18838 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18839 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18840 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18842 ;; Cursor keys with modifiers
18843 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18844 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18845 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18846 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18848 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18849 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18850 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18851 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18853 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18854 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18855 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18856 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18858 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18859 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18860 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18861 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18863 ;; Babel keys
18864 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18865 (mapc (lambda (pair)
18866 (define-key org-babel-map (car pair) (cdr pair)))
18867 org-babel-key-bindings)
18869 ;;; Extra keys for tty access.
18870 ;; We only set them when really needed because otherwise the
18871 ;; menus don't show the simple keys
18873 (when (or org-use-extra-keys
18874 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18875 (not window-system))
18876 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18877 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18878 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18879 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18880 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18881 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18882 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18883 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18884 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18885 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18886 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18887 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18888 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18889 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18890 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18891 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18892 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18893 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18894 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18895 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18896 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18897 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18898 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18899 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18900 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18901 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18902 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18903 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18905 ;; All the other keys
18907 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18908 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18909 (if (boundp 'narrow-map)
18910 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18911 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18912 (if (boundp 'narrow-map)
18913 (org-defkey narrow-map "b" 'org-narrow-to-block)
18914 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18915 (if (boundp 'narrow-map)
18916 (org-defkey narrow-map "e" 'org-narrow-to-element)
18917 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18918 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18919 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18920 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18921 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18922 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18923 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18924 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18925 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18926 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18927 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18928 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18929 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18930 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18931 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18932 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18933 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18934 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18935 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18936 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18937 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18938 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18939 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18940 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18941 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18942 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18943 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18944 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18945 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18946 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18947 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18948 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18949 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18950 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18951 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18952 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18953 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18954 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18955 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18956 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18957 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18958 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18959 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18960 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18961 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18962 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18963 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18964 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18965 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18966 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18967 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18968 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18969 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18970 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18971 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18972 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18973 (org-defkey org-mode-map "\C-c^" 'org-sort)
18974 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18975 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18976 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18977 (org-defkey org-mode-map "\C-o" 'org-ctrl-o)
18978 (org-defkey org-mode-map "\C-m" 'org-return)
18979 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18980 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18981 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18982 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18983 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18984 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18985 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18986 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18987 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18988 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18989 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18990 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18991 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18992 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18993 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18994 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18995 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18996 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18997 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18998 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18999 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19000 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19001 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19003 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19004 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19005 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19007 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19008 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19009 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19010 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19011 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19012 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19013 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19014 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19015 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19016 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19017 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19018 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19019 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19020 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19021 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19022 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19023 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19024 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19025 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19026 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19027 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19028 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19029 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19031 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19032 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19033 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19034 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19035 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19037 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19039 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19041 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19042 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19044 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19047 (when (featurep 'xemacs)
19048 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19051 (defconst org-speed-commands-default
19053 ("Outline Navigation")
19054 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19055 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19056 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19057 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19058 ("F" . org-next-block)
19059 ("B" . org-previous-block)
19060 ("u" . (org-speed-move-safe 'outline-up-heading))
19061 ("j" . org-goto)
19062 ("g" . (org-refile t))
19063 ("Outline Visibility")
19064 ("c" . org-cycle)
19065 ("C" . org-shifttab)
19066 (" " . org-display-outline-path)
19067 ("s" . org-narrow-to-subtree)
19068 ("=" . org-columns)
19069 ("Outline Structure Editing")
19070 ("U" . org-shiftmetaup)
19071 ("D" . org-shiftmetadown)
19072 ("r" . org-metaright)
19073 ("l" . org-metaleft)
19074 ("R" . org-shiftmetaright)
19075 ("L" . org-shiftmetaleft)
19076 ("i" . (progn (forward-char 1) (call-interactively
19077 'org-insert-heading-respect-content)))
19078 ("^" . org-sort)
19079 ("w" . org-refile)
19080 ("a" . org-archive-subtree-default-with-confirmation)
19081 ("@" . org-mark-subtree)
19082 ("#" . org-toggle-comment)
19083 ("Clock Commands")
19084 ("I" . org-clock-in)
19085 ("O" . org-clock-out)
19086 ("Meta Data Editing")
19087 ("t" . org-todo)
19088 ("," . (org-priority))
19089 ("0" . (org-priority ?\ ))
19090 ("1" . (org-priority ?A))
19091 ("2" . (org-priority ?B))
19092 ("3" . (org-priority ?C))
19093 (":" . org-set-tags-command)
19094 ("e" . org-set-effort)
19095 ("E" . org-inc-effort)
19096 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19097 (org-entry-put (point) "APPT_WARNTIME" m)))
19098 ("Agenda Views etc")
19099 ("v" . org-agenda)
19100 ("/" . org-sparse-tree)
19101 ("Misc")
19102 ("o" . org-open-at-point)
19103 ("?" . org-speed-command-help)
19104 ("<" . (org-agenda-set-restriction-lock 'subtree))
19105 (">" . (org-agenda-remove-restriction-lock))
19107 "The default speed commands.")
19109 (defun org-print-speed-command (e)
19110 (if (> (length (car e)) 1)
19111 (progn
19112 (princ "\n")
19113 (princ (car e))
19114 (princ "\n")
19115 (princ (make-string (length (car e)) ?-))
19116 (princ "\n"))
19117 (princ (car e))
19118 (princ " ")
19119 (if (symbolp (cdr e))
19120 (princ (symbol-name (cdr e)))
19121 (prin1 (cdr e)))
19122 (princ "\n")))
19124 (defun org-speed-command-help ()
19125 "Show the available speed commands."
19126 (interactive)
19127 (if (not org-use-speed-commands)
19128 (error "Speed commands are not activated, customize `org-use-speed-commands'")
19129 (with-output-to-temp-buffer "*Help*"
19130 (princ "User-defined Speed commands\n===========================\n")
19131 (mapc 'org-print-speed-command org-speed-commands-user)
19132 (princ "\n")
19133 (princ "Built-in Speed commands\n=======================\n")
19134 (mapc 'org-print-speed-command org-speed-commands-default))
19135 (with-current-buffer "*Help*"
19136 (setq truncate-lines t))))
19138 (defun org-speed-move-safe (cmd)
19139 "Execute CMD, but make sure that the cursor always ends up in a headline.
19140 If not, return to the original position and throw an error."
19141 (interactive)
19142 (let ((pos (point)))
19143 (call-interactively cmd)
19144 (unless (and (bolp) (org-at-heading-p))
19145 (goto-char pos)
19146 (error "Boundary reached while executing %s" cmd))))
19148 (defvar org-self-insert-command-undo-counter 0)
19150 (defvar org-table-auto-blank-field) ; defined in org-table.el
19151 (defvar org-speed-command nil)
19153 (define-obsolete-function-alias
19154 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19156 (defun org-speed-command-activate (keys)
19157 "Hook for activating single-letter speed commands.
19158 `org-speed-commands-default' specifies a minimal command set.
19159 Use `org-speed-commands-user' for further customization."
19160 (when (or (and (bolp) (looking-at org-outline-regexp))
19161 (and (functionp org-use-speed-commands)
19162 (funcall org-use-speed-commands)))
19163 (cdr (assoc keys (append org-speed-commands-user
19164 org-speed-commands-default)))))
19166 (define-obsolete-function-alias
19167 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19169 (defun org-babel-speed-command-activate (keys)
19170 "Hook for activating single-letter code block commands."
19171 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19172 (cdr (assoc keys org-babel-key-bindings))))
19174 (defcustom org-speed-command-hook
19175 '(org-speed-command-default-hook org-babel-speed-command-hook)
19176 "Hook for activating speed commands at strategic locations.
19177 Hook functions are called in sequence until a valid handler is
19178 found.
19180 Each hook takes a single argument, a user-pressed command key
19181 which is also a `self-insert-command' from the global map.
19183 Within the hook, examine the cursor position and the command key
19184 and return nil or a valid handler as appropriate. Handler could
19185 be one of an interactive command, a function, or a form.
19187 Set `org-use-speed-commands' to non-nil value to enable this
19188 hook. The default setting is `org-speed-command-activate'."
19189 :group 'org-structure
19190 :version "24.1"
19191 :type 'hook)
19193 (defun org-self-insert-command (N)
19194 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19195 If the cursor is in a table looking at whitespace, the whitespace is
19196 overwritten, and the table is not marked as requiring realignment."
19197 (interactive "p")
19198 (org-check-before-invisible-edit 'insert)
19199 (cond
19200 ((and org-use-speed-commands
19201 (setq org-speed-command
19202 (run-hook-with-args-until-success
19203 'org-speed-command-hook (this-command-keys))))
19204 (cond
19205 ((commandp org-speed-command)
19206 (setq this-command org-speed-command)
19207 (call-interactively org-speed-command))
19208 ((functionp org-speed-command)
19209 (funcall org-speed-command))
19210 ((and org-speed-command (listp org-speed-command))
19211 (eval org-speed-command))
19212 (t (let (org-use-speed-commands)
19213 (call-interactively 'org-self-insert-command)))))
19214 ((and
19215 (org-table-p)
19216 (progn
19217 ;; check if we blank the field, and if that triggers align
19218 (and (featurep 'org-table) org-table-auto-blank-field
19219 (member last-command
19220 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19221 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19222 ;; got extra space, this field does not determine column width
19223 (let (org-table-may-need-update) (org-table-blank-field))
19224 ;; no extra space, this field may determine column width
19225 (org-table-blank-field)))
19227 (eq N 1)
19228 (looking-at "[^|\n]* |"))
19229 (let (org-table-may-need-update)
19230 (goto-char (1- (match-end 0)))
19231 (backward-delete-char 1)
19232 (goto-char (match-beginning 0))
19233 (self-insert-command N)))
19235 (setq org-table-may-need-update t)
19236 (self-insert-command N)
19237 (org-fix-tags-on-the-fly)
19238 (if org-self-insert-cluster-for-undo
19239 (if (not (eq last-command 'org-self-insert-command))
19240 (setq org-self-insert-command-undo-counter 1)
19241 (if (>= org-self-insert-command-undo-counter 20)
19242 (setq org-self-insert-command-undo-counter 1)
19243 (and (> org-self-insert-command-undo-counter 0)
19244 buffer-undo-list (listp buffer-undo-list)
19245 (not (cadr buffer-undo-list)) ; remove nil entry
19246 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19247 (setq org-self-insert-command-undo-counter
19248 (1+ org-self-insert-command-undo-counter))))))))
19250 (defun org-check-before-invisible-edit (kind)
19251 "Check is editing if kind KIND would be dangerous with invisible text around.
19252 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19253 ;; First, try to get out of here as quickly as possible, to reduce overhead
19254 (if (and org-catch-invisible-edits
19255 (or (not (boundp 'visible-mode)) (not visible-mode))
19256 (or (get-char-property (point) 'invisible)
19257 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19258 ;; OK, we need to take a closer look
19259 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19260 (invisible-before-point (if (bobp) nil (get-char-property
19261 (1- (point)) 'invisible)))
19262 (border-and-ok-direction
19264 ;; Check if we are acting predictably before invisible text
19265 (and invisible-at-point (not invisible-before-point)
19266 (memq kind '(insert delete-backward)))
19267 ;; Check if we are acting predictably after invisible text
19268 ;; This works not well, and I have turned it off. It seems
19269 ;; better to always show and stop after invisible text.
19270 ;; (and (not invisible-at-point) invisible-before-point
19271 ;; (memq kind '(insert delete)))
19273 (when (or (memq invisible-at-point '(outline org-hide-block t))
19274 (memq invisible-before-point '(outline org-hide-block t)))
19275 (if (eq org-catch-invisible-edits 'error)
19276 (error "Editing in invisible areas is prohibited - make visible first"))
19277 (if (and org-custom-properties-overlays
19278 (y-or-n-p "Display invisible properties in this buffer? "))
19279 (org-toggle-custom-properties-visibility)
19280 ;; Make the area visible
19281 (save-excursion
19282 (if invisible-before-point
19283 (goto-char (previous-single-char-property-change
19284 (point) 'invisible)))
19285 (org-cycle))
19286 (cond
19287 ((eq org-catch-invisible-edits 'show)
19288 ;; That's it, we do the edit after showing
19289 (message
19290 "Unfolding invisible region around point before editing")
19291 (sit-for 1))
19292 ((and (eq org-catch-invisible-edits 'smart)
19293 border-and-ok-direction)
19294 (message "Unfolding invisible region around point before editing"))
19296 ;; Don't do the edit, make the user repeat it in full visibility
19297 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19299 (defun org-fix-tags-on-the-fly ()
19300 (when (and (equal (char-after (point-at-bol)) ?*)
19301 (org-at-heading-p))
19302 (org-align-tags-here org-tags-column)))
19304 (defun org-delete-backward-char (N)
19305 "Like `delete-backward-char', insert whitespace at field end in tables.
19306 When deleting backwards, in tables this function will insert whitespace in
19307 front of the next \"|\" separator, to keep the table aligned. The table will
19308 still be marked for re-alignment if the field did fill the entire column,
19309 because, in this case the deletion might narrow the column."
19310 (interactive "p")
19311 (save-match-data
19312 (org-check-before-invisible-edit 'delete-backward)
19313 (if (and (org-table-p)
19314 (eq N 1)
19315 (string-match "|" (buffer-substring (point-at-bol) (point)))
19316 (looking-at ".*?|"))
19317 (let ((pos (point))
19318 (noalign (looking-at "[^|\n\r]* |"))
19319 (c org-table-may-need-update))
19320 (backward-delete-char N)
19321 (if (not overwrite-mode)
19322 (progn
19323 (skip-chars-forward "^|")
19324 (insert " ")
19325 (goto-char (1- pos))))
19326 ;; noalign: if there were two spaces at the end, this field
19327 ;; does not determine the width of the column.
19328 (if noalign (setq org-table-may-need-update c)))
19329 (backward-delete-char N)
19330 (org-fix-tags-on-the-fly))))
19332 (defun org-delete-char (N)
19333 "Like `delete-char', but insert whitespace at field end in tables.
19334 When deleting characters, in tables this function will insert whitespace in
19335 front of the next \"|\" separator, to keep the table aligned. The table will
19336 still be marked for re-alignment if the field did fill the entire column,
19337 because, in this case the deletion might narrow the column."
19338 (interactive "p")
19339 (save-match-data
19340 (org-check-before-invisible-edit 'delete)
19341 (if (and (org-table-p)
19342 (not (bolp))
19343 (not (= (char-after) ?|))
19344 (eq N 1))
19345 (if (looking-at ".*?|")
19346 (let ((pos (point))
19347 (noalign (looking-at "[^|\n\r]* |"))
19348 (c org-table-may-need-update))
19349 (replace-match
19350 (concat (substring (match-string 0) 1 -1) " |") nil t)
19351 (goto-char pos)
19352 ;; noalign: if there were two spaces at the end, this field
19353 ;; does not determine the width of the column.
19354 (if noalign (setq org-table-may-need-update c)))
19355 (delete-char N))
19356 (delete-char N)
19357 (org-fix-tags-on-the-fly))))
19359 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19360 (put 'org-self-insert-command 'delete-selection t)
19361 (put 'orgtbl-self-insert-command 'delete-selection t)
19362 (put 'org-delete-char 'delete-selection 'supersede)
19363 (put 'org-delete-backward-char 'delete-selection 'supersede)
19364 (put 'org-yank 'delete-selection 'yank)
19366 ;; Make `flyspell-mode' delay after some commands
19367 (put 'org-self-insert-command 'flyspell-delayed t)
19368 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19369 (put 'org-delete-char 'flyspell-delayed t)
19370 (put 'org-delete-backward-char 'flyspell-delayed t)
19372 ;; Make pabbrev-mode expand after org-mode commands
19373 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19374 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19376 ;; How to do this: Measure non-white length of current string
19377 ;; If equal to column width, we should realign.
19379 (defun org-remap (map &rest commands)
19380 "In MAP, remap the functions given in COMMANDS.
19381 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19382 (let (new old)
19383 (while commands
19384 (setq old (pop commands) new (pop commands))
19385 (if (fboundp 'command-remapping)
19386 (org-defkey map (vector 'remap old) new)
19387 (substitute-key-definition old new map global-map)))))
19389 (defun org-transpose-words ()
19390 "Transpose words for Org.
19391 This uses the `org-mode-transpose-word-syntax-table' syntax
19392 table, which interprets characters in `org-emphasis-alist' as
19393 word constituants."
19394 (interactive)
19395 (with-syntax-table org-mode-transpose-word-syntax-table
19396 (call-interactively 'transpose-words)))
19397 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19399 (when (eq org-enable-table-editor 'optimized)
19400 ;; If the user wants maximum table support, we need to hijack
19401 ;; some standard editing functions
19402 (org-remap org-mode-map
19403 'self-insert-command 'org-self-insert-command
19404 'delete-char 'org-delete-char
19405 'delete-backward-char 'org-delete-backward-char)
19406 (org-defkey org-mode-map "|" 'org-force-self-insert))
19408 (defvar org-ctrl-c-ctrl-c-hook nil
19409 "Hook for functions attaching themselves to `C-c C-c'.
19411 This can be used to add additional functionality to the C-c C-c
19412 key which executes context-dependent commands. This hook is run
19413 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19414 run after the last test.
19416 Each function will be called with no arguments. The function
19417 must check if the context is appropriate for it to act. If yes,
19418 it should do its thing and then return a non-nil value. If the
19419 context is wrong, just do nothing and return nil.")
19421 (defvar org-ctrl-c-ctrl-c-final-hook nil
19422 "Hook for functions attaching themselves to `C-c C-c'.
19424 This can be used to add additional functionality to the C-c C-c
19425 key which executes context-dependent commands. This hook is run
19426 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19427 before the first test.
19429 Each function will be called with no arguments. The function
19430 must check if the context is appropriate for it to act. If yes,
19431 it should do its thing and then return a non-nil value. If the
19432 context is wrong, just do nothing and return nil.")
19434 (defvar org-tab-first-hook nil
19435 "Hook for functions to attach themselves to TAB.
19436 See `org-ctrl-c-ctrl-c-hook' for more information.
19437 This hook runs as the first action when TAB is pressed, even before
19438 `org-cycle' messes around with the `outline-regexp' to cater for
19439 inline tasks and plain list item folding.
19440 If any function in this hook returns t, any other actions that
19441 would have been caused by TAB (such as table field motion or visibility
19442 cycling) will not occur.")
19444 (defvar org-tab-after-check-for-table-hook nil
19445 "Hook for functions to attach themselves to TAB.
19446 See `org-ctrl-c-ctrl-c-hook' for more information.
19447 This hook runs after it has been established that the cursor is not in a
19448 table, but before checking if the cursor is in a headline or if global cycling
19449 should be done.
19450 If any function in this hook returns t, not other actions like visibility
19451 cycling will be done.")
19453 (defvar org-tab-after-check-for-cycling-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 not table field motion and
19457 not visibility should be done because of current context. This is probably
19458 the place where a package like yasnippets can hook in.")
19460 (defvar org-tab-before-tab-emulation-hook nil
19461 "Hook for functions to attach themselves to TAB.
19462 See `org-ctrl-c-ctrl-c-hook' for more information.
19463 This hook runs after every other options for TAB have been exhausted, but
19464 before indentation and \t insertion takes place.")
19466 (defvar org-metaleft-hook nil
19467 "Hook for functions attaching themselves to `M-left'.
19468 See `org-ctrl-c-ctrl-c-hook' for more information.")
19469 (defvar org-metaright-hook nil
19470 "Hook for functions attaching themselves to `M-right'.
19471 See `org-ctrl-c-ctrl-c-hook' for more information.")
19472 (defvar org-metaup-hook nil
19473 "Hook for functions attaching themselves to `M-up'.
19474 See `org-ctrl-c-ctrl-c-hook' for more information.")
19475 (defvar org-metadown-hook nil
19476 "Hook for functions attaching themselves to `M-down'.
19477 See `org-ctrl-c-ctrl-c-hook' for more information.")
19478 (defvar org-shiftmetaleft-hook nil
19479 "Hook for functions attaching themselves to `M-S-left'.
19480 See `org-ctrl-c-ctrl-c-hook' for more information.")
19481 (defvar org-shiftmetaright-hook nil
19482 "Hook for functions attaching themselves to `M-S-right'.
19483 See `org-ctrl-c-ctrl-c-hook' for more information.")
19484 (defvar org-shiftmetaup-hook nil
19485 "Hook for functions attaching themselves to `M-S-up'.
19486 See `org-ctrl-c-ctrl-c-hook' for more information.")
19487 (defvar org-shiftmetadown-hook nil
19488 "Hook for functions attaching themselves to `M-S-down'.
19489 See `org-ctrl-c-ctrl-c-hook' for more information.")
19490 (defvar org-metareturn-hook nil
19491 "Hook for functions attaching themselves to `M-RET'.
19492 See `org-ctrl-c-ctrl-c-hook' for more information.")
19493 (defvar org-shiftup-hook nil
19494 "Hook for functions attaching themselves to `S-up'.
19495 See `org-ctrl-c-ctrl-c-hook' for more information.")
19496 (defvar org-shiftup-final-hook nil
19497 "Hook for functions attaching themselves to `S-up'.
19498 This one runs after all other options except shift-select have been excluded.
19499 See `org-ctrl-c-ctrl-c-hook' for more information.")
19500 (defvar org-shiftdown-hook nil
19501 "Hook for functions attaching themselves to `S-down'.
19502 See `org-ctrl-c-ctrl-c-hook' for more information.")
19503 (defvar org-shiftdown-final-hook nil
19504 "Hook for functions attaching themselves to `S-down'.
19505 This one runs after all other options except shift-select have been excluded.
19506 See `org-ctrl-c-ctrl-c-hook' for more information.")
19507 (defvar org-shiftleft-hook nil
19508 "Hook for functions attaching themselves to `S-left'.
19509 See `org-ctrl-c-ctrl-c-hook' for more information.")
19510 (defvar org-shiftleft-final-hook nil
19511 "Hook for functions attaching themselves to `S-left'.
19512 This one runs after all other options except shift-select have been excluded.
19513 See `org-ctrl-c-ctrl-c-hook' for more information.")
19514 (defvar org-shiftright-hook nil
19515 "Hook for functions attaching themselves to `S-right'.
19516 See `org-ctrl-c-ctrl-c-hook' for more information.")
19517 (defvar org-shiftright-final-hook nil
19518 "Hook for functions attaching themselves to `S-right'.
19519 This one runs after all other options except shift-select have been excluded.
19520 See `org-ctrl-c-ctrl-c-hook' for more information.")
19522 (defun org-modifier-cursor-error ()
19523 "Throw an error, a modified cursor command was applied in wrong context."
19524 (error "This command is active in special context like tables, headlines or items"))
19526 (defun org-shiftselect-error ()
19527 "Throw an error because Shift-Cursor command was applied in wrong context."
19528 (if (and (boundp 'shift-select-mode) shift-select-mode)
19529 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19530 (error "This command works only in special context like headlines or timestamps")))
19532 (defun org-call-for-shift-select (cmd)
19533 (let ((this-command-keys-shift-translated t))
19534 (call-interactively cmd)))
19536 (defun org-shifttab (&optional arg)
19537 "Global visibility cycling or move to previous table field.
19538 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19539 on context.
19540 See the individual commands for more information."
19541 (interactive "P")
19542 (cond
19543 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19544 ((integerp arg)
19545 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19546 (message "Content view to level: %d" arg)
19547 (org-content (prefix-numeric-value arg2))
19548 (setq org-cycle-global-status 'overview)))
19549 (t (call-interactively 'org-global-cycle))))
19551 (defun org-shiftmetaleft ()
19552 "Promote subtree or delete table column.
19553 Calls `org-promote-subtree', `org-outdent-item-tree', or
19554 `org-table-delete-column', depending on context. See the
19555 individual commands for more information."
19556 (interactive)
19557 (cond
19558 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19559 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19560 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19561 ((if (not (org-region-active-p)) (org-at-item-p)
19562 (save-excursion (goto-char (region-beginning))
19563 (org-at-item-p)))
19564 (call-interactively 'org-outdent-item-tree))
19565 (t (org-modifier-cursor-error))))
19567 (defun org-shiftmetaright ()
19568 "Demote subtree or insert table column.
19569 Calls `org-demote-subtree', `org-indent-item-tree', or
19570 `org-table-insert-column', depending on context. See the
19571 individual commands for more information."
19572 (interactive)
19573 (cond
19574 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19575 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19576 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19577 ((if (not (org-region-active-p)) (org-at-item-p)
19578 (save-excursion (goto-char (region-beginning))
19579 (org-at-item-p)))
19580 (call-interactively 'org-indent-item-tree))
19581 (t (org-modifier-cursor-error))))
19583 (defun org-shiftmetaup (&optional arg)
19584 "Move subtree up or kill table row.
19585 Calls `org-move-subtree-up' or `org-table-kill-row' or
19586 `org-move-item-up' or `org-timestamp-up', depending on context.
19587 See the individual commands for more information."
19588 (interactive "P")
19589 (cond
19590 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19591 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19592 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19593 ((org-at-item-p) (call-interactively 'org-move-item-up))
19594 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19595 (call-interactively 'org-timestamp-up)))
19596 (t (call-interactively 'org-drag-line-backward))))
19598 (defun org-shiftmetadown (&optional arg)
19599 "Move subtree down or insert table row.
19600 Calls `org-move-subtree-down' or `org-table-insert-row' or
19601 `org-move-item-down' or `org-timestamp-up', depending on context.
19602 See the individual commands for more information."
19603 (interactive "P")
19604 (cond
19605 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19606 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19607 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19608 ((org-at-item-p) (call-interactively 'org-move-item-down))
19609 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19610 (call-interactively 'org-timestamp-down)))
19611 (t (call-interactively 'org-drag-line-forward))))
19613 (defsubst org-hidden-tree-error ()
19614 (error
19615 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19617 (defun org-metaleft (&optional arg)
19618 "Promote heading or move table column to left.
19619 Calls `org-do-promote' or `org-table-move-column', depending on context.
19620 With no specific context, calls the Emacs default `backward-word'.
19621 See the individual commands for more information."
19622 (interactive "P")
19623 (cond
19624 ((run-hook-with-args-until-success 'org-metaleft-hook))
19625 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19626 ((org-with-limited-levels
19627 (or (org-at-heading-p)
19628 (and (org-region-active-p)
19629 (save-excursion
19630 (goto-char (region-beginning))
19631 (org-at-heading-p)))))
19632 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19633 (call-interactively 'org-do-promote))
19634 ;; At an inline task.
19635 ((org-at-heading-p)
19636 (call-interactively 'org-inlinetask-promote))
19637 ((or (org-at-item-p)
19638 (and (org-region-active-p)
19639 (save-excursion
19640 (goto-char (region-beginning))
19641 (org-at-item-p))))
19642 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19643 (call-interactively 'org-outdent-item))
19644 (t (call-interactively 'backward-word))))
19646 (defun org-metaright (&optional arg)
19647 "Demote a subtree, a list item or move table column to right.
19648 In front of a drawer or a block keyword, indent it correctly.
19649 With no specific context, calls the Emacs default `forward-word'.
19650 See the individual commands for more information."
19651 (interactive "P")
19652 (cond
19653 ((run-hook-with-args-until-success 'org-metaright-hook))
19654 ((org-at-table-p) (call-interactively 'org-table-move-column))
19655 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19656 ((org-at-block-p) (call-interactively 'org-indent-block))
19657 ((org-with-limited-levels
19658 (or (org-at-heading-p)
19659 (and (org-region-active-p)
19660 (save-excursion
19661 (goto-char (region-beginning))
19662 (org-at-heading-p)))))
19663 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19664 (call-interactively 'org-do-demote))
19665 ;; At an inline task.
19666 ((org-at-heading-p)
19667 (call-interactively 'org-inlinetask-demote))
19668 ((or (org-at-item-p)
19669 (and (org-region-active-p)
19670 (save-excursion
19671 (goto-char (region-beginning))
19672 (org-at-item-p))))
19673 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19674 (call-interactively 'org-indent-item))
19675 (t (call-interactively 'forward-word))))
19677 (defun org-check-for-hidden (what)
19678 "Check if there are hidden headlines/items in the current visual line.
19679 WHAT can be either `headlines' or `items'. If the current line is
19680 an outline or item heading and it has a folded subtree below it,
19681 this function returns t, nil otherwise."
19682 (let ((re (cond
19683 ((eq what 'headlines) org-outline-regexp-bol)
19684 ((eq what 'items) (org-item-beginning-re))
19685 (t (error "This should not happen"))))
19686 beg end)
19687 (save-excursion
19688 (catch 'exit
19689 (unless (org-region-active-p)
19690 (setq beg (point-at-bol))
19691 (beginning-of-line 2)
19692 (while (and (not (eobp)) ;; this is like `next-line'
19693 (get-char-property (1- (point)) 'invisible))
19694 (beginning-of-line 2))
19695 (setq end (point))
19696 (goto-char beg)
19697 (goto-char (point-at-eol))
19698 (setq end (max end (point)))
19699 (while (re-search-forward re end t)
19700 (if (get-char-property (match-beginning 0) 'invisible)
19701 (throw 'exit t))))
19702 nil))))
19704 (defun org-metaup (&optional arg)
19705 "Move subtree up or move table row up.
19706 Calls `org-move-subtree-up' or `org-table-move-row' or
19707 `org-move-item-up', depending on context. See the individual commands
19708 for more information."
19709 (interactive "P")
19710 (cond
19711 ((run-hook-with-args-until-success 'org-metaup-hook))
19712 ((org-region-active-p)
19713 (let* ((a (min (region-beginning) (region-end)))
19714 (b (1- (max (region-beginning) (region-end))))
19715 (c (save-excursion (goto-char a)
19716 (move-beginning-of-line 0)))
19717 (d (save-excursion (goto-char a)
19718 (move-end-of-line 0) (point))))
19719 (transpose-regions a b c d)
19720 (goto-char c)))
19721 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19722 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19723 ((org-at-item-p) (call-interactively 'org-move-item-up))
19724 (t (org-drag-element-backward))))
19726 (defun org-metadown (&optional arg)
19727 "Move subtree down or move table row down.
19728 Calls `org-move-subtree-down' or `org-table-move-row' or
19729 `org-move-item-down', depending on context. See the individual
19730 commands for more information."
19731 (interactive "P")
19732 (cond
19733 ((run-hook-with-args-until-success 'org-metadown-hook))
19734 ((org-region-active-p)
19735 (let* ((a (min (region-beginning) (region-end)))
19736 (b (max (region-beginning) (region-end)))
19737 (c (save-excursion (goto-char b)
19738 (move-beginning-of-line 1)))
19739 (d (save-excursion (goto-char b)
19740 (move-end-of-line 1) (1+ (point)))))
19741 (transpose-regions a b c d)
19742 (goto-char d)))
19743 ((org-at-table-p) (call-interactively 'org-table-move-row))
19744 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19745 ((org-at-item-p) (call-interactively 'org-move-item-down))
19746 (t (org-drag-element-forward))))
19748 (defun org-shiftup (&optional arg)
19749 "Increase item in timestamp or increase priority of current headline.
19750 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19751 depending on context. See the individual commands for more information."
19752 (interactive "P")
19753 (cond
19754 ((run-hook-with-args-until-success 'org-shiftup-hook))
19755 ((and org-support-shift-select (org-region-active-p))
19756 (org-call-for-shift-select 'previous-line))
19757 ((org-at-timestamp-p t)
19758 (call-interactively (if org-edit-timestamp-down-means-later
19759 'org-timestamp-down 'org-timestamp-up)))
19760 ((and (not (eq org-support-shift-select 'always))
19761 org-enable-priority-commands
19762 (org-at-heading-p))
19763 (call-interactively 'org-priority-up))
19764 ((and (not org-support-shift-select) (org-at-item-p))
19765 (call-interactively 'org-previous-item))
19766 ((org-clocktable-try-shift 'up arg))
19767 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19768 (org-support-shift-select
19769 (org-call-for-shift-select 'previous-line))
19770 (t (org-shiftselect-error))))
19772 (defun org-shiftdown (&optional arg)
19773 "Decrease item in timestamp or decrease priority of current headline.
19774 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19775 depending on context. See the individual commands for more information."
19776 (interactive "P")
19777 (cond
19778 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19779 ((and org-support-shift-select (org-region-active-p))
19780 (org-call-for-shift-select 'next-line))
19781 ((org-at-timestamp-p t)
19782 (call-interactively (if org-edit-timestamp-down-means-later
19783 'org-timestamp-up 'org-timestamp-down)))
19784 ((and (not (eq org-support-shift-select 'always))
19785 org-enable-priority-commands
19786 (org-at-heading-p))
19787 (call-interactively 'org-priority-down))
19788 ((and (not org-support-shift-select) (org-at-item-p))
19789 (call-interactively 'org-next-item))
19790 ((org-clocktable-try-shift 'down arg))
19791 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19792 (org-support-shift-select
19793 (org-call-for-shift-select 'next-line))
19794 (t (org-shiftselect-error))))
19796 (defun org-shiftright (&optional arg)
19797 "Cycle the thing at point or in the current line, depending on context.
19798 Depending on context, this does one of the following:
19800 - switch a timestamp at point one day into the future
19801 - on a headline, switch to the next TODO keyword.
19802 - on an item, switch entire list to the next bullet type
19803 - on a property line, switch to the next allowed value
19804 - on a clocktable definition line, move time block into the future"
19805 (interactive "P")
19806 (cond
19807 ((run-hook-with-args-until-success 'org-shiftright-hook))
19808 ((and org-support-shift-select (org-region-active-p))
19809 (org-call-for-shift-select 'forward-char))
19810 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19811 ((and (not (eq org-support-shift-select 'always))
19812 (org-at-heading-p))
19813 (let ((org-inhibit-logging
19814 (not org-treat-S-cursor-todo-selection-as-state-change))
19815 (org-inhibit-blocking
19816 (not org-treat-S-cursor-todo-selection-as-state-change)))
19817 (org-call-with-arg 'org-todo 'right)))
19818 ((or (and org-support-shift-select
19819 (not (eq org-support-shift-select 'always))
19820 (org-at-item-bullet-p))
19821 (and (not org-support-shift-select) (org-at-item-p)))
19822 (org-call-with-arg 'org-cycle-list-bullet nil))
19823 ((and (not (eq org-support-shift-select 'always))
19824 (org-at-property-p))
19825 (call-interactively 'org-property-next-allowed-value))
19826 ((org-clocktable-try-shift 'right arg))
19827 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19828 (org-support-shift-select
19829 (org-call-for-shift-select 'forward-char))
19830 (t (org-shiftselect-error))))
19832 (defun org-shiftleft (&optional arg)
19833 "Cycle the thing at point or in the current line, depending on context.
19834 Depending on context, this does one of the following:
19836 - switch a timestamp at point one day into the past
19837 - on a headline, switch to the previous TODO keyword.
19838 - on an item, switch entire list to the previous bullet type
19839 - on a property line, switch to the previous allowed value
19840 - on a clocktable definition line, move time block into the past"
19841 (interactive "P")
19842 (cond
19843 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19844 ((and org-support-shift-select (org-region-active-p))
19845 (org-call-for-shift-select 'backward-char))
19846 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19847 ((and (not (eq org-support-shift-select 'always))
19848 (org-at-heading-p))
19849 (let ((org-inhibit-logging
19850 (not org-treat-S-cursor-todo-selection-as-state-change))
19851 (org-inhibit-blocking
19852 (not org-treat-S-cursor-todo-selection-as-state-change)))
19853 (org-call-with-arg 'org-todo 'left)))
19854 ((or (and org-support-shift-select
19855 (not (eq org-support-shift-select 'always))
19856 (org-at-item-bullet-p))
19857 (and (not org-support-shift-select) (org-at-item-p)))
19858 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19859 ((and (not (eq org-support-shift-select 'always))
19860 (org-at-property-p))
19861 (call-interactively 'org-property-previous-allowed-value))
19862 ((org-clocktable-try-shift 'left arg))
19863 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19864 (org-support-shift-select
19865 (org-call-for-shift-select 'backward-char))
19866 (t (org-shiftselect-error))))
19868 (defun org-shiftcontrolright ()
19869 "Switch to next TODO set."
19870 (interactive)
19871 (cond
19872 ((and org-support-shift-select (org-region-active-p))
19873 (org-call-for-shift-select 'forward-word))
19874 ((and (not (eq org-support-shift-select 'always))
19875 (org-at-heading-p))
19876 (org-call-with-arg 'org-todo 'nextset))
19877 (org-support-shift-select
19878 (org-call-for-shift-select 'forward-word))
19879 (t (org-shiftselect-error))))
19881 (defun org-shiftcontrolleft ()
19882 "Switch to previous TODO set."
19883 (interactive)
19884 (cond
19885 ((and org-support-shift-select (org-region-active-p))
19886 (org-call-for-shift-select 'backward-word))
19887 ((and (not (eq org-support-shift-select 'always))
19888 (org-at-heading-p))
19889 (org-call-with-arg 'org-todo 'previousset))
19890 (org-support-shift-select
19891 (org-call-for-shift-select 'backward-word))
19892 (t (org-shiftselect-error))))
19894 (defun org-shiftcontrolup (&optional n)
19895 "Change timestamps synchronously up in CLOCK log lines.
19896 Optional argument N tells to change by that many units."
19897 (interactive "P")
19898 (cond ((and (not org-support-shift-select)
19899 (org-at-clock-log-p)
19900 (org-at-timestamp-p t))
19901 (org-clock-timestamps-up n))
19902 (t (org-shiftselect-error))))
19904 (defun org-shiftcontroldown (&optional n)
19905 "Change timestamps synchronously down 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-down n))
19912 (t (org-shiftselect-error))))
19914 (defun org-ctrl-c-ret ()
19915 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19916 (interactive)
19917 (cond
19918 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19919 (t (call-interactively 'org-insert-heading))))
19921 (defun org-find-visible ()
19922 (let ((s (point)))
19923 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19924 (get-char-property s 'invisible)))
19926 (defun org-find-invisible ()
19927 (let ((s (point)))
19928 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19929 (not (get-char-property s 'invisible))))
19932 (defun org-copy-visible (beg end)
19933 "Copy the visible parts of the region."
19934 (interactive "r")
19935 (let (snippets s)
19936 (save-excursion
19937 (save-restriction
19938 (narrow-to-region beg end)
19939 (setq s (goto-char (point-min)))
19940 (while (not (= (point) (point-max)))
19941 (goto-char (org-find-invisible))
19942 (push (buffer-substring s (point)) snippets)
19943 (setq s (goto-char (org-find-visible))))))
19944 (kill-new (apply 'concat (nreverse snippets)))))
19946 (defun org-copy-special ()
19947 "Copy region in table or copy current subtree.
19948 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19949 See the individual commands for more information."
19950 (interactive)
19951 (call-interactively
19952 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19954 (defun org-cut-special ()
19955 "Cut region in table or cut current subtree.
19956 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19957 See the individual commands for more information."
19958 (interactive)
19959 (call-interactively
19960 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19962 (defun org-paste-special (arg)
19963 "Paste rectangular region into table, or past subtree relative to level.
19964 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19965 See the individual commands for more information."
19966 (interactive "P")
19967 (if (org-at-table-p)
19968 (org-table-paste-rectangle)
19969 (org-paste-subtree arg)))
19971 (defsubst org-in-fixed-width-region-p ()
19972 "Is point in a fixed-width region?"
19973 (save-match-data
19974 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19976 (defun org-edit-special (&optional arg)
19977 "Call a special editor for the element at point.
19978 When at a table, call the formula editor with `org-table-edit-formulas'.
19979 When in a source code block, call `org-edit-src-code'.
19980 When in a fixed-width region, call `org-edit-fixed-width-region'.
19981 When at an #+INCLUDE keyword, visit the included file.
19982 On a link, call `ffap' to visit the link at point.
19983 Otherwise, return a user error."
19984 (interactive "P")
19985 (let ((element (org-element-at-point)))
19986 (assert (not buffer-read-only) nil
19987 "Buffer is read-only: %s" (buffer-name))
19988 (case (org-element-type element)
19989 (src-block
19990 (if (not arg) (org-edit-src-code)
19991 (let* ((info (org-babel-get-src-block-info))
19992 (lang (nth 0 info))
19993 (params (nth 2 info))
19994 (session (cdr (assq :session params))))
19995 (if (not session) (org-edit-src-code)
19996 ;; At a src-block with a session and function called with
19997 ;; an ARG: switch to the buffer related to the inferior
19998 ;; process.
19999 (switch-to-buffer
20000 (funcall (intern (concat "org-babel-prep-session:" lang))
20001 session params))))))
20002 (keyword
20003 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20004 (find-file
20005 (org-remove-double-quotes
20006 (car (org-split-string (org-element-property :value element)))))
20007 (user-error "No special environment to edit here")))
20008 (table
20009 (if (eq (org-element-property :type element) 'table.el)
20010 (org-edit-src-code)
20011 (call-interactively 'org-table-edit-formulas)))
20012 ;; Only Org tables contain `table-row' type elements.
20013 (table-row (call-interactively 'org-table-edit-formulas))
20014 ((example-block export-block) (org-edit-src-code))
20015 (fixed-width (org-edit-fixed-width-region))
20016 (otherwise
20017 ;; No notable element at point. Though, we may be at a link,
20018 ;; which is an object. Thus, scan deeper.
20019 (if (eq (org-element-type (org-element-context element)) 'link)
20020 (call-interactively 'ffap)
20021 (user-error "No special environment to edit here"))))))
20023 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20024 (defun org-ctrl-c-ctrl-c (&optional arg)
20025 "Set tags in headline, or update according to changed information at point.
20027 This command does many different things, depending on context:
20029 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20030 this is what we do.
20032 - If the cursor is on a statistics cookie, update it.
20034 - If the cursor is in a headline, prompt for tags and insert them
20035 into the current line, aligned to `org-tags-column'. When called
20036 with prefix arg, realign all tags in the current buffer.
20038 - If the cursor is in one of the special #+KEYWORD lines, this
20039 triggers scanning the buffer for these lines and updating the
20040 information.
20042 - If the cursor is inside a table, realign the table. This command
20043 works even if the automatic table editor has been turned off.
20045 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20046 the entire table.
20048 - If the cursor is at a footnote reference or definition, jump to
20049 the corresponding definition or references, respectively.
20051 - If the cursor is a the beginning of a dynamic block, update it.
20053 - If the current buffer is a capture buffer, close note and file it.
20055 - If the cursor is on a <<<target>>>, update radio targets and
20056 corresponding links in this buffer.
20058 - If the cursor is on a numbered item in a plain list, renumber the
20059 ordered list.
20061 - If the cursor is on a checkbox, toggle it.
20063 - If the cursor is on a code block, evaluate it. The variable
20064 `org-confirm-babel-evaluate' can be used to control prompting
20065 before code block evaluation, by default every code block
20066 evaluation requires confirmation. Code block evaluation can be
20067 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20068 (interactive "P")
20069 (cond
20070 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20071 org-occur-highlights
20072 org-latex-fragment-image-overlays)
20073 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20074 (org-remove-occur-highlights)
20075 (org-remove-latex-fragment-image-overlays)
20076 (message "Temporary highlights/overlays removed from current buffer"))
20077 ((and (local-variable-p 'org-finish-function (current-buffer))
20078 (fboundp org-finish-function))
20079 (funcall org-finish-function))
20080 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20082 (let* ((context (org-element-context)) (type (org-element-type context)))
20083 ;; Test if point is within a blank line.
20084 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20085 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20086 (user-error "C-c C-c can do nothing useful at this location"))
20087 ;; For convenience: at the first line of a paragraph on the
20088 ;; same line as an item, apply function on that item instead.
20089 (when (eq type 'paragraph)
20090 (let ((parent (org-element-property :parent context)))
20091 (when (and (eq (org-element-type parent) 'item)
20092 (= (point-at-bol) (org-element-property :begin parent)))
20093 (setq context parent type 'item))))
20094 ;; Act according to type of element or object at point.
20095 (case type
20096 (clock (org-clock-update-time-maybe))
20097 (dynamic-block
20098 (save-excursion
20099 (goto-char (org-element-property :post-affiliated context))
20100 (org-update-dblock)))
20101 (footnote-definition
20102 (goto-char (org-element-property :post-affiliated context))
20103 (call-interactively 'org-footnote-action))
20104 (footnote-reference (call-interactively 'org-footnote-action))
20105 ((headline inlinetask)
20106 (save-excursion (goto-char (org-element-property :begin context))
20107 (call-interactively 'org-set-tags)))
20108 (item
20109 ;; At an item: a double C-u set checkbox to "[-]"
20110 ;; unconditionally, whereas a single one will toggle its
20111 ;; presence. Without an universal argument, if the item
20112 ;; has a checkbox, toggle it. Otherwise repair the list.
20113 (let* ((box (org-element-property :checkbox context))
20114 (struct (org-element-property :structure context))
20115 (old-struct (copy-tree struct))
20116 (parents (org-list-parents-alist struct))
20117 (prevs (org-list-prevs-alist struct))
20118 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20119 (org-list-set-checkbox
20120 (org-element-property :begin context) struct
20121 (cond ((equal arg '(16)) "[-]")
20122 ((and (not box) (equal arg '(4))) "[ ]")
20123 ((or (not box) (equal arg '(4))) nil)
20124 ((eq box 'on) "[ ]")
20125 (t "[X]")))
20126 ;; Mimic `org-list-write-struct' but with grabbing
20127 ;; a return value from `org-list-struct-fix-box'.
20128 (org-list-struct-fix-ind struct parents 2)
20129 (org-list-struct-fix-item-end struct)
20130 (org-list-struct-fix-bul struct prevs)
20131 (org-list-struct-fix-ind struct parents)
20132 (let ((block-item
20133 (org-list-struct-fix-box struct parents prevs orderedp)))
20134 (if (and box (equal struct old-struct))
20135 (if (equal arg '(16))
20136 (message "Checkboxes already reset")
20137 (user-error "Cannot toggle this checkbox: %s"
20138 (if (eq box 'on)
20139 "all subitems checked"
20140 "unchecked subitems")))
20141 (org-list-struct-apply-struct struct old-struct)
20142 (org-update-checkbox-count-maybe))
20143 (when block-item
20144 (message "Checkboxes were removed due to empty box at line %d"
20145 (org-current-line block-item))))))
20146 (keyword
20147 (let ((org-inhibit-startup-visibility-stuff t)
20148 (org-startup-align-all-tables nil))
20149 (when (boundp 'org-table-coordinate-overlays)
20150 (mapc 'delete-overlay org-table-coordinate-overlays)
20151 (setq org-table-coordinate-overlays nil))
20152 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20153 (message "Local setup has been refreshed"))
20154 (plain-list
20155 ;; At a plain list, with a double C-u argument, set
20156 ;; checkboxes of each item to "[-]", whereas a single one
20157 ;; will toggle their presence according to the state of the
20158 ;; first item in the list. Without an argument, repair the
20159 ;; list.
20160 (let* ((begin (org-element-property :contents-begin context))
20161 (beginm (move-marker (make-marker) begin))
20162 (struct (org-element-property :structure context))
20163 (old-struct (copy-tree struct))
20164 (first-box (save-excursion
20165 (goto-char begin)
20166 (looking-at org-list-full-item-re)
20167 (match-string-no-properties 3)))
20168 (new-box (cond ((equal arg '(16)) "[-]")
20169 ((equal arg '(4)) (unless first-box "[ ]"))
20170 ((equal first-box "[X]") "[ ]")
20171 (t "[X]"))))
20172 (cond
20173 (arg
20174 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20175 (org-list-get-all-items
20176 begin struct (org-list-prevs-alist struct))))
20177 ((and first-box (eq (point) begin))
20178 ;; For convenience, when point is at bol on the first
20179 ;; item of the list and no argument is provided, simply
20180 ;; toggle checkbox of that item, if any.
20181 (org-list-set-checkbox begin struct new-box)))
20182 (org-list-write-struct
20183 struct (org-list-parents-alist struct) old-struct)
20184 (org-update-checkbox-count-maybe)
20185 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20186 ((property-drawer node-property)
20187 (call-interactively 'org-property-action))
20188 ((radio-target target)
20189 (call-interactively 'org-update-radio-target-regexp))
20190 (statistics-cookie
20191 (call-interactively 'org-update-statistics-cookies))
20192 ((table table-cell table-row)
20193 ;; At a table, recalculate every field and align it. Also
20194 ;; send the table if necessary. If the table has
20195 ;; a `table.el' type, just give up. At a table row or
20196 ;; cell, maybe recalculate line but always align table.
20197 (if (eq (org-element-property :type context) 'table.el)
20198 (message "Use C-c ' to edit table.el tables")
20199 (let ((org-enable-table-editor t))
20200 (if (or (eq type 'table)
20201 ;; Check if point is at a TBLFM line.
20202 (and (eq type 'table-row)
20203 (= (point) (org-element-property :end context))))
20204 (save-excursion
20205 (if (org-at-TBLFM-p) (org-calc-current-TBLFM)
20206 (goto-char (org-element-property :contents-begin context))
20207 (org-call-with-arg 'org-table-recalculate (or arg t))
20208 (orgtbl-send-table 'maybe)))
20209 (org-table-maybe-eval-formula)
20210 (cond (arg (call-interactively 'org-table-recalculate))
20211 ((org-table-maybe-recalculate-line))
20212 (t (org-table-align)))))))
20213 (timestamp (org-timestamp-change 0 'day))
20214 (otherwise
20215 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20216 (user-error
20217 "C-c C-c can do nothing useful at this location")))))))))
20219 (defun org-mode-restart ()
20220 "Restart Org-mode, to scan again for special lines.
20221 Also updates the keyword regular expressions."
20222 (interactive)
20223 (org-mode)
20224 (message "Org-mode restarted"))
20226 (defun org-kill-note-or-show-branches ()
20227 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20228 (interactive)
20229 (if (not org-finish-function)
20230 (progn
20231 (hide-subtree)
20232 (call-interactively 'show-branches))
20233 (let ((org-note-abort t))
20234 (funcall org-finish-function))))
20236 (defun org-ctrl-o (n)
20237 "Insert a new row in tables, call `open-line' elsewhere."
20238 (interactive "*p")
20239 (if (org-at-table-p)
20240 (org-table-insert-row)
20241 (open-line n)))
20243 (defun org-return (&optional indent)
20244 "Goto next table row or insert a newline.
20245 Calls `org-table-next-row' or `newline', depending on context.
20246 See the individual commands for more information."
20247 (interactive)
20248 (let (org-ts-what)
20249 (cond
20250 ((or (bobp) (org-in-src-block-p))
20251 (if indent (newline-and-indent) (newline)))
20252 ((org-at-table-p)
20253 (org-table-justify-field-maybe)
20254 (call-interactively 'org-table-next-row))
20255 ;; when `newline-and-indent' is called within a list, make sure
20256 ;; text moved stays inside the item.
20257 ((and (org-in-item-p) indent)
20258 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20259 (progn
20260 (save-match-data (newline))
20261 (org-indent-line-to (length (match-string 0))))
20262 (let ((ind (org-get-indentation)))
20263 (newline)
20264 (if (org-looking-back org-list-end-re)
20265 (org-indent-line)
20266 (org-indent-line-to ind)))))
20267 ((and org-return-follows-link
20268 (org-at-timestamp-p t)
20269 (not (eq org-ts-what 'after)))
20270 (org-follow-timestamp-link))
20271 ((and org-return-follows-link
20272 (let ((tprop (get-text-property (point) 'face)))
20273 (or (eq tprop 'org-link)
20274 (and (listp tprop) (memq 'org-link tprop)))))
20275 (call-interactively 'org-open-at-point))
20276 ((and (org-at-heading-p)
20277 (looking-at
20278 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20279 (org-show-entry)
20280 (end-of-line 1)
20281 (newline))
20282 (t (if indent (newline-and-indent) (newline))))))
20284 (defun org-return-indent ()
20285 "Goto next table row or insert a newline and indent.
20286 Calls `org-table-next-row' or `newline-and-indent', depending on
20287 context. See the individual commands for more information."
20288 (interactive)
20289 (org-return t))
20291 (defun org-ctrl-c-star ()
20292 "Compute table, or change heading status of lines.
20293 Calls `org-table-recalculate' or `org-toggle-heading',
20294 depending on context."
20295 (interactive)
20296 (cond
20297 ((org-at-table-p)
20298 (call-interactively 'org-table-recalculate))
20300 ;; Convert all lines in region to list items
20301 (call-interactively 'org-toggle-heading))))
20303 (defun org-ctrl-c-minus ()
20304 "Insert separator line in table or modify bullet status of line.
20305 Also turns a plain line or a region of lines into list items.
20306 Calls `org-table-insert-hline', `org-toggle-item', or
20307 `org-cycle-list-bullet', depending on context."
20308 (interactive)
20309 (cond
20310 ((org-at-table-p)
20311 (call-interactively 'org-table-insert-hline))
20312 ((org-region-active-p)
20313 (call-interactively 'org-toggle-item))
20314 ((org-in-item-p)
20315 (call-interactively 'org-cycle-list-bullet))
20317 (call-interactively 'org-toggle-item))))
20319 (defun org-toggle-item (arg)
20320 "Convert headings or normal lines to items, items to normal lines.
20321 If there is no active region, only the current line is considered.
20323 If the first non blank line in the region is a headline, convert
20324 all headlines to items, shifting text accordingly.
20326 If it is an item, convert all items to normal lines.
20328 If it is normal text, change region into a list of items.
20329 With a prefix argument ARG, change the region in a single item."
20330 (interactive "P")
20331 (let ((shift-text
20332 (function
20333 ;; Shift text in current section to IND, from point to END.
20334 ;; The function leaves point to END line.
20335 (lambda (ind end)
20336 (let ((min-i 1000) (end (copy-marker end)))
20337 ;; First determine the minimum indentation (MIN-I) of
20338 ;; the text.
20339 (save-excursion
20340 (catch 'exit
20341 (while (< (point) end)
20342 (let ((i (org-get-indentation)))
20343 (cond
20344 ;; Skip blank lines and inline tasks.
20345 ((looking-at "^[ \t]*$"))
20346 ((looking-at org-outline-regexp-bol))
20347 ;; We can't find less than 0 indentation.
20348 ((zerop i) (throw 'exit (setq min-i 0)))
20349 ((< i min-i) (setq min-i i))))
20350 (forward-line))))
20351 ;; Then indent each line so that a line indented to
20352 ;; MIN-I becomes indented to IND. Ignore blank lines
20353 ;; and inline tasks in the process.
20354 (let ((delta (- ind min-i)))
20355 (while (< (point) end)
20356 (unless (or (looking-at "^[ \t]*$")
20357 (looking-at org-outline-regexp-bol))
20358 (org-indent-line-to (+ (org-get-indentation) delta)))
20359 (forward-line)))))))
20360 (skip-blanks
20361 (function
20362 ;; Return beginning of first non-blank line, starting from
20363 ;; line at POS.
20364 (lambda (pos)
20365 (save-excursion
20366 (goto-char pos)
20367 (skip-chars-forward " \r\t\n")
20368 (point-at-bol)))))
20369 beg end)
20370 ;; Determine boundaries of changes.
20371 (if (org-region-active-p)
20372 (setq beg (funcall skip-blanks (region-beginning))
20373 end (copy-marker (region-end)))
20374 (setq beg (funcall skip-blanks (point-at-bol))
20375 end (copy-marker (point-at-eol))))
20376 ;; Depending on the starting line, choose an action on the text
20377 ;; between BEG and END.
20378 (org-with-limited-levels
20379 (save-excursion
20380 (goto-char beg)
20381 (cond
20382 ;; Case 1. Start at an item: de-itemize. Note that it only
20383 ;; happens when a region is active: `org-ctrl-c-minus'
20384 ;; would call `org-cycle-list-bullet' otherwise.
20385 ((org-at-item-p)
20386 (while (< (point) end)
20387 (when (org-at-item-p)
20388 (skip-chars-forward " \t")
20389 (delete-region (point) (match-end 0)))
20390 (forward-line)))
20391 ;; Case 2. Start at an heading: convert to items.
20392 ((org-at-heading-p)
20393 (let* ((bul (org-list-bullet-string "-"))
20394 (bul-len (length bul))
20395 ;; Indentation of the first heading. It should be
20396 ;; relative to the indentation of its parent, if any.
20397 (start-ind (save-excursion
20398 (cond
20399 ((not org-adapt-indentation) 0)
20400 ((not (outline-previous-heading)) 0)
20401 (t (length (match-string 0))))))
20402 ;; Level of first heading. Further headings will be
20403 ;; compared to it to determine hierarchy in the list.
20404 (ref-level (org-reduced-level (org-outline-level))))
20405 (while (< (point) end)
20406 (let* ((level (org-reduced-level (org-outline-level)))
20407 (delta (max 0 (- level ref-level))))
20408 ;; If current headline is less indented than the first
20409 ;; one, set it as reference, in order to preserve
20410 ;; subtrees.
20411 (when (< level ref-level) (setq ref-level level))
20412 (replace-match bul t t)
20413 (org-indent-line-to (+ start-ind (* delta bul-len)))
20414 ;; Ensure all text down to END (or SECTION-END) belongs
20415 ;; to the newly created item.
20416 (let ((section-end (save-excursion
20417 (or (outline-next-heading) (point)))))
20418 (forward-line)
20419 (funcall shift-text
20420 (+ start-ind (* (1+ delta) bul-len))
20421 (min end section-end)))))))
20422 ;; Case 3. Normal line with ARG: make the first line of region
20423 ;; an item, and shift indentation of others lines to
20424 ;; set them as item's body.
20425 (arg (let* ((bul (org-list-bullet-string "-"))
20426 (bul-len (length bul))
20427 (ref-ind (org-get-indentation)))
20428 (skip-chars-forward " \t")
20429 (insert bul)
20430 (forward-line)
20431 (while (< (point) end)
20432 ;; Ensure that lines less indented than first one
20433 ;; still get included in item body.
20434 (funcall shift-text
20435 (+ ref-ind bul-len)
20436 (min end (save-excursion (or (outline-next-heading)
20437 (point)))))
20438 (forward-line))))
20439 ;; Case 4. Normal line without ARG: turn each non-item line
20440 ;; into an item.
20442 (while (< (point) end)
20443 (unless (or (org-at-heading-p) (org-at-item-p))
20444 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20445 (replace-match
20446 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20447 (forward-line))))))))
20449 (defun org-toggle-heading (&optional nstars)
20450 "Convert headings to normal text, or items or text to headings.
20451 If there is no active region, only convert the current line.
20453 With a \\[universal-argument] prefix, convert the whole list at
20454 point into heading.
20456 In a region:
20458 - If the first non blank line is a headline, remove the stars
20459 from all headlines in the region.
20461 - If it is a normal line, turn each and every normal line (i.e.,
20462 not an heading or an item) in the region into headings. If you
20463 want to convert only the first line of this region, use one
20464 universal prefix argument.
20466 - If it is a plain list item, turn all plain list items into headings.
20468 When converting a line into a heading, the number of stars is chosen
20469 such that the lines become children of the current entry. However,
20470 when a numeric prefix argument is given, its value determines the
20471 number of stars to add."
20472 (interactive "P")
20473 (let ((skip-blanks
20474 (function
20475 ;; Return beginning of first non-blank line, starting from
20476 ;; line at POS.
20477 (lambda (pos)
20478 (save-excursion
20479 (goto-char pos)
20480 (while (org-at-comment-p) (forward-line))
20481 (skip-chars-forward " \r\t\n")
20482 (point-at-bol)))))
20483 beg end toggled)
20484 ;; Determine boundaries of changes. If a universal prefix has
20485 ;; been given, put the list in a region. If region ends at a bol,
20486 ;; do not consider the last line to be in the region.
20488 (when (and current-prefix-arg (org-at-item-p))
20489 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20490 (org-mark-element))
20492 (if (org-region-active-p)
20493 (setq beg (funcall skip-blanks (region-beginning))
20494 end (copy-marker (save-excursion
20495 (goto-char (region-end))
20496 (if (bolp) (point) (point-at-eol)))))
20497 (setq beg (funcall skip-blanks (point-at-bol))
20498 end (copy-marker (point-at-eol))))
20499 ;; Ensure inline tasks don't count as headings.
20500 (org-with-limited-levels
20501 (save-excursion
20502 (goto-char beg)
20503 (cond
20504 ;; Case 1. Started at an heading: de-star headings.
20505 ((org-at-heading-p)
20506 (while (< (point) end)
20507 (when (org-at-heading-p t)
20508 (looking-at org-outline-regexp) (replace-match "")
20509 (setq toggled t))
20510 (forward-line)))
20511 ;; Case 2. Started at an item: change items into headlines.
20512 ;; One star will be added by `org-list-to-subtree'.
20513 ((org-at-item-p)
20514 (let* ((stars (make-string
20515 ;; subtract the star that will be added again by
20516 ;; `org-list-to-subtree'
20517 (if (numberp nstars) (1- nstars)
20518 (or (org-current-level) 0))
20519 ?*))
20520 (add-stars
20521 (cond (nstars "") ; stars from prefix only
20522 ((equal stars "") "") ; before first heading
20523 (org-odd-levels-only "*") ; inside heading, odd
20524 (t "")))) ; inside heading, oddeven
20525 (while (< (point) end)
20526 (when (org-at-item-p)
20527 ;; Pay attention to cases when region ends before list.
20528 (let* ((struct (org-list-struct))
20529 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20530 (save-restriction
20531 (narrow-to-region (point) list-end)
20532 (insert
20533 (org-list-to-subtree
20534 (org-list-parse-list t)
20535 '(:istart (concat stars add-stars (funcall get-stars depth))
20536 :icount (concat stars add-stars (funcall get-stars depth)))))))
20537 (setq toggled t))
20538 (forward-line))))
20539 ;; Case 3. Started at normal text: make every line an heading,
20540 ;; skipping headlines and items.
20541 (t (let* ((stars
20542 (make-string
20543 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20544 (add-stars
20545 (cond (nstars "") ; stars from prefix only
20546 ((equal stars "") "*") ; before first heading
20547 (org-odd-levels-only "**") ; inside heading, odd
20548 (t "*"))) ; inside heading, oddeven
20549 (rpl (concat stars add-stars " "))
20550 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20551 (while (< (point) (if (equal nstars '(4)) lend end))
20552 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20553 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20554 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20555 (forward-line)))))))
20556 (unless toggled (message "Cannot toggle heading from here"))))
20558 (defun org-meta-return (&optional arg)
20559 "Insert a new heading or wrap a region in a table.
20560 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20561 See the individual commands for more information."
20562 (interactive "P")
20563 (cond
20564 ((run-hook-with-args-until-success 'org-metareturn-hook))
20565 ((or (org-at-drawer-p) (org-at-property-p))
20566 (newline-and-indent))
20567 ((org-at-table-p)
20568 (call-interactively 'org-table-wrap-region))
20569 (t (call-interactively 'org-insert-heading))))
20571 ;;; Menu entries
20573 (defsubst org-in-subtree-not-table-p ()
20574 "Are we in a subtree and not in a table?"
20575 (and (not (org-before-first-heading-p))
20576 (not (org-at-table-p))))
20578 ;; Define the Org-mode menus
20579 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20580 '("Tbl"
20581 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20582 ["Next Field" org-cycle (org-at-table-p)]
20583 ["Previous Field" org-shifttab (org-at-table-p)]
20584 ["Next Row" org-return (org-at-table-p)]
20585 "--"
20586 ["Blank Field" org-table-blank-field (org-at-table-p)]
20587 ["Edit Field" org-table-edit-field (org-at-table-p)]
20588 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20589 "--"
20590 ("Column"
20591 ["Move Column Left" org-metaleft (org-at-table-p)]
20592 ["Move Column Right" org-metaright (org-at-table-p)]
20593 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20594 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20595 ("Row"
20596 ["Move Row Up" org-metaup (org-at-table-p)]
20597 ["Move Row Down" org-metadown (org-at-table-p)]
20598 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20599 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20600 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20601 "--"
20602 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20603 ("Rectangle"
20604 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20605 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20606 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20607 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20608 "--"
20609 ("Calculate"
20610 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20611 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20612 ["Edit Formulas" org-edit-special (org-at-table-p)]
20613 "--"
20614 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20615 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20616 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20617 "--"
20618 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20619 "--"
20620 ["Sum Column/Rectangle" org-table-sum
20621 (or (org-at-table-p) (org-region-active-p))]
20622 ["Which Column?" org-table-current-column (org-at-table-p)])
20623 ["Debug Formulas"
20624 org-table-toggle-formula-debugger
20625 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20626 ["Show Col/Row Numbers"
20627 org-table-toggle-coordinate-overlays
20628 :style toggle
20629 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20630 "--"
20631 ["Create" org-table-create (and (not (org-at-table-p))
20632 org-enable-table-editor)]
20633 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20634 ["Import from File" org-table-import (not (org-at-table-p))]
20635 ["Export to File" org-table-export (org-at-table-p)]
20636 "--"
20637 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20639 (easy-menu-define org-org-menu org-mode-map "Org menu"
20640 '("Org"
20641 ("Show/Hide"
20642 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20643 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20644 ["Sparse Tree..." org-sparse-tree t]
20645 ["Reveal Context" org-reveal t]
20646 ["Show All" show-all t]
20647 "--"
20648 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20649 "--"
20650 ["New Heading" org-insert-heading t]
20651 ("Navigate Headings"
20652 ["Up" outline-up-heading t]
20653 ["Next" outline-next-visible-heading t]
20654 ["Previous" outline-previous-visible-heading t]
20655 ["Next Same Level" outline-forward-same-level t]
20656 ["Previous Same Level" outline-backward-same-level t]
20657 "--"
20658 ["Jump" org-goto t])
20659 ("Edit Structure"
20660 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20661 "--"
20662 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20663 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20664 "--"
20665 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20666 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20667 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20668 "--"
20669 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20670 "--"
20671 ["Copy visible text" org-copy-visible t]
20672 "--"
20673 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20674 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20675 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20676 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20677 "--"
20678 ["Sort Region/Children" org-sort t]
20679 "--"
20680 ["Convert to odd levels" org-convert-to-odd-levels t]
20681 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20682 ("Editing"
20683 ["Emphasis..." org-emphasize t]
20684 ["Edit Source Example" org-edit-special t]
20685 "--"
20686 ["Footnote new/jump" org-footnote-action t]
20687 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20688 ("Archive"
20689 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20690 "--"
20691 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20692 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20693 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20695 "--"
20696 ("Hyperlinks"
20697 ["Store Link (Global)" org-store-link t]
20698 ["Find existing link to here" org-occur-link-in-agenda-files t]
20699 ["Insert Link" org-insert-link t]
20700 ["Follow Link" org-open-at-point t]
20701 "--"
20702 ["Next link" org-next-link t]
20703 ["Previous link" org-previous-link t]
20704 "--"
20705 ["Descriptive Links"
20706 org-toggle-link-display
20707 :style radio
20708 :selected org-descriptive-links
20710 ["Literal Links"
20711 org-toggle-link-display
20712 :style radio
20713 :selected (not org-descriptive-links)])
20714 "--"
20715 ("TODO Lists"
20716 ["TODO/DONE/-" org-todo t]
20717 ("Select keyword"
20718 ["Next keyword" org-shiftright (org-at-heading-p)]
20719 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20720 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20721 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20722 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20723 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20724 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20725 "--"
20726 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20727 :selected org-enforce-todo-dependencies :style toggle :active t]
20728 "Settings for tree at point"
20729 ["Do Children sequentially" org-toggle-ordered-property :style radio
20730 :selected (org-entry-get nil "ORDERED")
20731 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20732 ["Do Children parallel" org-toggle-ordered-property :style radio
20733 :selected (not (org-entry-get nil "ORDERED"))
20734 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20735 "--"
20736 ["Set Priority" org-priority t]
20737 ["Priority Up" org-shiftup t]
20738 ["Priority Down" org-shiftdown t]
20739 "--"
20740 ["Get news from all feeds" org-feed-update-all t]
20741 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20742 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20743 ("TAGS and Properties"
20744 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20745 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20746 "--"
20747 ["Set property" org-set-property (not (org-before-first-heading-p))]
20748 ["Column view of properties" org-columns t]
20749 ["Insert Column View DBlock" org-insert-columns-dblock t])
20750 ("Dates and Scheduling"
20751 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20752 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20753 ("Change Date"
20754 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20755 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20756 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20757 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20758 ["Compute Time Range" org-evaluate-time-range t]
20759 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20760 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20761 "--"
20762 ["Custom time format" org-toggle-time-stamp-overlays
20763 :style radio :selected org-display-custom-times]
20764 "--"
20765 ["Goto Calendar" org-goto-calendar t]
20766 ["Date from Calendar" org-date-from-calendar t]
20767 "--"
20768 ["Start/Restart Timer" org-timer-start t]
20769 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20770 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20771 ["Insert Timer String" org-timer t]
20772 ["Insert Timer Item" org-timer-item t])
20773 ("Logging work"
20774 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20775 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20776 ["Clock out" org-clock-out t]
20777 ["Clock cancel" org-clock-cancel t]
20778 "--"
20779 ["Mark as default task" org-clock-mark-default-task t]
20780 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20781 ["Goto running clock" org-clock-goto t]
20782 "--"
20783 ["Display times" org-clock-display t]
20784 ["Create clock table" org-clock-report t]
20785 "--"
20786 ["Record DONE time"
20787 (progn (setq org-log-done (not org-log-done))
20788 (message "Switching to %s will %s record a timestamp"
20789 (car org-done-keywords)
20790 (if org-log-done "automatically" "not")))
20791 :style toggle :selected org-log-done])
20792 "--"
20793 ["Agenda Command..." org-agenda t]
20794 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20795 ("File List for Agenda")
20796 ("Special views current file"
20797 ["TODO Tree" org-show-todo-tree t]
20798 ["Check Deadlines" org-check-deadlines t]
20799 ["Timeline" org-timeline t]
20800 ["Tags/Property tree" org-match-sparse-tree t])
20801 "--"
20802 ["Export/Publish..." org-export-dispatch t]
20803 ("LaTeX"
20804 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20805 :selected org-cdlatex-mode]
20806 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20807 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20808 ["Modify math symbol" org-cdlatex-math-modify
20809 (org-inside-LaTeX-fragment-p)]
20810 ["Insert citation" org-reftex-citation t]
20811 "--"
20812 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20813 "--"
20814 ("MobileOrg"
20815 ["Push Files and Views" org-mobile-push t]
20816 ["Get Captured and Flagged" org-mobile-pull t]
20817 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20818 "--"
20819 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20820 "--"
20821 ("Documentation"
20822 ["Show Version" org-version t]
20823 ["Info Documentation" org-info t])
20824 ("Customize"
20825 ["Browse Org Group" org-customize t]
20826 "--"
20827 ["Expand This Menu" org-create-customize-menu
20828 (fboundp 'customize-menu-create)])
20829 ["Send bug report" org-submit-bug-report t]
20830 "--"
20831 ("Refresh/Reload"
20832 ["Refresh setup current buffer" org-mode-restart t]
20833 ["Reload Org (after update)" org-reload t]
20834 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20837 (defun org-info (&optional node)
20838 "Read documentation for Org-mode in the info system.
20839 With optional NODE, go directly to that node."
20840 (interactive)
20841 (info (format "(org)%s" (or node ""))))
20843 ;;;###autoload
20844 (defun org-submit-bug-report ()
20845 "Submit a bug report on Org-mode via mail.
20847 Don't hesitate to report any problems or inaccurate documentation.
20849 If you don't have setup sending mail from (X)Emacs, please copy the
20850 output buffer into your mail program, as it gives us important
20851 information about your Org-mode version and configuration."
20852 (interactive)
20853 (require 'reporter)
20854 (org-load-modules-maybe)
20855 (org-require-autoloaded-modules)
20856 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20857 (reporter-submit-bug-report
20858 "emacs-orgmode@gnu.org"
20859 (org-version nil 'full)
20860 (let (list)
20861 (save-window-excursion
20862 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20863 (delete-other-windows)
20864 (erase-buffer)
20865 (insert "You are about to submit a bug report to the Org-mode mailing list.
20867 We would like to add your full Org-mode and Outline configuration to the
20868 bug report. This greatly simplifies the work of the maintainer and
20869 other experts on the mailing list.
20871 HOWEVER, some variables you have customized may contain private
20872 information. The names of customers, colleagues, or friends, might
20873 appear in the form of file names, tags, todo states, or search strings.
20874 If you answer yes to the prompt, you might want to check and remove
20875 such private information before sending the email.")
20876 (add-text-properties (point-min) (point-max) '(face org-warning))
20877 (when (yes-or-no-p "Include your Org-mode configuration ")
20878 (mapatoms
20879 (lambda (v)
20880 (and (boundp v)
20881 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20882 (or (and (symbol-value v)
20883 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20884 (and
20885 (get v 'custom-type) (get v 'standard-value)
20886 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20887 (push v list)))))
20888 (kill-buffer (get-buffer "*Warn about privacy*"))
20889 list))
20890 nil nil
20891 "Remember to cover the basics, that is, what you expected to happen and
20892 what in fact did happen. You don't know how to make a good report? See
20894 http://orgmode.org/manual/Feedback.html#Feedback
20896 Your bug report will be posted to the Org-mode mailing list.
20897 ------------------------------------------------------------------------")
20898 (save-excursion
20899 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20900 (replace-match "\\1Bug: \\3 [\\2]")))))
20903 (defun org-install-agenda-files-menu ()
20904 (let ((bl (buffer-list)))
20905 (save-excursion
20906 (while bl
20907 (set-buffer (pop bl))
20908 (if (derived-mode-p 'org-mode) (setq bl nil)))
20909 (when (derived-mode-p 'org-mode)
20910 (easy-menu-change
20911 '("Org") "File List for Agenda"
20912 (append
20913 (list
20914 ["Edit File List" (org-edit-agenda-file-list) t]
20915 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20916 ["Remove Current File from List" org-remove-file t]
20917 ["Cycle through agenda files" org-cycle-agenda-files t]
20918 ["Occur in all agenda files" org-occur-in-agenda-files t]
20919 "--")
20920 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20922 ;;;; Documentation
20924 (defun org-require-autoloaded-modules ()
20925 (interactive)
20926 (mapc 'require
20927 '(org-agenda org-archive org-attach org-clock org-colview org-id
20928 org-remember org-table org-timer)))
20930 ;;;###autoload
20931 (defun org-reload (&optional uncompiled)
20932 "Reload all org lisp files.
20933 With prefix arg UNCOMPILED, load the uncompiled versions."
20934 (interactive "P")
20935 (require 'loadhist)
20936 (let* ((org-dir (org-find-library-dir "org"))
20937 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20938 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20939 (remove-re (mapconcat 'identity
20940 (mapcar (lambda (f) (concat "^" f "$"))
20941 (list (if (featurep 'xemacs)
20942 "org-colview"
20943 "org-colview-xemacs")
20944 "org" "org-loaddefs" "org-version"))
20945 "\\|"))
20946 (feats (delete-dups
20947 (mapcar 'file-name-sans-extension
20948 (mapcar 'file-name-nondirectory
20949 (delq nil
20950 (mapcar 'feature-file
20951 features))))))
20952 (lfeat (append
20953 (sort
20954 (setq feats
20955 (delq nil (mapcar
20956 (lambda (f)
20957 (if (and (string-match feature-re f)
20958 (not (string-match remove-re f)))
20959 f nil))
20960 feats)))
20961 'string-lessp)
20962 (list "org-version" "org")))
20963 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20964 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20965 load-uncore load-misses)
20966 (setq load-misses
20967 (delq 't
20968 (mapcar (lambda (f)
20969 (or (org-load-noerror-mustsuffix (concat org-dir f))
20970 (and (string= org-dir contrib-dir)
20971 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20972 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20973 (add-to-list 'load-uncore f 'append)
20976 lfeat)))
20977 (if load-uncore
20978 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20979 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20980 (if load-misses
20981 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20982 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20983 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20985 ;;;###autoload
20986 (defun org-customize ()
20987 "Call the customize function with org as argument."
20988 (interactive)
20989 (org-load-modules-maybe)
20990 (org-require-autoloaded-modules)
20991 (customize-browse 'org))
20993 (defun org-create-customize-menu ()
20994 "Create a full customization menu for Org-mode, insert it into the menu."
20995 (interactive)
20996 (org-load-modules-maybe)
20997 (org-require-autoloaded-modules)
20998 (if (fboundp 'customize-menu-create)
20999 (progn
21000 (easy-menu-change
21001 '("Org") "Customize"
21002 `(["Browse Org group" org-customize t]
21003 "--"
21004 ,(customize-menu-create 'org)
21005 ["Set" Custom-set t]
21006 ["Save" Custom-save t]
21007 ["Reset to Current" Custom-reset-current t]
21008 ["Reset to Saved" Custom-reset-saved t]
21009 ["Reset to Standard Settings" Custom-reset-standard t]))
21010 (message "\"Org\"-menu now contains full customization menu"))
21011 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21013 ;;;; Miscellaneous stuff
21015 ;;; Generally useful functions
21017 (defun org-get-at-bol (property)
21018 "Get text property PROPERTY at beginning of line."
21019 (get-text-property (point-at-bol) property))
21021 (defun org-find-text-property-in-string (prop s)
21022 "Return the first non-nil value of property PROP in string S."
21023 (or (get-text-property 0 prop s)
21024 (get-text-property (or (next-single-property-change 0 prop s) 0)
21025 prop s)))
21027 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21028 "Display the given MESSAGE as a warning."
21029 (if (fboundp 'display-warning)
21030 (display-warning 'org message
21031 (if (featurep 'xemacs) 'warning :warning))
21032 (let ((buf (get-buffer-create "*Org warnings*")))
21033 (with-current-buffer buf
21034 (goto-char (point-max))
21035 (insert "Warning (Org): " message)
21036 (unless (bolp)
21037 (newline)))
21038 (display-buffer buf)
21039 (sit-for 0))))
21041 (defun org-eval (form)
21042 "Eval FORM and return result."
21043 (condition-case error
21044 (eval form)
21045 (error (format "%%![Error: %s]" error))))
21047 (defun org-in-clocktable-p ()
21048 "Check if the cursor is in a clocktable."
21049 (let ((pos (point)) start)
21050 (save-excursion
21051 (end-of-line 1)
21052 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21053 (setq start (match-beginning 0))
21054 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21055 (>= (match-end 0) pos)
21056 start))))
21058 (defun org-in-commented-line ()
21059 "Is point in a line starting with `#'?"
21060 (equal (char-after (point-at-bol)) ?#))
21062 (defun org-in-indented-comment-line ()
21063 "Is point in a line starting with `#' after some white space?"
21064 (save-excursion
21065 (save-match-data
21066 (goto-char (point-at-bol))
21067 (looking-at "[ \t]*#"))))
21069 (defun org-in-verbatim-emphasis ()
21070 (save-match-data
21071 (and (org-in-regexp org-emph-re 2)
21072 (>= (point) (match-beginning 3))
21073 (<= (point) (match-end 4))
21074 (member (match-string 3) '("=" "~")))))
21076 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21077 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21078 (if (and marker (marker-buffer marker)
21079 (buffer-live-p (marker-buffer marker)))
21080 (progn
21081 (org-pop-to-buffer-same-window (marker-buffer marker))
21082 (if (or (> marker (point-max)) (< marker (point-min)))
21083 (widen))
21084 (goto-char marker)
21085 (org-show-context 'org-goto))
21086 (if bookmark
21087 (bookmark-jump bookmark)
21088 (error "Cannot find location"))))
21090 (defun org-quote-csv-field (s)
21091 "Quote field for inclusion in CSV material."
21092 (if (string-match "[\",]" s)
21093 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21096 (defun org-force-self-insert (N)
21097 "Needed to enforce self-insert under remapping."
21098 (interactive "p")
21099 (self-insert-command N))
21101 (defun org-string-width (s)
21102 "Compute width of string, ignoring invisible characters.
21103 This ignores character with invisibility property `org-link', and also
21104 characters with property `org-cwidth', because these will become invisible
21105 upon the next fontification round."
21106 (let (b l)
21107 (when (or (eq t buffer-invisibility-spec)
21108 (assq 'org-link buffer-invisibility-spec))
21109 (while (setq b (text-property-any 0 (length s)
21110 'invisible 'org-link s))
21111 (setq s (concat (substring s 0 b)
21112 (substring s (or (next-single-property-change
21113 b 'invisible s) (length s)))))))
21114 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21115 (setq s (concat (substring s 0 b)
21116 (substring s (or (next-single-property-change
21117 b 'org-cwidth s) (length s))))))
21118 (setq l (string-width s) b -1)
21119 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21120 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21123 (defun org-shorten-string (s maxlength)
21124 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21125 If the string is shorter or has length MAXLENGTH, just return the
21126 original string. If it is longer, the functions finds a space in the
21127 string, breaks this string off at that locations and adds three dots
21128 as ellipsis. Including the ellipsis, the string will not be longer
21129 than MAXLENGTH. If finding a good breaking point in the string does
21130 not work, the string is just chopped off in the middle of a word
21131 if necessary."
21132 (if (<= (length s) maxlength)
21134 (let* ((n (max (- maxlength 4) 1))
21135 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21136 (if (string-match re s)
21137 (concat (match-string 1 s) "...")
21138 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21140 (defun org-get-indentation (&optional line)
21141 "Get the indentation of the current line, interpreting tabs.
21142 When LINE is given, assume it represents a line and compute its indentation."
21143 (if line
21144 (if (string-match "^ *" (org-remove-tabs line))
21145 (match-end 0))
21146 (save-excursion
21147 (beginning-of-line 1)
21148 (skip-chars-forward " \t")
21149 (current-column))))
21151 (defun org-get-string-indentation (s)
21152 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21153 (let ((n -1) (i 0) (w tab-width) c)
21154 (catch 'exit
21155 (while (< (setq n (1+ n)) (length s))
21156 (setq c (aref s n))
21157 (cond ((= c ?\ ) (setq i (1+ i)))
21158 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21159 (t (throw 'exit t)))))
21162 (defun org-remove-tabs (s &optional width)
21163 "Replace tabulators in S with spaces.
21164 Assumes that s is a single line, starting in column 0."
21165 (setq width (or width tab-width))
21166 (while (string-match "\t" s)
21167 (setq s (replace-match
21168 (make-string
21169 (- (* width (/ (+ (match-beginning 0) width) width))
21170 (match-beginning 0)) ?\ )
21171 t t s)))
21174 (defun org-fix-indentation (line ind)
21175 "Fix indentation in LINE.
21176 IND is a cons cell with target and minimum indentation.
21177 If the current indentation in LINE is smaller than the minimum,
21178 leave it alone. If it is larger than ind, set it to the target."
21179 (let* ((l (org-remove-tabs line))
21180 (i (org-get-indentation l))
21181 (i1 (car ind)) (i2 (cdr ind)))
21182 (if (>= i i2) (setq l (substring line i2)))
21183 (if (> i1 0)
21184 (concat (make-string i1 ?\ ) l)
21185 l)))
21187 (defun org-remove-indentation (code &optional n)
21188 "Remove the maximum common indentation from the lines in CODE.
21189 N may optionally be the number of spaces to remove."
21190 (with-temp-buffer
21191 (insert code)
21192 (org-do-remove-indentation n)
21193 (buffer-string)))
21195 (defun org-do-remove-indentation (&optional n)
21196 "Remove the maximum common indentation from the buffer."
21197 (untabify (point-min) (point-max))
21198 (let ((min 10000) re)
21199 (if n
21200 (setq min n)
21201 (goto-char (point-min))
21202 (while (re-search-forward "^ *[^ \n]" nil t)
21203 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21204 (unless (or (= min 0) (= min 10000))
21205 (setq re (format "^ \\{%d\\}" min))
21206 (goto-char (point-min))
21207 (while (re-search-forward re nil t)
21208 (replace-match "")
21209 (end-of-line 1))
21210 min)))
21212 (defun org-fill-template (template alist)
21213 "Find each %key of ALIST in TEMPLATE and replace it."
21214 (let ((case-fold-search nil)
21215 entry key value)
21216 (setq alist (sort (copy-sequence alist)
21217 (lambda (a b) (< (length (car a)) (length (car b))))))
21218 (while (setq entry (pop alist))
21219 (setq template
21220 (replace-regexp-in-string
21221 (concat "%" (regexp-quote (car entry)))
21222 (or (cdr entry) "") template t t)))
21223 template))
21225 (defun org-base-buffer (buffer)
21226 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21227 (if (not buffer)
21228 buffer
21229 (or (buffer-base-buffer buffer)
21230 buffer)))
21232 (defun org-trim (s)
21233 "Remove whitespace at beginning and end of string."
21234 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21235 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21238 (defun org-wrap (string &optional width lines)
21239 "Wrap string to either a number of lines, or a width in characters.
21240 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21241 that costs. If there is a word longer than WIDTH, the text is actually
21242 wrapped to the length of that word.
21243 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21244 many lines, whatever width that takes.
21245 The return value is a list of lines, without newlines at the end."
21246 (let* ((words (org-split-string string "[ \t\n]+"))
21247 (maxword (apply 'max (mapcar 'org-string-width words)))
21248 w ll)
21249 (cond (width
21250 (org-do-wrap words (max maxword width)))
21251 (lines
21252 (setq w maxword)
21253 (setq ll (org-do-wrap words maxword))
21254 (if (<= (length ll) lines)
21256 (setq ll words)
21257 (while (> (length ll) lines)
21258 (setq w (1+ w))
21259 (setq ll (org-do-wrap words w)))
21260 ll))
21261 (t (error "Cannot wrap this")))))
21263 (defun org-do-wrap (words width)
21264 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21265 (let (lines line)
21266 (while words
21267 (setq line (pop words))
21268 (while (and words (< (+ (length line) (length (car words))) width))
21269 (setq line (concat line " " (pop words))))
21270 (setq lines (push line lines)))
21271 (nreverse lines)))
21273 (defun org-split-string (string &optional separators)
21274 "Splits STRING into substrings at SEPARATORS.
21275 No empty strings are returned if there are matches at the beginning
21276 and end of string."
21277 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21278 (start 0)
21279 notfirst
21280 (list nil))
21281 (while (and (string-match rexp string
21282 (if (and notfirst
21283 (= start (match-beginning 0))
21284 (< start (length string)))
21285 (1+ start) start))
21286 (< (match-beginning 0) (length string)))
21287 (setq notfirst t)
21288 (or (eq (match-beginning 0) 0)
21289 (and (eq (match-beginning 0) (match-end 0))
21290 (eq (match-beginning 0) start))
21291 (setq list
21292 (cons (substring string start (match-beginning 0))
21293 list)))
21294 (setq start (match-end 0)))
21295 (or (eq start (length string))
21296 (setq list
21297 (cons (substring string start)
21298 list)))
21299 (nreverse list)))
21301 (defun org-quote-vert (s)
21302 "Replace \"|\" with \"\\vert\"."
21303 (while (string-match "|" s)
21304 (setq s (replace-match "\\vert" t t s)))
21307 (defun org-uuidgen-p (s)
21308 "Is S an ID created by UUIDGEN?"
21309 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21311 (defun org-in-src-block-p (&optional inside)
21312 "Whether point is in a code source block.
21313 When INSIDE is non-nil, don't consider we are within a src block
21314 when point is at #+BEGIN_SRC or #+END_SRC."
21315 (let ((case-fold-search t) ov)
21316 (or (and (setq ov (overlays-at (point)))
21317 (memq 'org-block-background
21318 (overlay-properties (car ov))))
21319 (and (not inside)
21320 (save-match-data
21321 (save-excursion
21322 (beginning-of-line)
21323 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21325 (defun org-context ()
21326 "Return a list of contexts of the current cursor position.
21327 If several contexts apply, all are returned.
21328 Each context entry is a list with a symbol naming the context, and
21329 two positions indicating start and end of the context. Possible
21330 contexts are:
21332 :headline anywhere in a headline
21333 :headline-stars on the leading stars in a headline
21334 :todo-keyword on a TODO keyword (including DONE) in a headline
21335 :tags on the TAGS in a headline
21336 :priority on the priority cookie in a headline
21337 :item on the first line of a plain list item
21338 :item-bullet on the bullet/number of a plain list item
21339 :checkbox on the checkbox in a plain list item
21340 :table in an org-mode table
21341 :table-special on a special filed in a table
21342 :table-table in a table.el table
21343 :clocktable in a clocktable
21344 :src-block in a source block
21345 :link on a hyperlink
21346 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21347 :target on a <<target>>
21348 :radio-target on a <<<radio-target>>>
21349 :latex-fragment on a LaTeX fragment
21350 :latex-preview on a LaTeX fragment with overlaid preview image
21352 This function expects the position to be visible because it uses font-lock
21353 faces as a help to recognize the following contexts: :table-special, :link,
21354 and :keyword."
21355 (let* ((f (get-text-property (point) 'face))
21356 (faces (if (listp f) f (list f)))
21357 (case-fold-search t)
21358 (p (point)) clist o)
21359 ;; First the large context
21360 (cond
21361 ((org-at-heading-p t)
21362 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21363 (when (progn
21364 (beginning-of-line 1)
21365 (looking-at org-todo-line-tags-regexp))
21366 (push (org-point-in-group p 1 :headline-stars) clist)
21367 (push (org-point-in-group p 2 :todo-keyword) clist)
21368 (push (org-point-in-group p 4 :tags) clist))
21369 (goto-char p)
21370 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21371 (if (looking-at "\\[#[A-Z0-9]\\]")
21372 (push (org-point-in-group p 0 :priority) clist)))
21374 ((org-at-item-p)
21375 (push (org-point-in-group p 2 :item-bullet) clist)
21376 (push (list :item (point-at-bol)
21377 (save-excursion (org-end-of-item) (point)))
21378 clist)
21379 (and (org-at-item-checkbox-p)
21380 (push (org-point-in-group p 0 :checkbox) clist)))
21382 ((org-at-table-p)
21383 (push (list :table (org-table-begin) (org-table-end)) clist)
21384 (if (memq 'org-formula faces)
21385 (push (list :table-special
21386 (previous-single-property-change p 'face)
21387 (next-single-property-change p 'face)) clist)))
21388 ((org-at-table-p 'any)
21389 (push (list :table-table) clist)))
21390 (goto-char p)
21392 (let ((case-fold-search t))
21393 ;; New the "medium" contexts: clocktables, source blocks
21394 (cond ((org-in-clocktable-p)
21395 (push (list :clocktable
21396 (and (or (looking-at "#\\+BEGIN: clocktable")
21397 (search-backward "#+BEGIN: clocktable" nil t))
21398 (match-beginning 0))
21399 (and (re-search-forward "#\\+END:?" nil t)
21400 (match-end 0))) clist))
21401 ((org-in-src-block-p)
21402 (push (list :src-block
21403 (and (or (looking-at "#\\+BEGIN_SRC")
21404 (search-backward "#+BEGIN_SRC" nil t))
21405 (match-beginning 0))
21406 (and (search-forward "#+END_SRC" nil t)
21407 (match-beginning 0))) clist))))
21408 (goto-char p)
21410 ;; Now the small context
21411 (cond
21412 ((org-at-timestamp-p)
21413 (push (org-point-in-group p 0 :timestamp) clist))
21414 ((memq 'org-link faces)
21415 (push (list :link
21416 (previous-single-property-change p 'face)
21417 (next-single-property-change p 'face)) clist))
21418 ((memq 'org-special-keyword faces)
21419 (push (list :keyword
21420 (previous-single-property-change p 'face)
21421 (next-single-property-change p 'face)) clist))
21422 ((org-at-target-p)
21423 (push (org-point-in-group p 0 :target) clist)
21424 (goto-char (1- (match-beginning 0)))
21425 (if (looking-at org-radio-target-regexp)
21426 (push (org-point-in-group p 0 :radio-target) clist))
21427 (goto-char p))
21428 ((setq o (car (delq nil
21429 (mapcar
21430 (lambda (x)
21431 (if (memq x org-latex-fragment-image-overlays) x))
21432 (overlays-at (point))))))
21433 (push (list :latex-fragment
21434 (overlay-start o) (overlay-end o)) clist)
21435 (push (list :latex-preview
21436 (overlay-start o) (overlay-end o)) clist))
21437 ((org-inside-LaTeX-fragment-p)
21438 ;; FIXME: positions wrong.
21439 (push (list :latex-fragment (point) (point)) clist)))
21441 (setq clist (nreverse (delq nil clist)))
21442 clist))
21444 ;; FIXME: Compare with at-regexp-p Do we need both?
21445 (defun org-in-regexp (re &optional nlines visually)
21446 "Check if point is inside a match of regexp.
21447 Normally only the current line is checked, but you can include NLINES extra
21448 lines both before and after point into the search.
21449 If VISUALLY is set, require that the cursor is not after the match but
21450 really on, so that the block visually is on the match."
21451 (catch 'exit
21452 (let ((pos (point))
21453 (eol (point-at-eol (+ 1 (or nlines 0))))
21454 (inc (if visually 1 0)))
21455 (save-excursion
21456 (beginning-of-line (- 1 (or nlines 0)))
21457 (while (re-search-forward re eol t)
21458 (if (and (<= (match-beginning 0) pos)
21459 (>= (+ inc (match-end 0)) pos))
21460 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21462 (defun org-at-regexp-p (regexp)
21463 "Is point inside a match of REGEXP in the current line?"
21464 (catch 'exit
21465 (save-excursion
21466 (let ((pos (point)) (end (point-at-eol)))
21467 (beginning-of-line 1)
21468 (while (re-search-forward regexp end t)
21469 (if (and (<= (match-beginning 0) pos)
21470 (>= (match-end 0) pos))
21471 (throw 'exit t)))
21472 nil))))
21474 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21475 "Non-nil when point is between matches of START-RE and END-RE.
21477 Also return a non-nil value when point is on one of the matches.
21479 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21480 buffer positions. Default values are the positions of headlines
21481 surrounding the point.
21483 The functions returns a cons cell whose car (resp. cdr) is the
21484 position before START-RE (resp. after END-RE)."
21485 (save-match-data
21486 (let ((pos (point))
21487 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21488 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21489 beg end)
21490 (save-excursion
21491 ;; Point is on a block when on START-RE or if START-RE can be
21492 ;; found before it...
21493 (and (or (org-at-regexp-p start-re)
21494 (re-search-backward start-re limit-up t))
21495 (setq beg (match-beginning 0))
21496 ;; ... and END-RE after it...
21497 (goto-char (match-end 0))
21498 (re-search-forward end-re limit-down t)
21499 (> (setq end (match-end 0)) pos)
21500 ;; ... without another START-RE in-between.
21501 (goto-char (match-beginning 0))
21502 (not (re-search-backward start-re (1+ beg) t))
21503 ;; Return value.
21504 (cons beg end))))))
21506 (defun org-in-block-p (names)
21507 "Non-nil when point belongs to a block whose name belongs to NAMES.
21509 NAMES is a list of strings containing names of blocks.
21511 Return first block name matched, or nil. Beware that in case of
21512 nested blocks, the returned name may not belong to the closest
21513 block from point."
21514 (save-match-data
21515 (catch 'exit
21516 (let ((case-fold-search t)
21517 (lim-up (save-excursion (outline-previous-heading)))
21518 (lim-down (save-excursion (outline-next-heading))))
21519 (mapc (lambda (name)
21520 (let ((n (regexp-quote name)))
21521 (when (org-between-regexps-p
21522 (concat "^[ \t]*#\\+begin_" n)
21523 (concat "^[ \t]*#\\+end_" n)
21524 lim-up lim-down)
21525 (throw 'exit n))))
21526 names))
21527 nil)))
21529 (defun org-occur-in-agenda-files (regexp &optional nlines)
21530 "Call `multi-occur' with buffers for all agenda files."
21531 (interactive "sOrg-files matching: \np")
21532 (let* ((files (org-agenda-files))
21533 (tnames (mapcar 'file-truename files))
21534 (extra org-agenda-text-search-extra-files)
21536 (when (eq (car extra) 'agenda-archives)
21537 (setq extra (cdr extra))
21538 (setq files (org-add-archive-files files)))
21539 (while (setq f (pop extra))
21540 (unless (member (file-truename f) tnames)
21541 (add-to-list 'files f 'append)
21542 (add-to-list 'tnames (file-truename f) 'append)))
21543 (multi-occur
21544 (mapcar (lambda (x)
21545 (with-current-buffer
21546 (or (get-file-buffer x) (find-file-noselect x))
21547 (widen)
21548 (current-buffer)))
21549 files)
21550 regexp)))
21552 (if (boundp 'occur-mode-find-occurrence-hook)
21553 ;; Emacs 23
21554 (add-hook 'occur-mode-find-occurrence-hook
21555 (lambda ()
21556 (when (derived-mode-p 'org-mode)
21557 (org-reveal))))
21558 ;; Emacs 22
21559 (defadvice occur-mode-goto-occurrence
21560 (after org-occur-reveal activate)
21561 (and (derived-mode-p 'org-mode) (org-reveal)))
21562 (defadvice occur-mode-goto-occurrence-other-window
21563 (after org-occur-reveal activate)
21564 (and (derived-mode-p 'org-mode) (org-reveal)))
21565 (defadvice occur-mode-display-occurrence
21566 (after org-occur-reveal activate)
21567 (when (derived-mode-p 'org-mode)
21568 (let ((pos (occur-mode-find-occurrence)))
21569 (with-current-buffer (marker-buffer pos)
21570 (save-excursion
21571 (goto-char pos)
21572 (org-reveal)))))))
21574 (defun org-occur-link-in-agenda-files ()
21575 "Create a link and search for it in the agendas.
21576 The link is not stored in `org-stored-links', it is just created
21577 for the search purpose."
21578 (interactive)
21579 (let ((link (condition-case nil
21580 (org-store-link nil)
21581 (error "Unable to create a link to here"))))
21582 (org-occur-in-agenda-files (regexp-quote link))))
21584 (defun org-reverse-string (string)
21585 "Return the reverse of STRING."
21586 (apply 'string (reverse (string-to-list string))))
21588 (defun org-uniquify (list)
21589 "Remove duplicate elements from LIST."
21590 (let (res)
21591 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21592 res))
21594 (defun org-uniquify-alist (alist)
21595 "Merge duplicate elements of an alist.
21597 For example, in this alist:
21599 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21600 => '((a 1 3) (b 2))
21602 merge (a 1) and (a 3) into (a 1 3) and return the new alist."
21603 (let (rtn)
21604 (mapc
21605 (lambda (e)
21606 (let (n)
21607 (if (not (assoc (car e) rtn))
21608 (push e rtn)
21609 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21610 (setq rtn (assq-delete-all (car e) rtn))
21611 (push n rtn))))
21612 alist)
21613 rtn))
21615 (defun org-delete-all (elts list)
21616 "Remove all elements in ELTS from LIST."
21617 (while elts
21618 (setq list (delete (pop elts) list)))
21619 list)
21621 (defun org-count (cl-item cl-seq)
21622 "Count the number of occurrences of ITEM in SEQ.
21623 Taken from `count' in cl-seq.el with all keyword arguments removed."
21624 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21625 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21626 (while (< cl-start cl-end)
21627 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21628 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21629 (setq cl-start (1+ cl-start)))
21630 cl-count))
21632 (defun org-remove-if (predicate seq)
21633 "Remove everything from SEQ that fulfills PREDICATE."
21634 (let (res e)
21635 (while seq
21636 (setq e (pop seq))
21637 (if (not (funcall predicate e)) (push e res)))
21638 (nreverse res)))
21640 (defun org-remove-if-not (predicate seq)
21641 "Remove everything from SEQ that does not fulfill PREDICATE."
21642 (let (res e)
21643 (while seq
21644 (setq e (pop seq))
21645 (if (funcall predicate e) (push e res)))
21646 (nreverse res)))
21648 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21649 "Reduce two-argument FUNCTION across SEQ.
21650 Taken from `reduce' in cl-seq.el with all keyword arguments but
21651 \":initial-value\" removed."
21652 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21653 (cadr (memq :initial-value cl-keys)))
21654 (cl-seq (pop cl-seq))
21655 (t (funcall cl-func)))))
21656 (while cl-seq
21657 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21658 cl-accum))
21660 (defun org-back-over-empty-lines ()
21661 "Move backwards over whitespace, to the beginning of the first empty line.
21662 Returns the number of empty lines passed."
21663 (let ((pos (point)))
21664 (if (cdr (assoc 'heading org-blank-before-new-entry))
21665 (skip-chars-backward " \t\n\r")
21666 (unless (eobp)
21667 (forward-line -1)))
21668 (beginning-of-line 2)
21669 (goto-char (min (point) pos))
21670 (count-lines (point) pos)))
21672 (defun org-skip-whitespace ()
21673 (skip-chars-forward " \t\n\r"))
21675 (defun org-point-in-group (point group &optional context)
21676 "Check if POINT is in match-group GROUP.
21677 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21678 match. If the match group does not exist or point is not inside it,
21679 return nil."
21680 (and (match-beginning group)
21681 (>= point (match-beginning group))
21682 (<= point (match-end group))
21683 (if context
21684 (list context (match-beginning group) (match-end group))
21685 t)))
21687 (defun org-switch-to-buffer-other-window (&rest args)
21688 "Switch to buffer in a second window on the current frame.
21689 In particular, do not allow pop-up frames.
21690 Returns the newly created buffer."
21691 (org-no-popups
21692 (apply 'switch-to-buffer-other-window args)))
21694 (defun org-combine-plists (&rest plists)
21695 "Create a single property list from all plists in PLISTS.
21696 The process starts by copying the first list, and then setting properties
21697 from the other lists. Settings in the last list are the most significant
21698 ones and overrule settings in the other lists."
21699 (let ((rtn (copy-sequence (pop plists)))
21700 p v ls)
21701 (while plists
21702 (setq ls (pop plists))
21703 (while ls
21704 (setq p (pop ls) v (pop ls))
21705 (setq rtn (plist-put rtn p v))))
21706 rtn))
21708 (defun org-replace-escapes (string table)
21709 "Replace %-escapes in STRING with values in TABLE.
21710 TABLE is an association list with keys like \"%a\" and string values.
21711 The sequences in STRING may contain normal field width and padding information,
21712 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21713 so values can contain further %-escapes if they are define later in TABLE."
21714 (let ((tbl (copy-alist table))
21715 (case-fold-search nil)
21716 (pchg 0)
21717 e re rpl)
21718 (while (setq e (pop tbl))
21719 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21720 (when (and (cdr e) (string-match re (cdr e)))
21721 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21722 (safe "SREF"))
21723 (add-text-properties 0 3 (list 'sref sref) safe)
21724 (setcdr e (replace-match safe t t (cdr e)))))
21725 (while (string-match re string)
21726 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21727 (cdr e)))
21728 (setq string (replace-match rpl t t string))))
21729 (while (setq pchg (next-property-change pchg string))
21730 (let ((sref (get-text-property pchg 'sref string)))
21731 (when (and sref (string-match "SREF" string pchg))
21732 (setq string (replace-match sref t t string)))))
21733 string))
21735 (defun org-sublist (list start end)
21736 "Return a section of LIST, from START to END.
21737 Counting starts at 1."
21738 (let (rtn (c start))
21739 (setq list (nthcdr (1- start) list))
21740 (while (and list (<= c end))
21741 (push (pop list) rtn)
21742 (setq c (1+ c)))
21743 (nreverse rtn)))
21745 (defun org-find-base-buffer-visiting (file)
21746 "Like `find-buffer-visiting' but always return the base buffer and
21747 not an indirect buffer."
21748 (let ((buf (or (get-file-buffer file)
21749 (find-buffer-visiting file))))
21750 (if buf
21751 (or (buffer-base-buffer buf) buf)
21752 nil)))
21754 (defun org-image-file-name-regexp (&optional extensions)
21755 "Return regexp matching the file names of images.
21756 If EXTENSIONS is given, only match these."
21757 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21758 (image-file-name-regexp)
21759 (let ((image-file-name-extensions
21760 (or extensions
21761 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21762 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21763 (concat "\\."
21764 (regexp-opt (nconc (mapcar 'upcase
21765 image-file-name-extensions)
21766 image-file-name-extensions)
21768 "\\'"))))
21770 (defun org-file-image-p (file &optional extensions)
21771 "Return non-nil if FILE is an image."
21772 (save-match-data
21773 (string-match (org-image-file-name-regexp extensions) file)))
21775 (defun org-get-cursor-date (&optional with-time)
21776 "Return the date at cursor in as a time.
21777 This works in the calendar and in the agenda, anywhere else it just
21778 returns the current time.
21779 If WITH-TIME is non-nil, returns the time of the event at point (in
21780 the agenda) or the current time of the day."
21781 (let (date day defd tp tm hod mod)
21782 (when with-time
21783 (setq tp (get-text-property (point) 'time))
21784 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21785 (setq hod (string-to-number (match-string 1 tp))
21786 mod (string-to-number (match-string 2 tp))))
21787 (or tp (setq hod (nth 2 (decode-time (current-time)))
21788 mod (nth 1 (decode-time (current-time))))))
21789 (cond
21790 ((eq major-mode 'calendar-mode)
21791 (setq date (calendar-cursor-to-date)
21792 defd (encode-time 0 (or mod 0) (or hod 0)
21793 (nth 1 date) (nth 0 date) (nth 2 date))))
21794 ((eq major-mode 'org-agenda-mode)
21795 (setq day (get-text-property (point) 'day))
21796 (if day
21797 (setq date (calendar-gregorian-from-absolute day)
21798 defd (encode-time 0 (or mod 0) (or hod 0)
21799 (nth 1 date) (nth 0 date) (nth 2 date))))))
21800 (or defd (current-time))))
21802 (defun org-mark-subtree (&optional up)
21803 "Mark the current subtree.
21804 This puts point at the start of the current subtree, and mark at
21805 the end. If a numeric prefix UP is given, move up into the
21806 hierarchy of headlines by UP levels before marking the subtree."
21807 (interactive "P")
21808 (org-with-limited-levels
21809 (cond ((org-at-heading-p) (beginning-of-line))
21810 ((org-before-first-heading-p) (error "Not in a subtree"))
21811 (t (outline-previous-visible-heading 1))))
21812 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21813 (if (org-called-interactively-p 'any)
21814 (call-interactively 'org-mark-element)
21815 (org-mark-element)))
21818 ;;; Indentation
21820 (defun org-indent-line ()
21821 "Indent line depending on context."
21822 (interactive)
21823 (let* ((pos (point))
21824 (itemp (org-at-item-p))
21825 (case-fold-search t)
21826 (org-drawer-regexp (or org-drawer-regexp "\000"))
21827 (inline-task-p (and (featurep 'org-inlinetask)
21828 (org-inlinetask-in-task-p)))
21829 (inline-re (and inline-task-p
21830 (org-inlinetask-outline-regexp)))
21831 column)
21832 (if (and orgstruct-is-++ (eq pos (point)))
21833 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21834 (indent-according-to-mode))
21835 (beginning-of-line 1)
21836 (cond
21837 ;; Headings
21838 ((looking-at org-outline-regexp) (setq column 0))
21839 ;; Footnote definition
21840 ((looking-at org-footnote-definition-re) (setq column 0))
21841 ;; Literal examples
21842 ((looking-at "[ \t]*:\\( \\|$\\)")
21843 (setq column (org-get-indentation))) ; do nothing
21844 ;; Lists
21845 ((ignore-errors (goto-char (org-in-item-p)))
21846 (setq column (if itemp
21847 (org-get-indentation)
21848 (org-list-item-body-column (point))))
21849 (goto-char pos))
21850 ;; Drawers
21851 ((and (looking-at "[ \t]*:END:")
21852 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21853 (save-excursion
21854 (goto-char (1- (match-beginning 1)))
21855 (setq column (current-column))))
21856 ;; Special blocks
21857 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21858 (save-excursion
21859 (re-search-backward
21860 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21861 (setq column (org-get-indentation (match-string 0))))
21862 ((and (not (looking-at "[ \t]*#\\+begin_"))
21863 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21864 (save-excursion
21865 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21866 (setq column
21867 (cond ((equal (downcase (match-string 1)) "src")
21868 ;; src blocks: let `org-edit-src-exit' handle them
21869 (org-get-indentation))
21870 ((equal (downcase (match-string 1)) "example")
21871 (max (org-get-indentation)
21872 (org-get-indentation (match-string 0))))
21874 (org-get-indentation (match-string 0))))))
21875 ;; This line has nothing special, look at the previous relevant
21876 ;; line to compute indentation
21878 (beginning-of-line 0)
21879 (while (and (not (bobp))
21880 (not (looking-at org-table-line-regexp))
21881 (not (looking-at org-drawer-regexp))
21882 ;; When point started in an inline task, do not move
21883 ;; above task starting line.
21884 (not (and inline-task-p (looking-at inline-re)))
21885 ;; Skip drawers, blocks, empty lines, verbatim,
21886 ;; comments, tables, footnotes definitions, lists,
21887 ;; inline tasks.
21888 (or (and (looking-at "[ \t]*:END:")
21889 (re-search-backward org-drawer-regexp nil t))
21890 (and (looking-at "[ \t]*#\\+end_")
21891 (re-search-backward "[ \t]*#\\+begin_"nil t))
21892 (looking-at "[ \t]*[\n:#|]")
21893 (looking-at org-footnote-definition-re)
21894 (and (not inline-task-p)
21895 (featurep 'org-inlinetask)
21896 (org-inlinetask-in-task-p)
21897 (or (org-inlinetask-goto-beginning) t))))
21898 (beginning-of-line 0))
21899 (cond
21900 ;; There was a list item above.
21901 ((save-excursion
21902 (and (ignore-errors (goto-char (org-in-item-p)))
21903 (goto-char
21904 (org-list-get-top-point (org-list-struct)))))
21905 (looking-at org-list-full-item-re)
21906 (setq column (length (match-string 0))))
21907 ;; There was an heading above.
21908 ((looking-at "\\*+[ \t]+")
21909 (if (not org-adapt-indentation)
21910 (setq column 0)
21911 (goto-char (match-end 0))
21912 (setq column (current-column))))
21913 ;; A drawer had started and is unfinished
21914 ((looking-at org-drawer-regexp)
21915 (goto-char (1- (match-beginning 1)))
21916 (setq column (current-column)))
21917 ;; Else, nothing noticeable found: get indentation and go on.
21918 (t (setq column (org-get-indentation))))))
21919 ;; Now apply indentation and move cursor accordingly
21920 (goto-char pos)
21921 (if (<= (current-column) (current-indentation))
21922 (org-indent-line-to column)
21923 (save-excursion (org-indent-line-to column)))
21924 ;; Special polishing for properties, see `org-property-format'
21925 (setq column (current-column))
21926 (beginning-of-line 1)
21927 (if (looking-at
21928 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21929 (replace-match (concat (match-string 1)
21930 (format org-property-format
21931 (match-string 2) (match-string 3)))
21932 t t))
21933 (org-move-to-column column))))
21935 (defun org-indent-drawer ()
21936 "Indent the drawer at point."
21937 (interactive)
21938 (let ((p (point))
21939 (e (and (save-excursion (re-search-forward ":END:" nil t))
21940 (match-end 0)))
21941 (folded
21942 (save-excursion
21943 (end-of-line)
21944 (when (overlays-at (point))
21945 (member 'invisible (overlay-properties
21946 (car (overlays-at (point)))))))))
21947 (when folded (org-cycle))
21948 (indent-for-tab-command)
21949 (while (and (move-beginning-of-line 2) (< (point) e))
21950 (indent-for-tab-command))
21951 (goto-char p)
21952 (when folded (org-cycle)))
21953 (message "Drawer at point indented"))
21955 (defun org-indent-block ()
21956 "Indent the block at point."
21957 (interactive)
21958 (let ((p (point))
21959 (case-fold-search t)
21960 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21961 (match-end 0)))
21962 (folded
21963 (save-excursion
21964 (end-of-line)
21965 (when (overlays-at (point))
21966 (member 'invisible (overlay-properties
21967 (car (overlays-at (point)))))))))
21968 (when folded (org-cycle))
21969 (indent-for-tab-command)
21970 (while (and (move-beginning-of-line 2) (< (point) e))
21971 (indent-for-tab-command))
21972 (goto-char p)
21973 (when folded (org-cycle)))
21974 (message "Block at point indented"))
21976 (defun org-indent-region (start end)
21977 "Indent region."
21978 (interactive "r")
21979 (save-excursion
21980 (let ((line-end (org-current-line end)))
21981 (goto-char start)
21982 (while (< (org-current-line) line-end)
21983 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21984 (t (call-interactively 'org-indent-line)))
21985 (move-beginning-of-line 2)))))
21988 ;;; Filling
21990 ;; We use our own fill-paragraph and auto-fill functions.
21992 ;; `org-fill-paragraph' relies on adaptive filling and context
21993 ;; checking. Appropriate `fill-prefix' is computed with
21994 ;; `org-adaptive-fill-function'.
21996 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21997 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21998 ;; `org-adaptive-fill-function' value. Internally,
21999 ;; `org-comment-line-break-function' breaks the line.
22001 ;; `org-setup-filling' installs filling and auto-filling related
22002 ;; variables during `org-mode' initialization.
22004 (defun org-setup-filling ()
22005 (interactive)
22006 ;; Prevent auto-fill from inserting unwanted new items.
22007 (when (boundp 'fill-nobreak-predicate)
22008 (org-set-local
22009 'fill-nobreak-predicate
22010 (org-uniquify
22011 (append fill-nobreak-predicate
22012 '(org-fill-paragraph-separate-nobreak-p
22013 org-fill-line-break-nobreak-p
22014 org-fill-paragraph-with-timestamp-nobreak-p)))))
22015 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22016 (org-set-local 'auto-fill-inhibit-regexp nil)
22017 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22018 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22019 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22021 (defvar org-element-paragraph-separate) ; org-element.el
22022 (defun org-fill-paragraph-separate-nobreak-p ()
22023 "Non-nil when a line break at point would insert a new item."
22024 (looking-at (substring org-element-paragraph-separate 1)))
22026 (defun org-fill-line-break-nobreak-p ()
22027 "Non-nil when a line break at point would create an Org line break."
22028 (save-excursion
22029 (skip-chars-backward "[ \t]")
22030 (skip-chars-backward "\\\\")
22031 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22033 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22034 "Non-nil when a line break at point would insert a new item."
22035 (and (org-at-timestamp-p t)
22036 (not (looking-at org-ts-regexp-both))))
22038 (declare-function message-in-body-p "message" ())
22039 (defvar orgtbl-line-start-regexp) ; From org-table.el
22040 (defun org-adaptive-fill-function ()
22041 "Compute a fill prefix for the current line.
22042 Return fill prefix, as a string, or nil if current line isn't
22043 meant to be filled."
22044 (let (prefix)
22045 (catch 'exit
22046 (when (derived-mode-p 'message-mode)
22047 (save-excursion
22048 (beginning-of-line)
22049 (cond ((or (not (message-in-body-p))
22050 (looking-at orgtbl-line-start-regexp))
22051 (throw 'exit nil))
22052 ((looking-at message-cite-prefix-regexp)
22053 (throw 'exit (match-string-no-properties 0)))
22054 ((looking-at org-outline-regexp)
22055 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22056 (org-with-wide-buffer
22057 (let* ((p (line-beginning-position))
22058 (element (save-excursion (beginning-of-line)
22059 (org-element-at-point)))
22060 (type (org-element-type element))
22061 (post-affiliated (org-element-property :post-affiliated element)))
22062 (unless (and post-affiliated (< p post-affiliated))
22063 (case type
22064 (comment (looking-at "[ \t]*# ?") (match-string 0))
22065 (footnote-definition "")
22066 ((item plain-list)
22067 (make-string (org-list-item-body-column
22068 (or post-affiliated
22069 (org-element-property :begin element)))
22070 ? ))
22071 (paragraph
22072 ;; Fill prefix is usually the same as the current line,
22073 ;; except if the paragraph is at the beginning of an item.
22074 (let ((parent (org-element-property :parent element)))
22075 (cond ((eq (org-element-type parent) 'item)
22076 (make-string (org-list-item-body-column
22077 (org-element-property :begin parent))
22078 ? ))
22079 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22080 (match-string 0))
22081 (t ""))))
22082 (comment-block
22083 ;; Only fill contents if P is within block boundaries.
22084 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22085 (forward-line)
22086 (point)))
22087 (cend (save-excursion
22088 (goto-char (org-element-property :end element))
22089 (skip-chars-backward " \r\t\n")
22090 (line-beginning-position))))
22091 (when (and (>= p cbeg) (< p cend))
22092 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22093 (match-string 0)
22094 "")))))))))))
22096 (declare-function message-goto-body "message" ())
22097 (defvar message-cite-prefix-regexp) ; From message.el
22098 (defun org-fill-paragraph (&optional justify)
22099 "Fill element at point, when applicable.
22101 This function only applies to comment blocks, comments, example
22102 blocks and paragraphs. Also, as a special case, re-align table
22103 when point is at one.
22105 If JUSTIFY is non-nil (interactively, with prefix argument),
22106 justify as well. If `sentence-end-double-space' is non-nil, then
22107 period followed by one space does not end a sentence, so don't
22108 break a line there. The variable `fill-column' controls the
22109 width for filling.
22111 For convenience, when point is at a plain list, an item or
22112 a footnote definition, try to fill the first paragraph within."
22113 (interactive)
22114 (if (and (derived-mode-p 'message-mode)
22115 (or (not (message-in-body-p))
22116 (save-excursion (move-beginning-of-line 1)
22117 (looking-at message-cite-prefix-regexp))))
22118 ;; First ensure filling is correct in message-mode.
22119 (let ((fill-paragraph-function
22120 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22121 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22122 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22123 (paragraph-separate
22124 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22125 (fill-paragraph nil))
22126 (with-syntax-table org-mode-transpose-word-syntax-table
22127 ;; Move to end of line in order to get the first paragraph
22128 ;; within a plain list or a footnote definition.
22129 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22130 ;; First check if point is in a blank line at the beginning of
22131 ;; the buffer. In that case, ignore filling.
22132 (case (org-element-type element)
22133 ;; Use major mode filling function is src blocks.
22134 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22135 ;; Align Org tables, leave table.el tables as-is.
22136 (table-row (org-table-align) t)
22137 (table
22138 (when (eq (org-element-property :type element) 'org)
22139 (org-table-align))
22141 (paragraph
22142 ;; Paragraphs may contain `line-break' type objects.
22143 (let ((beg (max (point-min)
22144 (org-element-property :contents-begin element)))
22145 (end (min (point-max)
22146 (org-element-property :contents-end element))))
22147 ;; Do nothing if point is at an affiliated keyword.
22148 (if (< (line-end-position) beg) t
22149 (when (derived-mode-p 'message-mode)
22150 ;; In `message-mode', do not fill following citation
22151 ;; in current paragraph nor text before message body.
22152 (let ((body-start (save-excursion (message-goto-body))))
22153 (when body-start (setq beg (max body-start beg))))
22154 (when (save-excursion
22155 (re-search-forward
22156 (concat "^" message-cite-prefix-regexp) end t))
22157 (setq end (match-beginning 0))))
22158 ;; Fill paragraph, taking line breaks into account.
22159 ;; For that, slice the paragraph using line breaks as
22160 ;; separators, and fill the parts in reverse order to
22161 ;; avoid messing with markers.
22162 (save-excursion
22163 (goto-char end)
22164 (mapc
22165 (lambda (pos)
22166 (fill-region-as-paragraph pos (point) justify)
22167 (goto-char pos))
22168 ;; Find the list of ending positions for line breaks
22169 ;; in the current paragraph. Add paragraph
22170 ;; beginning to include first slice.
22171 (nreverse
22172 (cons beg
22173 (org-element-map
22174 (org-element--parse-objects
22175 beg end nil (org-element-restriction 'paragraph))
22176 'line-break
22177 (lambda (lb) (org-element-property :end lb)))))))
22178 t)))
22179 ;; Contents of `comment-block' type elements should be
22180 ;; filled as plain text, but only if point is within block
22181 ;; markers.
22182 (comment-block
22183 (let* ((case-fold-search t)
22184 (beg (save-excursion
22185 (goto-char (org-element-property :begin element))
22186 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22187 (forward-line)
22188 (point)))
22189 (end (save-excursion
22190 (goto-char (org-element-property :end element))
22191 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22192 (line-beginning-position))))
22193 (when (and (>= (point) beg) (< (point) end))
22194 (fill-region-as-paragraph
22195 (save-excursion
22196 (end-of-line)
22197 (re-search-backward "^[ \t]*$" beg 'move)
22198 (line-beginning-position))
22199 (save-excursion
22200 (beginning-of-line)
22201 (re-search-forward "^[ \t]*$" end 'move)
22202 (line-beginning-position))
22203 justify)))
22205 ;; Fill comments.
22206 (comment (fill-comment-paragraph justify))
22207 ;; Ignore every other element.
22208 (otherwise t))))))
22210 (defun org-auto-fill-function ()
22211 "Auto-fill function."
22212 ;; Check if auto-filling is meaningful.
22213 (let ((fc (current-fill-column)))
22214 (when (and fc (> (current-column) fc))
22215 (let* ((fill-prefix (org-adaptive-fill-function))
22216 ;; Enforce empty fill prefix, if required. Otherwise, it
22217 ;; will be computed again.
22218 (adaptive-fill-mode (not (equal fill-prefix ""))))
22219 (when fill-prefix (do-auto-fill))))))
22221 (defun org-comment-line-break-function (&optional soft)
22222 "Break line at point and indent, continuing comment if within one.
22223 The inserted newline is marked hard if variable
22224 `use-hard-newlines' is true, unless optional argument SOFT is
22225 non-nil."
22226 (if soft (insert-and-inherit ?\n) (newline 1))
22227 (save-excursion (forward-char -1) (delete-horizontal-space))
22228 (delete-horizontal-space)
22229 (indent-to-left-margin)
22230 (insert-before-markers-and-inherit fill-prefix))
22233 ;;; Comments
22235 ;; Org comments syntax is quite complex. It requires the entire line
22236 ;; to be just a comment. Also, even with the right syntax at the
22237 ;; beginning of line, some some elements (i.e. verse-block or
22238 ;; example-block) don't accept comments. Usual Emacs comment commands
22239 ;; cannot cope with those requirements. Therefore, Org replaces them.
22241 ;; Org still relies on `comment-dwim', but cannot trust
22242 ;; `comment-only-p'. So, `comment-region-function' and
22243 ;; `uncomment-region-function' both point
22244 ;; to`org-comment-or-uncomment-region'. Eventually,
22245 ;; `org-insert-comment' takes care of insertion of comments at the
22246 ;; beginning of line.
22248 ;; `org-setup-comments-handling' install comments related variables
22249 ;; during `org-mode' initialization.
22251 (defun org-setup-comments-handling ()
22252 (interactive)
22253 (org-set-local 'comment-use-syntax nil)
22254 (org-set-local 'comment-start "# ")
22255 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22256 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22257 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22258 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22260 (defun org-insert-comment ()
22261 "Insert an empty comment above current line.
22262 If the line is empty, insert comment at its beginning."
22263 (beginning-of-line)
22264 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22265 (org-indent-line)
22266 (insert "# "))
22268 (defvar comment-empty-lines) ; From newcomment.el.
22269 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22270 "Comment or uncomment each non-blank line in the region.
22271 Uncomment each non-blank line between BEG and END if it only
22272 contains commented lines. Otherwise, comment them."
22273 (save-restriction
22274 ;; Restrict region
22275 (narrow-to-region (save-excursion (goto-char beg)
22276 (skip-chars-forward " \r\t\n" end)
22277 (line-beginning-position))
22278 (save-excursion (goto-char end)
22279 (skip-chars-backward " \r\t\n" beg)
22280 (line-end-position)))
22281 (let ((uncommentp
22282 ;; UNCOMMENTP is non-nil when every non blank line between
22283 ;; BEG and END is a comment.
22284 (save-excursion
22285 (goto-char (point-min))
22286 (while (and (not (eobp))
22287 (let ((element (org-element-at-point)))
22288 (and (eq (org-element-type element) 'comment)
22289 (goto-char (min (point-max)
22290 (org-element-property
22291 :end element)))))))
22292 (eobp))))
22293 (if uncommentp
22294 ;; Only blank lines and comments in region: uncomment it.
22295 (save-excursion
22296 (goto-char (point-min))
22297 (while (not (eobp))
22298 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22299 (replace-match "" nil nil nil 1))
22300 (forward-line)))
22301 ;; Comment each line in region.
22302 (let ((min-indent (point-max)))
22303 ;; First find the minimum indentation across all lines.
22304 (save-excursion
22305 (goto-char (point-min))
22306 (while (and (not (eobp)) (not (zerop min-indent)))
22307 (unless (looking-at "[ \t]*$")
22308 (setq min-indent (min min-indent (current-indentation))))
22309 (forward-line)))
22310 ;; Then loop over all lines.
22311 (save-excursion
22312 (goto-char (point-min))
22313 (while (not (eobp))
22314 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22315 ;; Don't get fooled by invisible text (e.g. link path)
22316 ;; when moving to column MIN-INDENT.
22317 (let ((buffer-invisibility-spec nil))
22318 (org-move-to-column min-indent t))
22319 (insert comment-start))
22320 (forward-line))))))))
22323 ;;; Planning
22325 ;; This section contains tools to operate on timestamp objects, as
22326 ;; returned by, e.g. `org-element-context'.
22328 (defun org-timestamp-has-time-p (timestamp)
22329 "Non-nil when TIMESTAMP has a time specified."
22330 (org-element-property :hour-start timestamp))
22332 (defun org-timestamp-format (timestamp format &optional end utc)
22333 "Format a TIMESTAMP element into a string.
22335 FORMAT is a format specifier to be passed to
22336 `format-time-string'.
22338 When optional argument END is non-nil, use end of date-range or
22339 time-range, if possible.
22341 When optional argument UTC is non-nil, time will be expressed as
22342 Universal Time."
22343 (format-time-string
22344 format
22345 (apply 'encode-time
22346 (cons 0
22347 (mapcar
22348 (lambda (prop) (or (org-element-property prop timestamp) 0))
22349 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22350 '(:minute-start :hour-start :day-start :month-start
22351 :year-start)))))
22352 utc))
22354 (defun org-timestamp-split-range (timestamp &optional end)
22355 "Extract a timestamp object from a date or time range.
22357 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22358 the end of the range. Otherwise, extract its start.
22360 Return a new timestamp object sharing the same parent as
22361 TIMESTAMP."
22362 (let ((type (org-element-property :type timestamp)))
22363 (if (memq type '(active inactive diary)) timestamp
22364 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22365 ;; Set new type.
22366 (org-element-put-property
22367 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22368 ;; Copy start properties over end properties if END is
22369 ;; non-nil. Otherwise, copy end properties over `start' ones.
22370 (let ((p-alist '((:minute-start . :minute-end)
22371 (:hour-start . :hour-end)
22372 (:day-start . :day-end)
22373 (:month-start . :month-end)
22374 (:year-start . :year-end))))
22375 (dolist (p-cell p-alist)
22376 (org-element-put-property
22377 split-ts
22378 (funcall (if end 'car 'cdr) p-cell)
22379 (org-element-property
22380 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22381 ;; Eventually refresh `:raw-value'.
22382 (org-element-put-property split-ts :raw-value nil)
22383 (org-element-put-property
22384 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22386 (defun org-timestamp-translate (timestamp &optional boundary)
22387 "Apply `org-translate-time' on a TIMESTAMP object.
22388 When optional argument BOUNDARY is non-nil, it is either the
22389 symbol `start' or `end'. In this case, only translate the
22390 starting or ending part of TIMESTAMP if it is a date or time
22391 range. Otherwise, translate both parts."
22392 (if (and (not boundary)
22393 (memq (org-element-property :type timestamp)
22394 '(active-range inactive-range)))
22395 (concat
22396 (org-translate-time
22397 (org-element-property :raw-value
22398 (org-timestamp-split-range timestamp)))
22399 "--"
22400 (org-translate-time
22401 (org-element-property :raw-value
22402 (org-timestamp-split-range timestamp t))))
22403 (org-translate-time
22404 (org-element-property
22405 :raw-value
22406 (if (not boundary) timestamp
22407 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22411 ;;; Other stuff.
22413 (defun org-toggle-fixed-width-section (arg)
22414 "Toggle the fixed-width export.
22415 If there is no active region, the QUOTE keyword at the current headline is
22416 inserted or removed. When present, it causes the text between this headline
22417 and the next to be exported as fixed-width text, and unmodified.
22418 If there is an active region, this command adds or removes a colon as the
22419 first character of this line. If the first character of a line is a colon,
22420 this line is also exported in fixed-width font."
22421 (interactive "P")
22422 (let* ((cc 0)
22423 (regionp (org-region-active-p))
22424 (beg (if regionp (region-beginning) (point)))
22425 (end (if regionp (region-end)))
22426 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22427 (case-fold-search nil)
22428 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22429 off)
22430 (if regionp
22431 (save-excursion
22432 (goto-char beg)
22433 (setq cc (current-column))
22434 (beginning-of-line 1)
22435 (setq off (looking-at re))
22436 (while (> nlines 0)
22437 (setq nlines (1- nlines))
22438 (beginning-of-line 1)
22439 (cond
22440 (arg
22441 (org-move-to-column cc t)
22442 (insert ": \n")
22443 (forward-line -1))
22444 ((and off (looking-at re))
22445 (replace-match "" t t nil 1))
22446 ((not off) (org-move-to-column cc t) (insert ": ")))
22447 (forward-line 1)))
22448 (save-excursion
22449 (org-back-to-heading)
22450 (cond
22451 ((looking-at (format org-heading-keyword-regexp-format
22452 org-quote-string))
22453 (goto-char (match-end 1))
22454 (looking-at (concat " +" org-quote-string))
22455 (replace-match "" t t)
22456 (when (eolp) (insert " ")))
22457 ((looking-at org-outline-regexp)
22458 (goto-char (match-end 0))
22459 (insert org-quote-string " ")))))))
22461 (defun org-reftex-citation ()
22462 "Use reftex-citation to insert a citation into the buffer.
22463 This looks for a line like
22465 #+BIBLIOGRAPHY: foo plain option:-d
22467 and derives from it that foo.bib is the bibliography file relevant
22468 for this document. It then installs the necessary environment for RefTeX
22469 to work in this buffer and calls `reftex-citation' to insert a citation
22470 into the buffer.
22472 Export of such citations to both LaTeX and HTML is handled by the contributed
22473 package org-exp-bibtex by Taru Karttunen."
22474 (interactive)
22475 (let ((reftex-docstruct-symbol 'rds)
22476 (reftex-cite-format "\\cite{%l}")
22477 rds bib)
22478 (save-excursion
22479 (save-restriction
22480 (widen)
22481 (let ((case-fold-search t)
22482 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22483 (if (not (save-excursion
22484 (or (re-search-forward re nil t)
22485 (re-search-backward re nil t))))
22486 (error "No bibliography defined in file")
22487 (setq bib (concat (match-string 1) ".bib")
22488 rds (list (list 'bib bib)))))))
22489 (call-interactively 'reftex-citation)))
22491 ;;;; Functions extending outline functionality
22493 (defun org-beginning-of-line (&optional arg)
22494 "Go to the beginning of the current line. If that is invisible, continue
22495 to a visible line beginning. This makes the function of C-a more intuitive.
22496 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22497 first attempt, and only move to after the tags when the cursor is already
22498 beyond the end of the headline."
22499 (interactive "P")
22500 (let ((pos (point))
22501 (special (if (consp org-special-ctrl-a/e)
22502 (car org-special-ctrl-a/e)
22503 org-special-ctrl-a/e))
22504 refpos)
22505 (if (org-bound-and-true-p visual-line-mode)
22506 (beginning-of-visual-line 1)
22507 (beginning-of-line 1))
22508 (if (and arg (fboundp 'move-beginning-of-line))
22509 (call-interactively 'move-beginning-of-line)
22510 (if (bobp)
22512 (backward-char 1)
22513 (if (org-truely-invisible-p)
22514 (while (and (not (bobp)) (org-truely-invisible-p))
22515 (backward-char 1)
22516 (beginning-of-line 1))
22517 (forward-char 1))))
22518 (when special
22519 (cond
22520 ((and (looking-at org-complex-heading-regexp)
22521 (= (char-after (match-end 1)) ?\ ))
22522 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22523 (point-at-eol)))
22524 (goto-char
22525 (if (eq special t)
22526 (cond ((> pos refpos) refpos)
22527 ((= pos (point)) refpos)
22528 (t (point)))
22529 (cond ((> pos (point)) (point))
22530 ((not (eq last-command this-command)) (point))
22531 (t refpos)))))
22532 ((org-at-item-p)
22533 ;; Being at an item and not looking at an the item means point
22534 ;; was previously moved to beginning of a visual line, which
22535 ;; doesn't contain the item. Therefore, do nothing special,
22536 ;; just stay here.
22537 (when (looking-at org-list-full-item-re)
22538 ;; Set special position at first white space character after
22539 ;; bullet, and check-box, if any.
22540 (let ((after-bullet
22541 (let ((box (match-end 3)))
22542 (if (not box) (match-end 1)
22543 (let ((after (char-after box)))
22544 (if (and after (= after ? )) (1+ box) box))))))
22545 ;; Special case: Move point to special position when
22546 ;; currently after it or at beginning of line.
22547 (if (eq special t)
22548 (when (or (> pos after-bullet) (= (point) pos))
22549 (goto-char after-bullet))
22550 ;; Reversed case: Move point to special position when
22551 ;; point was already at beginning of line and command is
22552 ;; repeated.
22553 (when (and (= (point) pos) (eq last-command this-command))
22554 (goto-char after-bullet))))))))
22555 (org-no-warnings
22556 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22558 (defun org-end-of-line (&optional arg)
22559 "Go to the end of the line.
22560 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22561 tags on the first attempt, and only move to after the tags when
22562 the cursor is already beyond the end of the headline."
22563 (interactive "P")
22564 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22565 org-special-ctrl-a/e))
22566 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22567 'end-of-visual-line)
22568 ((fboundp 'move-end-of-line) 'move-end-of-line)
22569 (t 'end-of-line))))
22570 (if (or (not special) arg) (call-interactively move-fun)
22571 (let* ((element (save-excursion (beginning-of-line)
22572 (org-element-at-point)))
22573 (type (org-element-type element)))
22574 (cond
22575 ((memq type '(headline inlinetask))
22576 (let ((pos (point)))
22577 (beginning-of-line 1)
22578 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22579 (if (eq special t)
22580 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22581 (goto-char (match-beginning 1))
22582 (goto-char (match-end 0)))
22583 (if (or (< pos (match-end 0))
22584 (not (eq this-command last-command)))
22585 (goto-char (match-end 0))
22586 (goto-char (match-beginning 1))))
22587 (call-interactively move-fun))))
22588 ((org-element-property :hiddenp element)
22589 ;; If element is hidden, `move-end-of-line' would put point
22590 ;; after it. Use `end-of-line' to stay on current line.
22591 (call-interactively 'end-of-line))
22592 (t (call-interactively move-fun)))))
22593 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22595 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22596 (define-key org-mode-map "\C-e" 'org-end-of-line)
22598 (defun org-backward-sentence (&optional arg)
22599 "Go to beginning of sentence, or beginning of table field.
22600 This will call `backward-sentence' or `org-table-beginning-of-field',
22601 depending on context."
22602 (interactive "P")
22603 (cond
22604 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22605 (t (call-interactively 'backward-sentence))))
22607 (defun org-forward-sentence (&optional arg)
22608 "Go to end of sentence, or end of table field.
22609 This will call `forward-sentence' or `org-table-end-of-field',
22610 depending on context."
22611 (interactive "P")
22612 (cond
22613 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22614 (t (call-interactively 'forward-sentence))))
22616 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22617 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22619 (defun org-kill-line (&optional arg)
22620 "Kill line, to tags or end of line."
22621 (interactive "P")
22622 (cond
22623 ((or (not org-special-ctrl-k)
22624 (bolp)
22625 (not (org-at-heading-p)))
22626 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22627 org-ctrl-k-protect-subtree)
22628 (if (or (eq org-ctrl-k-protect-subtree 'error)
22629 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22630 (error "C-k aborted - would kill hidden subtree")))
22631 (call-interactively
22632 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22633 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22634 (kill-region (point) (match-beginning 1))
22635 (org-set-tags nil t))
22636 (t (kill-region (point) (point-at-eol)))))
22638 (define-key org-mode-map "\C-k" 'org-kill-line)
22640 (defun org-yank (&optional arg)
22641 "Yank. If the kill is a subtree, treat it specially.
22642 This command will look at the current kill and check if is a single
22643 subtree, or a series of subtrees[1]. If it passes the test, and if the
22644 cursor is at the beginning of a line or after the stars of a currently
22645 empty headline, then the yank is handled specially. How exactly depends
22646 on the value of the following variables, both set by default.
22648 org-yank-folded-subtrees
22649 When set, the subtree(s) will be folded after insertion, but only
22650 if doing so would now swallow text after the yanked text.
22652 org-yank-adjusted-subtrees
22653 When set, the subtree will be promoted or demoted in order to
22654 fit into the local outline tree structure, which means that the level
22655 will be adjusted so that it becomes the smaller one of the two
22656 *visible* surrounding headings.
22658 Any prefix to this command will cause `yank' to be called directly with
22659 no special treatment. In particular, a simple \\[universal-argument] prefix \
22660 will just
22661 plainly yank the text as it is.
22663 \[1] The test checks if the first non-white line is a heading
22664 and if there are no other headings with fewer stars."
22665 (interactive "P")
22666 (org-yank-generic 'yank arg))
22668 (defun org-yank-generic (command arg)
22669 "Perform some yank-like command.
22671 This function implements the behavior described in the `org-yank'
22672 documentation. However, it has been generalized to work for any
22673 interactive command with similar behavior."
22675 ;; pretend to be command COMMAND
22676 (setq this-command command)
22678 (if arg
22679 (call-interactively command)
22681 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22682 (and (org-kill-is-subtree-p)
22683 (or (bolp)
22684 (and (looking-at "[ \t]*$")
22685 (string-match
22686 "\\`\\*+\\'"
22687 (buffer-substring (point-at-bol) (point)))))))
22688 swallowp)
22689 (cond
22690 ((and subtreep org-yank-folded-subtrees)
22691 (let ((beg (point))
22692 end)
22693 (if (and subtreep org-yank-adjusted-subtrees)
22694 (org-paste-subtree nil nil 'for-yank)
22695 (call-interactively command))
22697 (setq end (point))
22698 (goto-char beg)
22699 (when (and (bolp) subtreep
22700 (not (setq swallowp
22701 (org-yank-folding-would-swallow-text beg end))))
22702 (org-with-limited-levels
22703 (or (looking-at org-outline-regexp)
22704 (re-search-forward org-outline-regexp-bol end t))
22705 (while (and (< (point) end) (looking-at org-outline-regexp))
22706 (hide-subtree)
22707 (org-cycle-show-empty-lines 'folded)
22708 (condition-case nil
22709 (outline-forward-same-level 1)
22710 (error (goto-char end))))))
22711 (when swallowp
22712 (message
22713 "Inserted text not folded because that would swallow text"))
22715 (goto-char end)
22716 (skip-chars-forward " \t\n\r")
22717 (beginning-of-line 1)
22718 (push-mark beg 'nomsg)))
22719 ((and subtreep org-yank-adjusted-subtrees)
22720 (let ((beg (point-at-bol)))
22721 (org-paste-subtree nil nil 'for-yank)
22722 (push-mark beg 'nomsg)))
22724 (call-interactively command))))))
22726 (defun org-yank-folding-would-swallow-text (beg end)
22727 "Would hide-subtree at BEG swallow any text after END?"
22728 (let (level)
22729 (org-with-limited-levels
22730 (save-excursion
22731 (goto-char beg)
22732 (when (or (looking-at org-outline-regexp)
22733 (re-search-forward org-outline-regexp-bol end t))
22734 (setq level (org-outline-level)))
22735 (goto-char end)
22736 (skip-chars-forward " \t\r\n\v\f")
22737 (if (or (eobp)
22738 (and (bolp) (looking-at org-outline-regexp)
22739 (<= (org-outline-level) level)))
22740 nil ; Nothing would be swallowed
22741 t))))) ; something would swallow
22743 (define-key org-mode-map "\C-y" 'org-yank)
22745 (defun org-truely-invisible-p ()
22746 "Check if point is at a character currently not visible.
22747 This version does not only check the character property, but also
22748 `visible-mode'."
22749 ;; Early versions of noutline don't have `outline-invisible-p'.
22750 (if (org-bound-and-true-p visible-mode)
22752 (outline-invisible-p)))
22754 (defun org-invisible-p2 ()
22755 "Check if point is at a character currently not visible."
22756 (save-excursion
22757 (if (and (eolp) (not (bobp))) (backward-char 1))
22758 ;; Early versions of noutline don't have `outline-invisible-p'.
22759 (outline-invisible-p)))
22761 (defun org-back-to-heading (&optional invisible-ok)
22762 "Call `outline-back-to-heading', but provide a better error message."
22763 (condition-case nil
22764 (outline-back-to-heading invisible-ok)
22765 (error (error "Before first headline at position %d in buffer %s"
22766 (point) (current-buffer)))))
22768 (defun org-before-first-heading-p ()
22769 "Before first heading?"
22770 (save-excursion
22771 (end-of-line)
22772 (null (re-search-backward org-outline-regexp-bol nil t))))
22774 (defun org-at-heading-p (&optional ignored)
22775 (outline-on-heading-p t))
22776 ;; Compatibility alias with Org versions < 7.8.03
22777 (defalias 'org-on-heading-p 'org-at-heading-p)
22779 (defun org-at-comment-p nil
22780 "Is cursor in a line starting with a # character?"
22781 (save-excursion
22782 (beginning-of-line)
22783 (looking-at "^#")))
22785 (defun org-at-drawer-p nil
22786 "Is cursor at a drawer keyword?"
22787 (save-excursion
22788 (move-beginning-of-line 1)
22789 (looking-at org-drawer-regexp)))
22791 (defun org-at-block-p nil
22792 "Is cursor at a block keyword?"
22793 (save-excursion
22794 (move-beginning-of-line 1)
22795 (looking-at org-block-regexp)))
22797 (defun org-point-at-end-of-empty-headline ()
22798 "If point is at the end of an empty headline, return t, else nil.
22799 If the heading only contains a TODO keyword, it is still still considered
22800 empty."
22801 (and (looking-at "[ \t]*$")
22802 (when org-todo-line-regexp
22803 (save-excursion
22804 (beginning-of-line 1)
22805 (let ((case-fold-search nil))
22806 (looking-at org-todo-line-regexp)
22807 (string= (match-string 3) ""))))))
22809 (defun org-at-heading-or-item-p ()
22810 (or (org-at-heading-p) (org-at-item-p)))
22812 (defun org-at-target-p ()
22813 (or (org-in-regexp org-radio-target-regexp)
22814 (org-in-regexp org-target-regexp)))
22815 ;; Compatibility alias with Org versions < 7.8.03
22816 (defalias 'org-on-target-p 'org-at-target-p)
22818 (defun org-up-heading-all (arg)
22819 "Move to the heading line of which the present line is a subheading.
22820 This function considers both visible and invisible heading lines.
22821 With argument, move up ARG levels."
22822 (if (fboundp 'outline-up-heading-all)
22823 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22824 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22826 (defun org-up-heading-safe ()
22827 "Move to the heading line of which the present line is a subheading.
22828 This version will not throw an error. It will return the level of the
22829 headline found, or nil if no higher level is found.
22831 Also, this function will be a lot faster than `outline-up-heading',
22832 because it relies on stars being the outline starters. This can really
22833 make a significant difference in outlines with very many siblings."
22834 (let (start-level re)
22835 (org-back-to-heading t)
22836 (setq start-level (funcall outline-level))
22837 (if (equal start-level 1)
22839 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22840 (if (re-search-backward re nil t)
22841 (funcall outline-level)))))
22843 (defun org-first-sibling-p ()
22844 "Is this heading the first child of its parents?"
22845 (interactive)
22846 (let ((re org-outline-regexp-bol)
22847 level l)
22848 (unless (org-at-heading-p t)
22849 (error "Not at a heading"))
22850 (setq level (funcall outline-level))
22851 (save-excursion
22852 (if (not (re-search-backward re nil t))
22854 (setq l (funcall outline-level))
22855 (< l level)))))
22857 (defun org-goto-sibling (&optional previous)
22858 "Goto the next sibling, even if it is invisible.
22859 When PREVIOUS is set, go to the previous sibling instead. Returns t
22860 when a sibling was found. When none is found, return nil and don't
22861 move point."
22862 (let ((fun (if previous 're-search-backward 're-search-forward))
22863 (pos (point))
22864 (re org-outline-regexp-bol)
22865 level l)
22866 (when (condition-case nil (org-back-to-heading t) (error nil))
22867 (setq level (funcall outline-level))
22868 (catch 'exit
22869 (or previous (forward-char 1))
22870 (while (funcall fun re nil t)
22871 (setq l (funcall outline-level))
22872 (when (< l level) (goto-char pos) (throw 'exit nil))
22873 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22874 (goto-char pos)
22875 nil))))
22877 (defun org-show-siblings ()
22878 "Show all siblings of the current headline."
22879 (save-excursion
22880 (while (org-goto-sibling) (org-flag-heading nil)))
22881 (save-excursion
22882 (while (org-goto-sibling 'previous)
22883 (org-flag-heading nil))))
22885 (defun org-goto-first-child ()
22886 "Goto the first child, even if it is invisible.
22887 Return t when a child was found. Otherwise don't move point and
22888 return nil."
22889 (let (level (pos (point)) (re org-outline-regexp-bol))
22890 (when (condition-case nil (org-back-to-heading t) (error nil))
22891 (setq level (outline-level))
22892 (forward-char 1)
22893 (if (and (re-search-forward re nil t) (> (outline-level) level))
22894 (progn (goto-char (match-beginning 0)) t)
22895 (goto-char pos) nil))))
22897 (defun org-show-hidden-entry ()
22898 "Show an entry where even the heading is hidden."
22899 (save-excursion
22900 (org-show-entry)))
22902 (defun org-flag-heading (flag &optional entry)
22903 "Flag the current heading. FLAG non-nil means make invisible.
22904 When ENTRY is non-nil, show the entire entry."
22905 (save-excursion
22906 (org-back-to-heading t)
22907 ;; Check if we should show the entire entry
22908 (if entry
22909 (progn
22910 (org-show-entry)
22911 (save-excursion
22912 (and (outline-next-heading)
22913 (org-flag-heading nil))))
22914 (outline-flag-region (max (point-min) (1- (point)))
22915 (save-excursion (outline-end-of-heading) (point))
22916 flag))))
22918 (defun org-get-next-sibling ()
22919 "Move to next heading of the same level, and return point.
22920 If there is no such heading, return nil.
22921 This is like outline-next-sibling, but invisible headings are ok."
22922 (let ((level (funcall outline-level)))
22923 (outline-next-heading)
22924 (while (and (not (eobp)) (> (funcall outline-level) level))
22925 (outline-next-heading))
22926 (if (or (eobp) (< (funcall outline-level) level))
22928 (point))))
22930 (defun org-get-last-sibling ()
22931 "Move to previous heading of the same level, and return point.
22932 If there is no such heading, return nil."
22933 (let ((opoint (point))
22934 (level (funcall outline-level)))
22935 (outline-previous-heading)
22936 (when (and (/= (point) opoint) (outline-on-heading-p t))
22937 (while (and (> (funcall outline-level) level)
22938 (not (bobp)))
22939 (outline-previous-heading))
22940 (if (< (funcall outline-level) level)
22942 (point)))))
22944 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22945 "Goto to the end of a subtree."
22946 ;; This contains an exact copy of the original function, but it uses
22947 ;; `org-back-to-heading', to make it work also in invisible
22948 ;; trees. And is uses an invisible-ok argument.
22949 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22950 ;; Furthermore, when used inside Org, finding the end of a large subtree
22951 ;; with many children and grandchildren etc, this can be much faster
22952 ;; than the outline version.
22953 (org-back-to-heading invisible-ok)
22954 (let ((first t)
22955 (level (funcall outline-level)))
22956 (if (and (derived-mode-p 'org-mode) (< level 1000))
22957 ;; A true heading (not a plain list item), in Org-mode
22958 ;; This means we can easily find the end by looking
22959 ;; only for the right number of stars. Using a regexp to do
22960 ;; this is so much faster than using a Lisp loop.
22961 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22962 (forward-char 1)
22963 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22964 ;; something else, do it the slow way
22965 (while (and (not (eobp))
22966 (or first (> (funcall outline-level) level)))
22967 (setq first nil)
22968 (outline-next-heading)))
22969 (unless to-heading
22970 (if (memq (preceding-char) '(?\n ?\^M))
22971 (progn
22972 ;; Go to end of line before heading
22973 (forward-char -1)
22974 (if (memq (preceding-char) '(?\n ?\^M))
22975 ;; leave blank line before heading
22976 (forward-char -1))))))
22977 (point))
22979 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22980 "Use Org version in org-mode, for dramatic speed-up."
22981 (if (derived-mode-p 'org-mode)
22982 (progn
22983 (org-end-of-subtree nil t)
22984 (unless (eobp) (backward-char 1)))
22985 ad-do-it))
22987 (defun org-end-of-meta-data-and-drawers ()
22988 "Jump to the first text after meta data and drawers in the current entry.
22989 This will move over empty lines, lines with planning time stamps,
22990 clocking lines, and drawers."
22991 (org-back-to-heading t)
22992 (let ((end (save-excursion (outline-next-heading) (point)))
22993 (re (concat "\\(" org-drawer-regexp "\\)"
22994 "\\|" "[ \t]*" org-keyword-time-regexp)))
22995 (forward-line 1)
22996 (while (re-search-forward re end t)
22997 (if (not (match-end 1))
22998 ;; empty or planning line
22999 (forward-line 1)
23000 ;; a drawer, find the end
23001 (re-search-forward "^[ \t]*:END:" end 'move)
23002 (forward-line 1)))
23003 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23004 (point)))
23006 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23007 "Move forward to the ARG'th subheading at same level as this one.
23008 Stop at the first and last subheadings of a superior heading.
23009 Normally this only looks at visible headings, but when INVISIBLE-OK is
23010 non-nil it will also look at invisible ones."
23011 (interactive "p")
23012 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23013 (if (and arg (< arg 0))
23014 (goto-char (point-min))
23015 (outline-next-heading))
23016 (org-at-heading-p)
23017 (let ((level (- (match-end 0) (match-beginning 0) 1))
23018 (f (if (and arg (< arg 0))
23019 're-search-backward
23020 're-search-forward))
23021 (count (if arg (abs arg) 1))
23022 (result (point)))
23023 (forward-char (if (and arg (< arg 0)) -1 1))
23024 (while (and (> count 0)
23025 (funcall f org-outline-regexp-bol nil 'move))
23026 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23027 (cond ((< l level) (setq count 0))
23028 ((and (= l level)
23029 (or invisible-ok
23030 (progn
23031 (goto-char (line-beginning-position))
23032 (not (outline-invisible-p)))))
23033 (setq count (1- count))
23034 (when (eq l level)
23035 (setq result (point)))))))
23036 (goto-char result))
23037 (beginning-of-line 1)))
23039 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23040 "Move backward to the ARG'th subheading at same level as this one.
23041 Stop at the first and last subheadings of a superior heading."
23042 (interactive "p")
23043 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23045 (defun org-next-block (arg &optional backward block-regexp)
23046 "Jump to the next block.
23047 With a prefix argument ARG, jump forward ARG many source blocks.
23048 When BACKWARD is non-nil, jump to the previous block.
23049 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23050 (interactive "p")
23051 (let ((re (or block-regexp org-block-regexp))
23052 (re-search-fn (or (and backward 're-search-backward)
23053 're-search-forward)))
23054 (if (looking-at re) (forward-char 1))
23055 (condition-case nil
23056 (funcall re-search-fn re nil nil arg)
23057 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23058 (goto-char (match-beginning 0)) (org-show-context)))
23060 (defun org-previous-block (arg &optional block-regexp)
23061 "Jump to the previous block.
23062 With a prefix argument ARG, jump backward ARG many source blocks.
23063 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23064 (interactive "p")
23065 (org-next-block arg t block-regexp))
23067 (defun org-forward-element ()
23068 "Move forward by one element.
23069 Move to the next element at the same level, when possible."
23070 (interactive)
23071 (cond ((eobp) (user-error "Cannot move further down"))
23072 ((org-with-limited-levels (org-at-heading-p))
23073 (let ((origin (point)))
23074 (goto-char (org-end-of-subtree nil t))
23075 (unless (org-with-limited-levels (org-at-heading-p))
23076 (goto-char origin)
23077 (user-error "Cannot move further down"))))
23079 (let* ((elem (org-element-at-point))
23080 (end (org-element-property :end elem))
23081 (parent (org-element-property :parent elem)))
23082 (if (and parent (= (org-element-property :contents-end parent) end))
23083 (goto-char (org-element-property :end parent))
23084 (goto-char end))))))
23086 (defun org-backward-element ()
23087 "Move backward by one element.
23088 Move to the previous element at the same level, when possible."
23089 (interactive)
23090 (cond ((bobp) (user-error "Cannot move further up"))
23091 ((org-with-limited-levels (org-at-heading-p))
23092 ;; At a headline, move to the previous one, if any, or stay
23093 ;; here.
23094 (let ((origin (point)))
23095 (org-with-limited-levels (org-backward-heading-same-level 1))
23096 ;; When current headline has no sibling above, move to its
23097 ;; parent.
23098 (when (= (point) origin)
23099 (or (org-with-limited-levels (org-up-heading-safe))
23100 (progn (goto-char origin)
23101 (user-error "Cannot move further up"))))))
23103 (let* ((trail (org-element-at-point 'keep-trail))
23104 (elem (car trail))
23105 (prev-elem (nth 1 trail))
23106 (beg (org-element-property :begin elem)))
23107 (cond
23108 ;; Move to beginning of current element if point isn't
23109 ;; there already.
23110 ((/= (point) beg) (goto-char beg))
23111 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23112 ((org-before-first-heading-p) (goto-char (point-min)))
23113 (t (org-back-to-heading)))))))
23115 (defun org-up-element ()
23116 "Move to upper element."
23117 (interactive)
23118 (if (org-with-limited-levels (org-at-heading-p))
23119 (unless (org-up-heading-safe) (error "No surrounding element"))
23120 (let* ((elem (org-element-at-point))
23121 (parent (org-element-property :parent elem)))
23122 (if parent (goto-char (org-element-property :begin parent))
23123 (if (org-with-limited-levels (org-before-first-heading-p))
23124 (error "No surrounding element")
23125 (org-with-limited-levels (org-back-to-heading)))))))
23127 (defvar org-element-greater-elements)
23128 (defun org-down-element ()
23129 "Move to inner element."
23130 (interactive)
23131 (let ((element (org-element-at-point)))
23132 (cond
23133 ((memq (org-element-type element) '(plain-list table))
23134 (goto-char (org-element-property :contents-begin element))
23135 (forward-char))
23136 ((memq (org-element-type element) org-element-greater-elements)
23137 ;; If contents are hidden, first disclose them.
23138 (when (org-element-property :hiddenp element) (org-cycle))
23139 (goto-char (or (org-element-property :contents-begin element)
23140 (error "No content for this element"))))
23141 (t (error "No inner element")))))
23143 (defun org-drag-element-backward ()
23144 "Move backward element at point."
23145 (interactive)
23146 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23147 (let* ((trail (org-element-at-point 'keep-trail))
23148 (elem (car trail))
23149 (prev-elem (nth 1 trail)))
23150 ;; Error out if no previous element or previous element is
23151 ;; a parent of the current one.
23152 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23153 (error "Cannot drag element backward")
23154 (let ((pos (point)))
23155 (org-element-swap-A-B prev-elem elem)
23156 (goto-char (+ (org-element-property :begin prev-elem)
23157 (- pos (org-element-property :begin elem)))))))))
23159 (defun org-drag-element-forward ()
23160 "Move forward element at point."
23161 (interactive)
23162 (let* ((pos (point))
23163 (elem (org-element-at-point)))
23164 (when (= (point-max) (org-element-property :end elem))
23165 (error "Cannot drag element forward"))
23166 (goto-char (org-element-property :end elem))
23167 (let ((next-elem (org-element-at-point)))
23168 (when (or (org-element-nested-p elem next-elem)
23169 (and (eq (org-element-type next-elem) 'headline)
23170 (not (eq (org-element-type elem) 'headline))))
23171 (goto-char pos)
23172 (error "Cannot drag element forward"))
23173 ;; Compute new position of point: it's shifted by NEXT-ELEM
23174 ;; body's length (without final blanks) and by the length of
23175 ;; blanks between ELEM and NEXT-ELEM.
23176 (let ((size-next (- (save-excursion
23177 (goto-char (org-element-property :end next-elem))
23178 (skip-chars-backward " \r\t\n")
23179 (forward-line)
23180 ;; Small correction if buffer doesn't end
23181 ;; with a newline character.
23182 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23183 (org-element-property :begin next-elem)))
23184 (size-blank (- (org-element-property :end elem)
23185 (save-excursion
23186 (goto-char (org-element-property :end elem))
23187 (skip-chars-backward " \r\t\n")
23188 (forward-line)
23189 (point)))))
23190 (org-element-swap-A-B elem next-elem)
23191 (goto-char (+ pos size-next size-blank))))))
23193 (defun org-drag-line-forward (arg)
23194 "Drag the line at point ARG lines forward."
23195 (interactive "p")
23196 (dotimes (n (abs arg))
23197 (let ((c (current-column)))
23198 (if (< 0 arg)
23199 (progn
23200 (beginning-of-line 2)
23201 (transpose-lines 1)
23202 (beginning-of-line 0))
23203 (transpose-lines 1)
23204 (beginning-of-line -1))
23205 (org-move-to-column c))))
23207 (defun org-drag-line-backward (arg)
23208 "Drag the line at point ARG lines backward."
23209 (interactive "p")
23210 (org-drag-line-forward (- arg)))
23212 (defun org-mark-element ()
23213 "Put point at beginning of this element, mark at end.
23215 Interactively, if this command is repeated or (in Transient Mark
23216 mode) if the mark is active, it marks the next element after the
23217 ones already marked."
23218 (interactive)
23219 (let (deactivate-mark)
23220 (if (and (org-called-interactively-p 'any)
23221 (or (and (eq last-command this-command) (mark t))
23222 (and transient-mark-mode mark-active)))
23223 (set-mark
23224 (save-excursion
23225 (goto-char (mark))
23226 (goto-char (org-element-property :end (org-element-at-point)))))
23227 (let ((element (org-element-at-point)))
23228 (end-of-line)
23229 (push-mark (org-element-property :end element) t t)
23230 (goto-char (org-element-property :begin element))))))
23232 (defun org-narrow-to-element ()
23233 "Narrow buffer to current element."
23234 (interactive)
23235 (let ((elem (org-element-at-point)))
23236 (cond
23237 ((eq (car elem) 'headline)
23238 (narrow-to-region
23239 (org-element-property :begin elem)
23240 (org-element-property :end elem)))
23241 ((memq (car elem) org-element-greater-elements)
23242 (narrow-to-region
23243 (org-element-property :contents-begin elem)
23244 (org-element-property :contents-end elem)))
23246 (narrow-to-region
23247 (org-element-property :begin elem)
23248 (org-element-property :end elem))))))
23250 (defun org-transpose-element ()
23251 "Transpose current and previous elements, keeping blank lines between.
23252 Point is moved after both elements."
23253 (interactive)
23254 (org-skip-whitespace)
23255 (let ((end (org-element-property :end (org-element-at-point))))
23256 (org-drag-element-backward)
23257 (goto-char end)))
23259 (defun org-unindent-buffer ()
23260 "Un-indent the visible part of the buffer.
23261 Relative indentation (between items, inside blocks, etc.) isn't
23262 modified."
23263 (interactive)
23264 (unless (eq major-mode 'org-mode)
23265 (error "Cannot un-indent a buffer not in Org mode"))
23266 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23267 unindent-tree ; For byte-compiler.
23268 (unindent-tree
23269 (function
23270 (lambda (contents)
23271 (mapc
23272 (lambda (element)
23273 (if (memq (org-element-type element) '(headline section))
23274 (funcall unindent-tree (org-element-contents element))
23275 (save-excursion
23276 (save-restriction
23277 (narrow-to-region
23278 (org-element-property :begin element)
23279 (org-element-property :end element))
23280 (org-do-remove-indentation)))))
23281 (reverse contents))))))
23282 (funcall unindent-tree (org-element-contents parse-tree))))
23284 (defun org-show-subtree ()
23285 "Show everything after this heading at deeper levels."
23286 (interactive)
23287 (outline-flag-region
23288 (point)
23289 (save-excursion
23290 (org-end-of-subtree t t))
23291 nil))
23293 (defun org-show-entry ()
23294 "Show the body directly following this heading.
23295 Show the heading too, if it is currently invisible."
23296 (interactive)
23297 (save-excursion
23298 (condition-case nil
23299 (progn
23300 (org-back-to-heading t)
23301 (outline-flag-region
23302 (max (point-min) (1- (point)))
23303 (save-excursion
23304 (if (re-search-forward
23305 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23306 (match-beginning 1)
23307 (point-max)))
23308 nil)
23309 (org-cycle-hide-drawers 'children))
23310 (error nil))))
23312 (defun org-make-options-regexp (kwds &optional extra)
23313 "Make a regular expression for keyword lines."
23314 (concat
23315 "^#\\+\\("
23316 (mapconcat 'regexp-quote kwds "\\|")
23317 (if extra (concat "\\|" extra))
23318 "\\):[ \t]*\\(.*\\)"))
23320 ;; Make isearch reveal the necessary context
23321 (defun org-isearch-end ()
23322 "Reveal context after isearch exits."
23323 (when isearch-success ; only if search was successful
23324 (if (featurep 'xemacs)
23325 ;; Under XEmacs, the hook is run in the correct place,
23326 ;; we directly show the context.
23327 (org-show-context 'isearch)
23328 ;; In Emacs the hook runs *before* restoring the overlays.
23329 ;; So we have to use a one-time post-command-hook to do this.
23330 ;; (Emacs 22 has a special variable, see function `org-mode')
23331 (unless (and (boundp 'isearch-mode-end-hook-quit)
23332 isearch-mode-end-hook-quit)
23333 ;; Only when the isearch was not quitted.
23334 (org-add-hook 'post-command-hook 'org-isearch-post-command
23335 'append 'local)))
23336 (org-fix-ellipsis-at-bol)))
23338 (defun org-isearch-post-command ()
23339 "Remove self from hook, and show context."
23340 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23341 (org-show-context 'isearch))
23344 ;;;; Integration with and fixes for other packages
23346 ;;; Imenu support
23348 (defvar org-imenu-markers nil
23349 "All markers currently used by Imenu.")
23350 (make-variable-buffer-local 'org-imenu-markers)
23352 (defun org-imenu-new-marker (&optional pos)
23353 "Return a new marker for use by Imenu, and remember the marker."
23354 (let ((m (make-marker)))
23355 (move-marker m (or pos (point)))
23356 (push m org-imenu-markers)
23359 (defun org-imenu-get-tree ()
23360 "Produce the index for Imenu."
23361 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23362 (setq org-imenu-markers nil)
23363 (let* ((n org-imenu-depth)
23364 (re (concat "^" (org-get-limited-outline-regexp)))
23365 (subs (make-vector (1+ n) nil))
23366 (last-level 0)
23367 m level head0 head)
23368 (save-excursion
23369 (save-restriction
23370 (widen)
23371 (goto-char (point-max))
23372 (while (re-search-backward re nil t)
23373 (setq level (org-reduced-level (funcall outline-level)))
23374 (when (and (<= level n)
23375 (looking-at org-complex-heading-regexp)
23376 (setq head0 (org-match-string-no-properties 4)))
23377 (setq head (org-link-display-format head0)
23378 m (org-imenu-new-marker))
23379 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23380 (if (>= level last-level)
23381 (push (cons head m) (aref subs level))
23382 (push (cons head (aref subs (1+ level))) (aref subs level))
23383 (loop for i from (1+ level) to n do (aset subs i nil)))
23384 (setq last-level level)))))
23385 (aref subs 1)))
23387 (eval-after-load "imenu"
23388 '(progn
23389 (add-hook 'imenu-after-jump-hook
23390 (lambda ()
23391 (if (derived-mode-p 'org-mode)
23392 (org-show-context 'org-goto))))))
23394 (defun org-link-display-format (link)
23395 "Replace a link with its the description.
23396 If there is no description, use the link target."
23397 (save-match-data
23398 (if (string-match org-bracket-link-analytic-regexp link)
23399 (replace-match (if (match-end 5)
23400 (match-string 5 link)
23401 (concat (match-string 1 link)
23402 (match-string 3 link)))
23403 nil t link)
23404 link)))
23406 (defun org-toggle-link-display ()
23407 "Toggle the literal or descriptive display of links."
23408 (interactive)
23409 (if org-descriptive-links
23410 (progn (org-remove-from-invisibility-spec '(org-link))
23411 (org-restart-font-lock)
23412 (setq org-descriptive-links nil))
23413 (progn (add-to-invisibility-spec '(org-link))
23414 (org-restart-font-lock)
23415 (setq org-descriptive-links t))))
23417 ;; Speedbar support
23419 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23420 "Overlay marking the agenda restriction line in speedbar.")
23421 (overlay-put org-speedbar-restriction-lock-overlay
23422 'face 'org-agenda-restriction-lock)
23423 (overlay-put org-speedbar-restriction-lock-overlay
23424 'help-echo "Agendas are currently limited to this item.")
23425 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23427 (defun org-speedbar-set-agenda-restriction ()
23428 "Restrict future agenda commands to the location at point in speedbar.
23429 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23430 (interactive)
23431 (require 'org-agenda)
23432 (let (p m tp np dir txt)
23433 (cond
23434 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23435 'org-imenu t))
23436 (setq m (get-text-property p 'org-imenu-marker))
23437 (with-current-buffer (marker-buffer m)
23438 (goto-char m)
23439 (org-agenda-set-restriction-lock 'subtree)))
23440 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23441 'speedbar-function 'speedbar-find-file))
23442 (setq tp (previous-single-property-change
23443 (1+ p) 'speedbar-function)
23444 np (next-single-property-change
23445 tp 'speedbar-function)
23446 dir (speedbar-line-directory)
23447 txt (buffer-substring-no-properties (or tp (point-min))
23448 (or np (point-max))))
23449 (with-current-buffer (find-file-noselect
23450 (let ((default-directory dir))
23451 (expand-file-name txt)))
23452 (unless (derived-mode-p 'org-mode)
23453 (error "Cannot restrict to non-Org-mode file"))
23454 (org-agenda-set-restriction-lock 'file)))
23455 (t (error "Don't know how to restrict Org-mode's agenda")))
23456 (move-overlay org-speedbar-restriction-lock-overlay
23457 (point-at-bol) (point-at-eol))
23458 (setq current-prefix-arg nil)
23459 (org-agenda-maybe-redo)))
23461 (eval-after-load "speedbar"
23462 '(progn
23463 (speedbar-add-supported-extension ".org")
23464 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23465 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23466 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23467 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23468 (add-hook 'speedbar-visiting-tag-hook
23469 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23471 ;;; Fixes and Hacks for problems with other packages
23473 ;; Make flyspell not check words in links, to not mess up our keymap
23474 (defvar org-element-affiliated-keywords) ; From org-element.el
23475 (defvar org-element-block-name-alist) ; From org-element.el
23476 (defun org-mode-flyspell-verify ()
23477 "Don't let flyspell put overlays at active buttons, or on
23478 {todo,all-time,additional-option-like}-keywords."
23479 (require 'org-element) ; For `org-element-affiliated-keywords'
23480 (let ((pos (max (1- (point)) (point-min)))
23481 (word (thing-at-point 'word)))
23482 (and (not (get-text-property pos 'keymap))
23483 (not (get-text-property pos 'org-no-flyspell))
23484 (not (member word org-todo-keywords-1))
23485 (not (member word org-all-time-keywords))
23486 (not (member word org-options-keywords))
23487 (not (member word (mapcar 'car org-startup-options)))
23488 (not (member-ignore-case word org-element-affiliated-keywords))
23489 (not (member-ignore-case word (org-get-export-keywords)))
23490 (not (member-ignore-case
23491 word (mapcar 'car org-element-block-name-alist)))
23492 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23494 (defun org-remove-flyspell-overlays-in (beg end)
23495 "Remove flyspell overlays in region."
23496 (and (org-bound-and-true-p flyspell-mode)
23497 (fboundp 'flyspell-delete-region-overlays)
23498 (flyspell-delete-region-overlays beg end))
23499 (add-text-properties beg end '(org-no-flyspell t)))
23501 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23502 (eval-after-load "bookmark"
23503 '(if (boundp 'bookmark-after-jump-hook)
23504 ;; We can use the hook
23505 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23506 ;; Hook not available, use advice
23507 (defadvice bookmark-jump (after org-make-visible activate)
23508 "Make the position visible."
23509 (org-bookmark-jump-unhide))))
23511 ;; Make sure saveplace shows the location if it was hidden
23512 (eval-after-load "saveplace"
23513 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23514 "Make the position visible."
23515 (org-bookmark-jump-unhide)))
23517 ;; Make sure ecb shows the location if it was hidden
23518 (eval-after-load "ecb"
23519 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23520 "Make hierarchy visible when jumping into location from ECB tree buffer."
23521 (if (derived-mode-p 'org-mode)
23522 (org-show-context))))
23524 (defun org-bookmark-jump-unhide ()
23525 "Unhide the current position, to show the bookmark location."
23526 (and (derived-mode-p 'org-mode)
23527 (or (outline-invisible-p)
23528 (save-excursion (goto-char (max (point-min) (1- (point))))
23529 (outline-invisible-p)))
23530 (org-show-context 'bookmark-jump)))
23532 ;; Make session.el ignore our circular variable
23533 (eval-after-load "session"
23534 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23536 ;;;; Finish up
23538 (provide 'org)
23540 (run-hooks 'org-load-hook)
23542 ;;; org.el ends here