Let's a :APPT_WARNTIME: property override `appt-message-warning-time' in `org-agenda...
[org-mode.git] / lisp / org.el
blob7933d4726d07f9e7c6d24cb448a1c0c4964f18fd
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 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 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
82 ;; some places -- e.g. see the macro org-with-limited-levels.
84 ;; In Org buffers, the value of `outline-regexp' is that of
85 ;; `org-outline-regexp'. The only function still directly relying on
86 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
87 ;; job when `orgstruct-mode' is active.
88 (defvar org-outline-regexp "\\*+ "
89 "Regexp to match Org headlines.")
90 (defconst org-outline-regexp-bol "^\\*+ "
91 "Regexp to match Org headlines.
92 This is similar to `org-outline-regexp' but additionally makes
93 sure that we are at the beginning of the line.")
95 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
96 "Matches an headline, putting stars and text into groups.
97 Stars are put in group 1 and the trimmed body in group 2.")
99 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
100 (when (fboundp 'defvaralias)
101 (unless (boundp 'calendar-view-holidays-initially-flag)
102 (defvaralias 'calendar-view-holidays-initially-flag
103 'view-calendar-holidays-initially))
104 (unless (boundp 'calendar-view-diary-initially-flag)
105 (defvaralias 'calendar-view-diary-initially-flag
106 'view-diary-entries-initially))
107 (unless (boundp 'diary-fancy-buffer)
108 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
110 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
111 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
112 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
113 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
114 (declare-function org-at-clock-log-p "org-clock" ())
115 (declare-function org-clock-timestamps-up "org-clock" ())
116 (declare-function org-clock-timestamps-down "org-clock" ())
118 ;; load languages based on value of `org-babel-load-languages'
119 (defvar org-babel-load-languages)
120 ;;;###autoload
121 (defun org-babel-do-load-languages (sym value)
122 "Load the languages defined in `org-babel-load-languages'."
123 (set-default sym value)
124 (mapc (lambda (pair)
125 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
126 (if active
127 (progn
128 (require (intern (concat "ob-" lang))))
129 (progn
130 (funcall 'fmakunbound
131 (intern (concat "org-babel-execute:" lang)))
132 (funcall 'fmakunbound
133 (intern (concat "org-babel-expand-body:" lang)))))))
134 org-babel-load-languages))
136 (defcustom org-babel-load-languages '((emacs-lisp . t))
137 "Languages which can be evaluated in Org-mode buffers.
138 This list can be used to load support for any of the languages
139 below, note that each language will depend on a different set of
140 system executables and/or Emacs modes. When a language is
141 \"loaded\", then code blocks in that language can be evaluated
142 with `org-babel-execute-src-block' bound by default to C-c
143 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
144 be set to remove code block evaluation from the C-c C-c
145 keybinding. By default only Emacs Lisp (which has no
146 requirements) is loaded."
147 :group 'org-babel
148 :set 'org-babel-do-load-languages
149 :version "24.1"
150 :type '(alist :tag "Babel Languages"
151 :key-type
152 (choice
153 (const :tag "Awk" awk)
154 (const :tag "C" C)
155 (const :tag "R" R)
156 (const :tag "Asymptote" asymptote)
157 (const :tag "Calc" calc)
158 (const :tag "Clojure" clojure)
159 (const :tag "CSS" css)
160 (const :tag "Ditaa" ditaa)
161 (const :tag "Dot" dot)
162 (const :tag "Emacs Lisp" emacs-lisp)
163 (const :tag "Fortran" fortran)
164 (const :tag "Gnuplot" gnuplot)
165 (const :tag "Haskell" haskell)
166 (const :tag "IO" io)
167 (const :tag "Java" java)
168 (const :tag "Javascript" js)
169 (const :tag "LaTeX" latex)
170 (const :tag "Ledger" ledger)
171 (const :tag "Lilypond" lilypond)
172 (const :tag "Lisp" lisp)
173 (const :tag "Maxima" maxima)
174 (const :tag "Matlab" matlab)
175 (const :tag "Mscgen" mscgen)
176 (const :tag "Ocaml" ocaml)
177 (const :tag "Octave" octave)
178 (const :tag "Org" org)
179 (const :tag "Perl" perl)
180 (const :tag "Pico Lisp" picolisp)
181 (const :tag "PlantUML" plantuml)
182 (const :tag "Python" python)
183 (const :tag "Ruby" ruby)
184 (const :tag "Sass" sass)
185 (const :tag "Scala" scala)
186 (const :tag "Scheme" scheme)
187 (const :tag "Screen" screen)
188 (const :tag "Shell Script" sh)
189 (const :tag "Shen" shen)
190 (const :tag "Sql" sql)
191 (const :tag "Sqlite" sqlite))
192 :value-type (boolean :tag "Activate" :value t)))
194 ;;;; Customization variables
195 (defcustom org-clone-delete-id nil
196 "Remove ID property of clones of a subtree.
197 When non-nil, clones of a subtree don't inherit the ID property.
198 Otherwise they inherit the ID property with a new unique
199 identifier."
200 :type 'boolean
201 :version "24.1"
202 :group 'org-id)
204 ;;; Version
205 (org-check-version)
206 ;;;###autoload
207 (defun org-version (&optional here full message)
208 "Show the org-mode version in the echo area.
209 With prefix argument HERE, insert it at point.
210 When FULL is non-nil, use a verbose version string.
211 When MESSAGE is non-nil, display a message with the version."
212 (interactive "P")
213 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
214 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
215 (org-trash (or
216 (and (fboundp 'org-release) (fboundp 'org-git-version))
217 (load (concat org-dir "org-version.el")
218 'noerror 'nomessage 'nosuffix)))
219 (org-version (org-release))
220 (git-version (org-git-version))
221 (version (format "Org-mode version %s (%s @ %s)"
222 org-version
223 git-version
224 (if org-install-dir
225 (if (string= org-dir org-install-dir)
226 org-install-dir
227 (concat "mixed installation! " org-install-dir " and " org-dir))
228 "org-install.el can not be found!")))
229 (_version (if full version org-version)))
230 (if (org-called-interactively-p 'interactive)
231 (if here
232 (insert version)
233 (message version))
234 (if message (message _version))
235 _version)))
237 ;;; Compatibility constants
239 ;;; The custom variables
241 (defgroup org nil
242 "Outline-based notes management and organizer."
243 :tag "Org"
244 :group 'outlines
245 :group 'calendar)
247 (defcustom org-mode-hook nil
248 "Mode hook for Org-mode, run after the mode was turned on."
249 :group 'org
250 :type 'hook)
252 (defcustom org-load-hook nil
253 "Hook that is run after org.el has been loaded."
254 :group 'org
255 :type 'hook)
257 (defcustom org-log-buffer-setup-hook nil
258 "Hook that is run after an Org log buffer is created."
259 :group 'org
260 :version "24.1"
261 :type 'hook)
263 (defvar org-modules) ; defined below
264 (defvar org-modules-loaded nil
265 "Have the modules been loaded already?")
267 (defun org-load-modules-maybe (&optional force)
268 "Load all extensions listed in `org-modules'."
269 (when (or force (not org-modules-loaded))
270 (mapc (lambda (ext)
271 (condition-case nil (require ext)
272 (error (message "Problems while trying to load feature `%s'" ext))))
273 org-modules)
274 (setq org-modules-loaded t)))
276 (defun org-set-modules (var value)
277 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
278 (set var value)
279 (when (featurep 'org)
280 (org-load-modules-maybe 'force)))
282 (when (org-bound-and-true-p org-modules)
283 (let ((a (member 'org-infojs org-modules)))
284 (and a (setcar a 'org-jsinfo))))
286 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
287 "Modules that should always be loaded together with org.el.
288 If a description starts with <C>, the file is not part of Emacs
289 and loading it will require that you have downloaded and properly installed
290 the org-mode distribution.
292 You can also use this system to load external packages (i.e. neither Org
293 core modules, nor modules from the CONTRIB directory). Just add symbols
294 to the end of the list. If the package is called org-xyz.el, then you need
295 to add the symbol `xyz', and the package must have a call to
297 (provide 'org-xyz)"
298 :group 'org
299 :set 'org-set-modules
300 :type
301 '(set :greedy t
302 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
303 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
304 (const :tag " crypt: Encryption of subtrees" org-crypt)
305 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
306 (const :tag " docview: Links to doc-view buffers" org-docview)
307 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
308 (const :tag " id: Global IDs for identifying entries" org-id)
309 (const :tag " info: Links to Info nodes" org-info)
310 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
311 (const :tag " habit: Track your consistency with habits" org-habit)
312 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
313 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
314 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
315 (const :tag " mew Links to Mew folders/messages" org-mew)
316 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
317 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
318 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
319 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
320 (const :tag " vm: Links to VM folders/messages" org-vm)
321 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
322 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
323 (const :tag " mouse: Additional mouse support" org-mouse)
324 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
326 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
327 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
328 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
329 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
330 (const :tag "C collector: Collect properties into tables" org-collector)
331 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
332 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
333 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
334 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
335 (const :tag "C eval: Include command output as text" org-eval)
336 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
337 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
338 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
339 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
340 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
342 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
344 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
345 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
346 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
347 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
348 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
349 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
350 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
351 (const :tag "C mtags: Support for muse-like tags" org-mtags)
352 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
353 (const :tag "C registry: A registry for Org-mode links" org-registry)
354 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
355 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
356 (const :tag "C secretary: Team management with org-mode" org-secretary)
357 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
358 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
359 (const :tag "C track: Keep up with Org-mode development" org-track)
360 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
361 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
362 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
364 (defcustom org-support-shift-select nil
365 "Non-nil means make shift-cursor commands select text when possible.
367 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
368 start selecting a region, or enlarge regions started in this way.
369 In Org-mode, in special contexts, these same keys are used for
370 other purposes, important enough to compete with shift selection.
371 Org tries to balance these needs by supporting `shift-select-mode'
372 outside these special contexts, under control of this variable.
374 The default of this variable is nil, to avoid confusing behavior. Shifted
375 cursor keys will then execute Org commands in the following contexts:
376 - on a headline, changing TODO state (left/right) and priority (up/down)
377 - on a time stamp, changing the time
378 - in a plain list item, changing the bullet type
379 - in a property definition line, switching between allowed values
380 - in the BEGIN line of a clock table (changing the time block).
381 Outside these contexts, the commands will throw an error.
383 When this variable is t and the cursor is not in a special
384 context, Org-mode will support shift-selection for making and
385 enlarging regions. To make this more effective, the bullet
386 cycling will no longer happen anywhere in an item line, but only
387 if the cursor is exactly on the bullet.
389 If you set this variable to the symbol `always', then the keys
390 will not be special in headlines, property lines, and item lines,
391 to make shift selection work there as well. If this is what you
392 want, you can use the following alternative commands: `C-c C-t'
393 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
394 can be used to switch TODO sets, `C-c -' to cycle item bullet
395 types, and properties can be edited by hand or in column view.
397 However, when the cursor is on a timestamp, shift-cursor commands
398 will still edit the time stamp - this is just too good to give up.
400 XEmacs user should have this variable set to nil, because
401 `shift-select-mode' is in Emacs 23 or later only."
402 :group 'org
403 :type '(choice
404 (const :tag "Never" nil)
405 (const :tag "When outside special context" t)
406 (const :tag "Everywhere except timestamps" always)))
408 (defcustom org-loop-over-headlines-in-active-region nil
409 "Shall some commands act upon headlines in the active region?
411 When set to `t', some commands will be performed in all headlines
412 within the active region.
414 When set to `start-level', some commands will be performed in all
415 headlines within the active region, provided that these headlines
416 are of the same level than the first one.
418 When set to a string, those commands will be performed on the
419 matching headlines within the active region. Such string must be
420 a tags/property/todo match as it is used in the agenda tags view.
422 The list of commands is: `org-schedule', `org-deadline',
423 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
424 `org-archive-to-archive-sibling'. The archiving commands skip
425 already archived entries."
426 :type '(choice (const :tag "Don't loop" nil)
427 (const :tag "All headlines in active region" t)
428 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
429 (string :tag "Tags/Property/Todo matcher"))
430 :version "24.1"
431 :group 'org-todo
432 :group 'org-archive)
434 (defgroup org-startup nil
435 "Options concerning startup of Org-mode."
436 :tag "Org Startup"
437 :group 'org)
439 (defcustom org-startup-folded t
440 "Non-nil means entering Org-mode will switch to OVERVIEW.
441 This can also be configured on a per-file basis by adding one of
442 the following lines anywhere in the buffer:
444 #+STARTUP: fold (or `overview', this is equivalent)
445 #+STARTUP: nofold (or `showall', this is equivalent)
446 #+STARTUP: content
447 #+STARTUP: showeverything"
448 :group 'org-startup
449 :type '(choice
450 (const :tag "nofold: show all" nil)
451 (const :tag "fold: overview" t)
452 (const :tag "content: all headlines" content)
453 (const :tag "show everything, even drawers" showeverything)))
455 (defcustom org-startup-truncated t
456 "Non-nil means entering Org-mode will set `truncate-lines'.
457 This is useful since some lines containing links can be very long and
458 uninteresting. Also tables look terrible when wrapped."
459 :group 'org-startup
460 :type 'boolean)
462 (defcustom org-startup-indented nil
463 "Non-nil means turn on `org-indent-mode' on startup.
464 This can also be configured on a per-file basis by adding one of
465 the following lines anywhere in the buffer:
467 #+STARTUP: indent
468 #+STARTUP: noindent"
469 :group 'org-structure
470 :type '(choice
471 (const :tag "Not" nil)
472 (const :tag "Globally (slow on startup in large files)" t)))
474 (defcustom org-use-sub-superscripts t
475 "Non-nil means interpret \"_\" and \"^\" for export.
476 When this option is turned on, you can use TeX-like syntax for sub- and
477 superscripts. Several characters after \"_\" or \"^\" will be
478 considered as a single item - so grouping with {} is normally not
479 needed. For example, the following things will be parsed as single
480 sub- or superscripts.
482 10^24 or 10^tau several digits will be considered 1 item.
483 10^-12 or 10^-tau a leading sign with digits or a word
484 x^2-y^3 will be read as x^2 - y^3, because items are
485 terminated by almost any nonword/nondigit char.
486 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
488 Still, ambiguity is possible - so when in doubt use {} to enclose the
489 sub/superscript. If you set this variable to the symbol `{}',
490 the braces are *required* in order to trigger interpretations as
491 sub/superscript. This can be helpful in documents that need \"_\"
492 frequently in plain text.
494 Not all export backends support this, but HTML does.
496 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
497 :group 'org-startup
498 :group 'org-export-translation
499 :version "24.1"
500 :type '(choice
501 (const :tag "Always interpret" t)
502 (const :tag "Only with braces" {})
503 (const :tag "Never interpret" nil)))
505 (if (fboundp 'defvaralias)
506 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
509 (defcustom org-startup-with-beamer-mode nil
510 "Non-nil means turn on `org-beamer-mode' on startup.
511 This can also be configured on a per-file basis by adding one of
512 the following lines anywhere in the buffer:
514 #+STARTUP: beamer"
515 :group 'org-startup
516 :version "24.1"
517 :type 'boolean)
519 (defcustom org-startup-align-all-tables nil
520 "Non-nil means align all tables when visiting a file.
521 This is useful when the column width in tables is forced with <N> cookies
522 in table fields. Such tables will look correct only after the first re-align.
523 This can also be configured on a per-file basis by adding one of
524 the following lines anywhere in the buffer:
525 #+STARTUP: align
526 #+STARTUP: noalign"
527 :group 'org-startup
528 :type 'boolean)
530 (defcustom org-startup-with-inline-images nil
531 "Non-nil means show inline images when loading a new Org file.
532 This can also be configured on a per-file basis by adding one of
533 the following lines anywhere in the buffer:
534 #+STARTUP: inlineimages
535 #+STARTUP: noinlineimages"
536 :group 'org-startup
537 :version "24.1"
538 :type 'boolean)
540 (defcustom org-insert-mode-line-in-empty-file nil
541 "Non-nil means insert the first line setting Org-mode in empty files.
542 When the function `org-mode' is called interactively in an empty file, this
543 normally means that the file name does not automatically trigger Org-mode.
544 To ensure that the file will always be in Org-mode in the future, a
545 line enforcing Org-mode will be inserted into the buffer, if this option
546 has been set."
547 :group 'org-startup
548 :type 'boolean)
550 (defcustom org-replace-disputed-keys nil
551 "Non-nil means use alternative key bindings for some keys.
552 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
553 These keys are also used by other packages like shift-selection-mode'
554 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
555 If you want to use Org-mode together with one of these other modes,
556 or more generally if you would like to move some Org-mode commands to
557 other keys, set this variable and configure the keys with the variable
558 `org-disputed-keys'.
560 This option is only relevant at load-time of Org-mode, and must be set
561 *before* org.el is loaded. Changing it requires a restart of Emacs to
562 become effective."
563 :group 'org-startup
564 :type 'boolean)
566 (defcustom org-use-extra-keys nil
567 "Non-nil means use extra key sequence definitions for certain commands.
568 This happens automatically if you run XEmacs or if `window-system'
569 is nil. This variable lets you do the same manually. You must
570 set it before loading org.
572 Example: on Carbon Emacs 22 running graphically, with an external
573 keyboard on a Powerbook, the default way of setting M-left might
574 not work for either Alt or ESC. Setting this variable will make
575 it work for ESC."
576 :group 'org-startup
577 :type 'boolean)
579 (if (fboundp 'defvaralias)
580 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
582 (defcustom org-disputed-keys
583 '(([(shift up)] . [(meta p)])
584 ([(shift down)] . [(meta n)])
585 ([(shift left)] . [(meta -)])
586 ([(shift right)] . [(meta +)])
587 ([(control shift right)] . [(meta shift +)])
588 ([(control shift left)] . [(meta shift -)]))
589 "Keys for which Org-mode and other modes compete.
590 This is an alist, cars are the default keys, second element specifies
591 the alternative to use when `org-replace-disputed-keys' is t.
593 Keys can be specified in any syntax supported by `define-key'.
594 The value of this option takes effect only at Org-mode's startup,
595 therefore you'll have to restart Emacs to apply it after changing."
596 :group 'org-startup
597 :type 'alist)
599 (defun org-key (key)
600 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
601 Or return the original if not disputed.
602 Also apply the translations defined in `org-xemacs-key-equivalents'."
603 (when org-replace-disputed-keys
604 (let* ((nkey (key-description key))
605 (x (org-find-if (lambda (x)
606 (equal (key-description (car x)) nkey))
607 org-disputed-keys)))
608 (setq key (if x (cdr x) key))))
609 (when (featurep 'xemacs)
610 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
611 key)
613 (defun org-find-if (predicate seq)
614 (catch 'exit
615 (while seq
616 (if (funcall predicate (car seq))
617 (throw 'exit (car seq))
618 (pop seq)))))
620 (defun org-defkey (keymap key def)
621 "Define a key, possibly translated, as returned by `org-key'."
622 (define-key keymap (org-key key) def))
624 (defcustom org-ellipsis nil
625 "The ellipsis to use in the Org-mode outline.
626 When nil, just use the standard three dots. When a string, use that instead,
627 When a face, use the standard 3 dots, but with the specified face.
628 The change affects only Org-mode (which will then use its own display table).
629 Changing this requires executing `M-x org-mode' in a buffer to become
630 effective."
631 :group 'org-startup
632 :type '(choice (const :tag "Default" nil)
633 (face :tag "Face" :value org-warning)
634 (string :tag "String" :value "...#")))
636 (defvar org-display-table nil
637 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
639 (defgroup org-keywords nil
640 "Keywords in Org-mode."
641 :tag "Org Keywords"
642 :group 'org)
644 (defcustom org-deadline-string "DEADLINE:"
645 "String to mark deadline entries.
646 A deadline is this string, followed by a time stamp. Should be a word,
647 terminated by a colon. You can insert a schedule keyword and
648 a timestamp with \\[org-deadline].
649 Changes become only effective after restarting Emacs."
650 :group 'org-keywords
651 :type 'string)
653 (defcustom org-scheduled-string "SCHEDULED:"
654 "String to mark scheduled TODO entries.
655 A schedule is this string, followed by a time stamp. Should be a word,
656 terminated by a colon. You can insert a schedule keyword and
657 a timestamp with \\[org-schedule].
658 Changes become only effective after restarting Emacs."
659 :group 'org-keywords
660 :type 'string)
662 (defcustom org-closed-string "CLOSED:"
663 "String used as the prefix for timestamps logging closing a TODO entry."
664 :group 'org-keywords
665 :type 'string)
667 (defcustom org-clock-string "CLOCK:"
668 "String used as prefix for timestamps clocking work hours on an item."
669 :group 'org-keywords
670 :type 'string)
672 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
673 org-scheduled-string "\\|"
674 org-deadline-string "\\|"
675 org-closed-string "\\|"
676 org-clock-string "\\)")
677 "Matches a line with planning or clock info.")
679 (defcustom org-comment-string "COMMENT"
680 "Entries starting with this keyword will never be exported.
681 An entry can be toggled between COMMENT and normal with
682 \\[org-toggle-comment].
683 Changes become only effective after restarting Emacs."
684 :group 'org-keywords
685 :type 'string)
687 (defcustom org-quote-string "QUOTE"
688 "Entries starting with this keyword will be exported in fixed-width font.
689 Quoting applies only to the text in the entry following the headline, and does
690 not extend beyond the next headline, even if that is lower level.
691 An entry can be toggled between QUOTE and normal with
692 \\[org-toggle-fixed-width-section]."
693 :group 'org-keywords
694 :type 'string)
696 (defconst org-repeat-re
697 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
698 "Regular expression for specifying repeated events.
699 After a match, group 1 contains the repeat expression.")
701 (defgroup org-structure nil
702 "Options concerning the general structure of Org-mode files."
703 :tag "Org Structure"
704 :group 'org)
706 (defgroup org-reveal-location nil
707 "Options about how to make context of a location visible."
708 :tag "Org Reveal Location"
709 :group 'org-structure)
711 (defconst org-context-choice
712 '(choice
713 (const :tag "Always" t)
714 (const :tag "Never" nil)
715 (repeat :greedy t :tag "Individual contexts"
716 (cons
717 (choice :tag "Context"
718 (const agenda)
719 (const org-goto)
720 (const occur-tree)
721 (const tags-tree)
722 (const link-search)
723 (const mark-goto)
724 (const bookmark-jump)
725 (const isearch)
726 (const default))
727 (boolean))))
728 "Contexts for the reveal options.")
730 (defcustom org-show-hierarchy-above '((default . t))
731 "Non-nil means show full hierarchy when revealing a location.
732 Org-mode often shows locations in an org-mode file which might have
733 been invisible before. When this is set, the hierarchy of headings
734 above the exposed location is shown.
735 Turning this off for example for sparse trees makes them very compact.
736 Instead of t, this can also be an alist specifying this option for different
737 contexts. Valid contexts are
738 agenda when exposing an entry from the agenda
739 org-goto when using the command `org-goto' on key C-c C-j
740 occur-tree when using the command `org-occur' on key C-c /
741 tags-tree when constructing a sparse tree based on tags matches
742 link-search when exposing search matches associated with a link
743 mark-goto when exposing the jump goal of a mark
744 bookmark-jump when exposing a bookmark location
745 isearch when exiting from an incremental search
746 default default for all contexts not set explicitly"
747 :group 'org-reveal-location
748 :type org-context-choice)
750 (defcustom org-show-following-heading '((default . nil))
751 "Non-nil means show following heading when revealing a location.
752 Org-mode often shows locations in an org-mode file which might have
753 been invisible before. When this is set, the heading following the
754 match is shown.
755 Turning this off for example for sparse trees makes them very compact,
756 but makes it harder to edit the location of the match. In such a case,
757 use the command \\[org-reveal] to show more context.
758 Instead of t, this can also be an alist specifying this option for different
759 contexts. See `org-show-hierarchy-above' for valid contexts."
760 :group 'org-reveal-location
761 :type org-context-choice)
763 (defcustom org-show-siblings '((default . nil) (isearch t))
764 "Non-nil means show all sibling heading when revealing a location.
765 Org-mode often shows locations in an org-mode file which might have
766 been invisible before. When this is set, the sibling of the current entry
767 heading are all made visible. If `org-show-hierarchy-above' is t,
768 the same happens on each level of the hierarchy above the current entry.
770 By default this is on for the isearch context, off for all other contexts.
771 Turning this off for example for sparse trees makes them very compact,
772 but makes it harder to edit the location of the match. In such a case,
773 use the command \\[org-reveal] to show more context.
774 Instead of t, this can also be an alist specifying this option for different
775 contexts. See `org-show-hierarchy-above' for valid contexts."
776 :group 'org-reveal-location
777 :type org-context-choice)
779 (defcustom org-show-entry-below '((default . nil))
780 "Non-nil means show the entry below a headline when revealing a location.
781 Org-mode often shows locations in an org-mode file which might have
782 been invisible before. When this is set, the text below the headline that is
783 exposed is also shown.
785 By default this is off for all contexts.
786 Instead of t, this can also be an alist specifying this option for different
787 contexts. See `org-show-hierarchy-above' for valid contexts."
788 :group 'org-reveal-location
789 :type org-context-choice)
791 (defcustom org-indirect-buffer-display 'other-window
792 "How should indirect tree buffers be displayed?
793 This applies to indirect buffers created with the commands
794 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
795 Valid values are:
796 current-window Display in the current window
797 other-window Just display in another window.
798 dedicated-frame Create one new frame, and re-use it each time.
799 new-frame Make a new frame each time. Note that in this case
800 previously-made indirect buffers are kept, and you need to
801 kill these buffers yourself."
802 :group 'org-structure
803 :group 'org-agenda-windows
804 :type '(choice
805 (const :tag "In current window" current-window)
806 (const :tag "In current frame, other window" other-window)
807 (const :tag "Each time a new frame" new-frame)
808 (const :tag "One dedicated frame" dedicated-frame)))
810 (defcustom org-use-speed-commands nil
811 "Non-nil means activate single letter commands at beginning of a headline.
812 This may also be a function to test for appropriate locations where speed
813 commands should be active."
814 :group 'org-structure
815 :type '(choice
816 (const :tag "Never" nil)
817 (const :tag "At beginning of headline stars" t)
818 (function)))
820 (defcustom org-speed-commands-user nil
821 "Alist of additional speed commands.
822 This list will be checked before `org-speed-commands-default'
823 when the variable `org-use-speed-commands' is non-nil
824 and when the cursor is at the beginning of a headline.
825 The car if each entry is a string with a single letter, which must
826 be assigned to `self-insert-command' in the global map.
827 The cdr is either a command to be called interactively, a function
828 to be called, or a form to be evaluated.
829 An entry that is just a list with a single string will be interpreted
830 as a descriptive headline that will be added when listing the speed
831 commands in the Help buffer using the `?' speed command."
832 :group 'org-structure
833 :type '(repeat :value ("k" . ignore)
834 (choice :value ("k" . ignore)
835 (list :tag "Descriptive Headline" (string :tag "Headline"))
836 (cons :tag "Letter and Command"
837 (string :tag "Command letter")
838 (choice
839 (function)
840 (sexp))))))
842 (defgroup org-cycle nil
843 "Options concerning visibility cycling in Org-mode."
844 :tag "Org Cycle"
845 :group 'org-structure)
847 (defcustom org-cycle-skip-children-state-if-no-children t
848 "Non-nil means skip CHILDREN state in entries that don't have any."
849 :group 'org-cycle
850 :type 'boolean)
852 (defcustom org-cycle-max-level nil
853 "Maximum level which should still be subject to visibility cycling.
854 Levels higher than this will, for cycling, be treated as text, not a headline.
855 When `org-odd-levels-only' is set, a value of N in this variable actually
856 means 2N-1 stars as the limiting headline.
857 When nil, cycle all levels.
858 Note that the limiting level of cycling is also influenced by
859 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
860 `org-inlinetask-min-level' is, cycling will be limited to levels one less
861 than its value."
862 :group 'org-cycle
863 :type '(choice
864 (const :tag "No limit" nil)
865 (integer :tag "Maximum level")))
867 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
868 "Names of drawers. Drawers are not opened by cycling on the headline above.
869 Drawers only open with a TAB on the drawer line itself. A drawer looks like
870 this:
871 :DRAWERNAME:
872 .....
873 :END:
874 The drawer \"PROPERTIES\" is special for capturing properties through
875 the property API.
877 Drawers can be defined on the per-file basis with a line like:
879 #+DRAWERS: HIDDEN STATE PROPERTIES"
880 :group 'org-structure
881 :group 'org-cycle
882 :type '(repeat (string :tag "Drawer Name")))
884 (defcustom org-hide-block-startup nil
885 "Non-nil means entering Org-mode will fold all blocks.
886 This can also be set in on a per-file basis with
888 #+STARTUP: hideblocks
889 #+STARTUP: showblocks"
890 :group 'org-startup
891 :group 'org-cycle
892 :type 'boolean)
894 (defcustom org-cycle-global-at-bob nil
895 "Cycle globally if cursor is at beginning of buffer and not at a headline.
896 This makes it possible to do global cycling without having to use S-TAB or
897 \\[universal-argument] TAB. For this special case to work, the first line \
898 of the buffer
899 must not be a headline - it may be empty or some other text. When used in
900 this way, `org-cycle-hook' is disables temporarily, to make sure the
901 cursor stays at the beginning of the buffer.
902 When this option is nil, don't do anything special at the beginning
903 of the buffer."
904 :group 'org-cycle
905 :type 'boolean)
907 (defcustom org-cycle-level-after-item/entry-creation t
908 "Non-nil means cycle entry level or item indentation in new empty entries.
910 When the cursor is at the end of an empty headline, i.e with only stars
911 and maybe a TODO keyword, TAB will then switch the entry to become a child,
912 and then all possible ancestor states, before returning to the original state.
913 This makes data entry extremely fast: M-RET to create a new headline,
914 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
916 When the cursor is at the end of an empty plain list item, one TAB will
917 make it a subitem, two or more tabs will back up to make this an item
918 higher up in the item hierarchy."
919 :group 'org-cycle
920 :type 'boolean)
922 (defcustom org-cycle-emulate-tab t
923 "Where should `org-cycle' emulate TAB.
924 nil Never
925 white Only in completely white lines
926 whitestart Only at the beginning of lines, before the first non-white char
927 t Everywhere except in headlines
928 exc-hl-bol Everywhere except at the start of a headline
929 If TAB is used in a place where it does not emulate TAB, the current subtree
930 visibility is cycled."
931 :group 'org-cycle
932 :type '(choice (const :tag "Never" nil)
933 (const :tag "Only in completely white lines" white)
934 (const :tag "Before first char in a line" whitestart)
935 (const :tag "Everywhere except in headlines" t)
936 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
939 (defcustom org-cycle-separator-lines 2
940 "Number of empty lines needed to keep an empty line between collapsed trees.
941 If you leave an empty line between the end of a subtree and the following
942 headline, this empty line is hidden when the subtree is folded.
943 Org-mode will leave (exactly) one empty line visible if the number of
944 empty lines is equal or larger to the number given in this variable.
945 So the default 2 means at least 2 empty lines after the end of a subtree
946 are needed to produce free space between a collapsed subtree and the
947 following headline.
949 If the number is negative, and the number of empty lines is at least -N,
950 all empty lines are shown.
952 Special case: when 0, never leave empty lines in collapsed view."
953 :group 'org-cycle
954 :type 'integer)
955 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
957 (defcustom org-pre-cycle-hook nil
958 "Hook that is run before visibility cycling is happening.
959 The function(s) in this hook must accept a single argument which indicates
960 the new state that will be set right after running this hook. The
961 argument is a symbol. Before a global state change, it can have the values
962 `overview', `content', or `all'. Before a local state change, it can have
963 the values `folded', `children', or `subtree'."
964 :group 'org-cycle
965 :type 'hook)
967 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
968 org-cycle-hide-drawers
969 org-cycle-show-empty-lines
970 org-optimize-window-after-visibility-change)
971 "Hook that is run after `org-cycle' has changed the buffer visibility.
972 The function(s) in this hook must accept a single argument which indicates
973 the new state that was set by the most recent `org-cycle' command. The
974 argument is a symbol. After a global state change, it can have the values
975 `overview', `content', or `all'. After a local state change, it can have
976 the values `folded', `children', or `subtree'."
977 :group 'org-cycle
978 :type 'hook)
980 (defgroup org-edit-structure nil
981 "Options concerning structure editing in Org-mode."
982 :tag "Org Edit Structure"
983 :group 'org-structure)
985 (defcustom org-odd-levels-only nil
986 "Non-nil means skip even levels and only use odd levels for the outline.
987 This has the effect that two stars are being added/taken away in
988 promotion/demotion commands. It also influences how levels are
989 handled by the exporters.
990 Changing it requires restart of `font-lock-mode' to become effective
991 for fontification also in regions already fontified.
992 You may also set this on a per-file basis by adding one of the following
993 lines to the buffer:
995 #+STARTUP: odd
996 #+STARTUP: oddeven"
997 :group 'org-edit-structure
998 :group 'org-appearance
999 :type 'boolean)
1001 (defcustom org-adapt-indentation t
1002 "Non-nil means adapt indentation to outline node level.
1004 When this variable is set, Org assumes that you write outlines by
1005 indenting text in each node to align with the headline (after the stars).
1006 The following issues are influenced by this variable:
1008 - When this is set and the *entire* text in an entry is indented, the
1009 indentation is increased by one space in a demotion command, and
1010 decreased by one in a promotion command. If any line in the entry
1011 body starts with text at column 0, indentation is not changed at all.
1013 - Property drawers and planning information is inserted indented when
1014 this variable s set. When nil, they will not be indented.
1016 - TAB indents a line relative to context. The lines below a headline
1017 will be indented when this variable is set.
1019 Note that this is all about true indentation, by adding and removing
1020 space characters. See also `org-indent.el' which does level-dependent
1021 indentation in a virtual way, i.e. at display time in Emacs."
1022 :group 'org-edit-structure
1023 :type 'boolean)
1025 (defcustom org-special-ctrl-a/e nil
1026 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1028 When t, `C-a' will bring back the cursor to the beginning of the
1029 headline text, i.e. after the stars and after a possible TODO
1030 keyword. In an item, this will be the position after bullet and
1031 check-box, if any. When the cursor is already at that position,
1032 another `C-a' will bring it to the beginning of the line.
1034 `C-e' will jump to the end of the headline, ignoring the presence
1035 of tags in the headline. A second `C-e' will then jump to the
1036 true end of the line, after any tags. This also means that, when
1037 this variable is non-nil, `C-e' also will never jump beyond the
1038 end of the heading of a folded section, i.e. not after the
1039 ellipses.
1041 When set to the symbol `reversed', the first `C-a' or `C-e' works
1042 normally, going to the true line boundary first. Only a directly
1043 following, identical keypress will bring the cursor to the
1044 special positions.
1046 This may also be a cons cell where the behavior for `C-a' and
1047 `C-e' is set separately."
1048 :group 'org-edit-structure
1049 :type '(choice
1050 (const :tag "off" nil)
1051 (const :tag "on: after stars/bullet and before tags first" t)
1052 (const :tag "reversed: true line boundary first" reversed)
1053 (cons :tag "Set C-a and C-e separately"
1054 (choice :tag "Special C-a"
1055 (const :tag "off" nil)
1056 (const :tag "on: after stars/bullet first" t)
1057 (const :tag "reversed: before stars/bullet first" reversed))
1058 (choice :tag "Special C-e"
1059 (const :tag "off" nil)
1060 (const :tag "on: before tags first" t)
1061 (const :tag "reversed: after tags first" reversed)))))
1062 (if (fboundp 'defvaralias)
1063 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1065 (defcustom org-special-ctrl-k nil
1066 "Non-nil means `C-k' will behave specially in headlines.
1067 When nil, `C-k' will call the default `kill-line' command.
1068 When t, the following will happen while the cursor is in the headline:
1070 - When the cursor is at the beginning of a headline, kill the entire
1071 line and possible the folded subtree below the line.
1072 - When in the middle of the headline text, kill the headline up to the tags.
1073 - When after the headline text, kill the tags."
1074 :group 'org-edit-structure
1075 :type 'boolean)
1077 (defcustom org-ctrl-k-protect-subtree nil
1078 "Non-nil means, do not delete a hidden subtree with C-k.
1079 When set to the symbol `error', simply throw an error when C-k is
1080 used to kill (part-of) a headline that has hidden text behind it.
1081 Any other non-nil value will result in a query to the user, if it is
1082 OK to kill that hidden subtree. When nil, kill without remorse."
1083 :group 'org-edit-structure
1084 :version "24.1"
1085 :type '(choice
1086 (const :tag "Do not protect hidden subtrees" nil)
1087 (const :tag "Protect hidden subtrees with a security query" t)
1088 (const :tag "Never kill a hidden subtree with C-k" error)))
1090 (defcustom org-catch-invisible-edits nil
1091 "Check if in invisible region before inserting or deleting a character.
1092 Valid values are:
1094 nil Do not check, so just do invisible edits.
1095 error Throw an error and do nothing.
1096 show Make point visible, and do the requested edit.
1097 show-and-error Make point visible, then throw an error and abort the edit.
1098 smart Make point visible, and do insertion/deletion if it is
1099 adjacent to visible text and the change feels predictable.
1100 Never delete a previously invisible character or add in the
1101 middle or right after an invisible region. Basically, this
1102 allows insertion and backward-delete right before ellipses.
1103 FIXME: maybe in this case we should not even show?"
1104 :group 'org-edit-structure
1105 :version "24.1"
1106 :type '(choice
1107 (const :tag "Do not check" nil)
1108 (const :tag "Throw error when trying to edit" error)
1109 (const :tag "Unhide, but do not do the edit" show-and-error)
1110 (const :tag "Show invisible part and do the edit" show)
1111 (const :tag "Be smart and do the right thing" smart)))
1113 (defcustom org-yank-folded-subtrees t
1114 "Non-nil means when yanking subtrees, fold them.
1115 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1116 it starts with a heading and all other headings in it are either children
1117 or siblings, then fold all the subtrees. However, do this only if no
1118 text after the yank would be swallowed into a folded tree by this action."
1119 :group 'org-edit-structure
1120 :type 'boolean)
1122 (defcustom org-yank-adjusted-subtrees nil
1123 "Non-nil means when yanking subtrees, adjust the level.
1124 With this setting, `org-paste-subtree' is used to insert the subtree, see
1125 this function for details."
1126 :group 'org-edit-structure
1127 :type 'boolean)
1129 (defcustom org-M-RET-may-split-line '((default . t))
1130 "Non-nil means M-RET will split the line at the cursor position.
1131 When nil, it will go to the end of the line before making a
1132 new line.
1133 You may also set this option in a different way for different
1134 contexts. Valid contexts are:
1136 headline when creating a new headline
1137 item when creating a new item
1138 table in a table field
1139 default the value to be used for all contexts not explicitly
1140 customized"
1141 :group 'org-structure
1142 :group 'org-table
1143 :type '(choice
1144 (const :tag "Always" t)
1145 (const :tag "Never" nil)
1146 (repeat :greedy t :tag "Individual contexts"
1147 (cons
1148 (choice :tag "Context"
1149 (const headline)
1150 (const item)
1151 (const table)
1152 (const default))
1153 (boolean)))))
1156 (defcustom org-insert-heading-respect-content nil
1157 "Non-nil means insert new headings after the current subtree.
1158 When nil, the new heading is created directly after the current line.
1159 The commands \\[org-insert-heading-respect-content] and
1160 \\[org-insert-todo-heading-respect-content] turn this variable on
1161 for the duration of the command."
1162 :group 'org-structure
1163 :type 'boolean)
1165 (defcustom org-blank-before-new-entry '((heading . auto)
1166 (plain-list-item . auto))
1167 "Should `org-insert-heading' leave a blank line before new heading/item?
1168 The value is an alist, with `heading' and `plain-list-item' as CAR,
1169 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1170 which case Org will look at the surrounding headings/items and try to
1171 make an intelligent decision whether to insert a blank line or not.
1173 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1174 set, the setting here is ignored and no empty line is inserted, to avoid
1175 breaking the list structure."
1176 :group 'org-edit-structure
1177 :type '(list
1178 (cons (const heading)
1179 (choice (const :tag "Never" nil)
1180 (const :tag "Always" t)
1181 (const :tag "Auto" auto)))
1182 (cons (const plain-list-item)
1183 (choice (const :tag "Never" nil)
1184 (const :tag "Always" t)
1185 (const :tag "Auto" auto)))))
1187 (defcustom org-insert-heading-hook nil
1188 "Hook being run after inserting a new heading."
1189 :group 'org-edit-structure
1190 :type 'hook)
1192 (defcustom org-enable-fixed-width-editor t
1193 "Non-nil means lines starting with \":\" are treated as fixed-width.
1194 This currently only means they are never auto-wrapped.
1195 When nil, such lines will be treated like ordinary lines.
1196 See also the QUOTE keyword."
1197 :group 'org-edit-structure
1198 :type 'boolean)
1200 (defcustom org-goto-auto-isearch t
1201 "Non-nil means typing characters in `org-goto' starts incremental search."
1202 :group 'org-edit-structure
1203 :type 'boolean)
1205 (defgroup org-sparse-trees nil
1206 "Options concerning sparse trees in Org-mode."
1207 :tag "Org Sparse Trees"
1208 :group 'org-structure)
1210 (defcustom org-highlight-sparse-tree-matches t
1211 "Non-nil means highlight all matches that define a sparse tree.
1212 The highlights will automatically disappear the next time the buffer is
1213 changed by an edit command."
1214 :group 'org-sparse-trees
1215 :type 'boolean)
1217 (defcustom org-remove-highlights-with-change t
1218 "Non-nil means any change to the buffer will remove temporary highlights.
1219 Such highlights are created by `org-occur' and `org-clock-display'.
1220 When nil, `C-c C-c needs to be used to get rid of the highlights.
1221 The highlights created by `org-preview-latex-fragment' always need
1222 `C-c C-c' to be removed."
1223 :group 'org-sparse-trees
1224 :group 'org-time
1225 :type 'boolean)
1228 (defcustom org-occur-hook '(org-first-headline-recenter)
1229 "Hook that is run after `org-occur' has constructed a sparse tree.
1230 This can be used to recenter the window to show as much of the structure
1231 as possible."
1232 :group 'org-sparse-trees
1233 :type 'hook)
1235 (defgroup org-imenu-and-speedbar nil
1236 "Options concerning imenu and speedbar in Org-mode."
1237 :tag "Org Imenu and Speedbar"
1238 :group 'org-structure)
1240 (defcustom org-imenu-depth 2
1241 "The maximum level for Imenu access to Org-mode headlines.
1242 This also applied for speedbar access."
1243 :group 'org-imenu-and-speedbar
1244 :type 'integer)
1246 (defgroup org-table nil
1247 "Options concerning tables in Org-mode."
1248 :tag "Org Table"
1249 :group 'org)
1251 (defcustom org-enable-table-editor 'optimized
1252 "Non-nil means lines starting with \"|\" are handled by the table editor.
1253 When nil, such lines will be treated like ordinary lines.
1255 When equal to the symbol `optimized', the table editor will be optimized to
1256 do the following:
1257 - Automatic overwrite mode in front of whitespace in table fields.
1258 This makes the structure of the table stay in tact as long as the edited
1259 field does not exceed the column width.
1260 - Minimize the number of realigns. Normally, the table is aligned each time
1261 TAB or RET are pressed to move to another field. With optimization this
1262 happens only if changes to a field might have changed the column width.
1263 Optimization requires replacing the functions `self-insert-command',
1264 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1265 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1266 very good at guessing when a re-align will be necessary, but you can always
1267 force one with \\[org-ctrl-c-ctrl-c].
1269 If you would like to use the optimized version in Org-mode, but the
1270 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1272 This variable can be used to turn on and off the table editor during a session,
1273 but in order to toggle optimization, a restart is required.
1275 See also the variable `org-table-auto-blank-field'."
1276 :group 'org-table
1277 :type '(choice
1278 (const :tag "off" nil)
1279 (const :tag "on" t)
1280 (const :tag "on, optimized" optimized)))
1282 (defcustom org-self-insert-cluster-for-undo (version<= emacs-version "24.1")
1283 "Non-nil means cluster self-insert commands for undo when possible.
1284 If this is set, then, like in the Emacs command loop, 20 consecutive
1285 characters will be undone together.
1286 This is configurable, because there is some impact on typing performance."
1287 :group 'org-table
1288 :type 'boolean)
1290 (defcustom org-table-tab-recognizes-table.el t
1291 "Non-nil means TAB will automatically notice a table.el table.
1292 When it sees such a table, it moves point into it and - if necessary -
1293 calls `table-recognize-table'."
1294 :group 'org-table-editing
1295 :type 'boolean)
1297 (defgroup org-link nil
1298 "Options concerning links in Org-mode."
1299 :tag "Org Link"
1300 :group 'org)
1302 (defvar org-link-abbrev-alist-local nil
1303 "Buffer-local version of `org-link-abbrev-alist', which see.
1304 The value of this is taken from the #+LINK lines.")
1305 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1307 (defcustom org-link-abbrev-alist nil
1308 "Alist of link abbreviations.
1309 The car of each element is a string, to be replaced at the start of a link.
1310 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1311 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1313 [[linkkey:tag][description]]
1315 The 'linkkey' must be a word word, starting with a letter, followed
1316 by letters, numbers, '-' or '_'.
1318 If REPLACE is a string, the tag will simply be appended to create the link.
1319 If the string contains \"%s\", the tag will be inserted there. If the string
1320 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1321 at that point (see the function `url-hexify-string'). If the string contains
1322 the specifier \"%(my-function)\", then the custom function `my-function' will
1323 be invoked: this function takes the tag as its only argument and must return
1324 a string.
1326 REPLACE may also be a function that will be called with the tag as the
1327 only argument to create the link, which should be returned as a string.
1329 See the manual for examples."
1330 :group 'org-link
1331 :type '(repeat
1332 (cons
1333 (string :tag "Protocol")
1334 (choice
1335 (string :tag "Format")
1336 (function)))))
1338 (defcustom org-descriptive-links t
1339 "Non-nil means Org will display descriptive links.
1340 E.g. [[http://orgmode.org][Org website]] will be displayed as
1341 \"Org Website\", hiding the link itself and just displaying its
1342 description. When set to `nil', Org will display the full links
1343 literally.
1345 You can interactively set the value of this variable by calling
1346 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1347 :group 'org-link
1348 :type 'boolean)
1350 (defcustom org-link-file-path-type 'adaptive
1351 "How the path name in file links should be stored.
1352 Valid values are:
1354 relative Relative to the current directory, i.e. the directory of the file
1355 into which the link is being inserted.
1356 absolute Absolute path, if possible with ~ for home directory.
1357 noabbrev Absolute path, no abbreviation of home directory.
1358 adaptive Use relative path for files in the current directory and sub-
1359 directories of it. For other files, use an absolute path."
1360 :group 'org-link
1361 :type '(choice
1362 (const relative)
1363 (const absolute)
1364 (const noabbrev)
1365 (const adaptive)))
1367 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1368 "Types of links that should be activated in Org-mode files.
1369 This is a list of symbols, each leading to the activation of a certain link
1370 type. In principle, it does not hurt to turn on most link types - there may
1371 be a small gain when turning off unused link types. The types are:
1373 bracket The recommended [[link][description]] or [[link]] links with hiding.
1374 angle Links in angular brackets that may contain whitespace like
1375 <bbdb:Carsten Dominik>.
1376 plain Plain links in normal text, no whitespace, like http://google.com.
1377 radio Text that is matched by a radio target, see manual for details.
1378 tag Tag settings in a headline (link to tag search).
1379 date Time stamps (link to calendar).
1380 footnote Footnote labels.
1382 Changing this variable requires a restart of Emacs to become effective."
1383 :group 'org-link
1384 :type '(set :greedy t
1385 (const :tag "Double bracket links" bracket)
1386 (const :tag "Angular bracket links" angle)
1387 (const :tag "Plain text links" plain)
1388 (const :tag "Radio target matches" radio)
1389 (const :tag "Tags" tag)
1390 (const :tag "Timestamps" date)
1391 (const :tag "Footnotes" footnote)))
1393 (defcustom org-make-link-description-function nil
1394 "Function to use to generate link descriptions from links.
1395 If nil the link location will be used. This function must take
1396 two parameters; the first is the link and the second the
1397 description `org-insert-link' has generated, and should return the
1398 description to use."
1399 :group 'org-link
1400 :type 'function)
1402 (defgroup org-link-store nil
1403 "Options concerning storing links in Org-mode."
1404 :tag "Org Store Link"
1405 :group 'org-link)
1407 (defcustom org-email-link-description-format "Email %c: %.30s"
1408 "Format of the description part of a link to an email or usenet message.
1409 The following %-escapes will be replaced by corresponding information:
1411 %F full \"From\" field
1412 %f name, taken from \"From\" field, address if no name
1413 %T full \"To\" field
1414 %t first name in \"To\" field, address if no name
1415 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1416 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1417 %s subject
1418 %d date
1419 %m message-id.
1421 You may use normal field width specification between the % and the letter.
1422 This is for example useful to limit the length of the subject.
1424 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1425 :group 'org-link-store
1426 :type 'string)
1428 (defcustom org-from-is-user-regexp
1429 (let (r1 r2)
1430 (when (and user-mail-address (not (string= user-mail-address "")))
1431 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1432 (when (and user-full-name (not (string= user-full-name "")))
1433 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1434 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1435 "Regexp matched against the \"From:\" header of an email or usenet message.
1436 It should match if the message is from the user him/herself."
1437 :group 'org-link-store
1438 :type 'regexp)
1440 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1441 "Non-nil means storing a link to an Org file will use entry IDs.
1443 Note that before this variable is even considered, org-id must be loaded,
1444 so please customize `org-modules' and turn it on.
1446 The variable can have the following values:
1448 t Create an ID if needed to make a link to the current entry.
1450 create-if-interactive
1451 If `org-store-link' is called directly (interactively, as a user
1452 command), do create an ID to support the link. But when doing the
1453 job for remember, only use the ID if it already exists. The
1454 purpose of this setting is to avoid proliferation of unwanted
1455 IDs, just because you happen to be in an Org file when you
1456 call `org-remember' that automatically and preemptively
1457 creates a link. If you do want to get an ID link in a remember
1458 template to an entry not having an ID, create it first by
1459 explicitly creating a link to it, using `C-c C-l' first.
1461 create-if-interactive-and-no-custom-id
1462 Like create-if-interactive, but do not create an ID if there is
1463 a CUSTOM_ID property defined in the entry. This is the default.
1465 use-existing
1466 Use existing ID, do not create one.
1468 nil Never use an ID to make a link, instead link using a text search for
1469 the headline text."
1470 :group 'org-link-store
1471 :type '(choice
1472 (const :tag "Create ID to make link" t)
1473 (const :tag "Create if storing link interactively"
1474 create-if-interactive)
1475 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1476 create-if-interactive-and-no-custom-id)
1477 (const :tag "Only use existing" use-existing)
1478 (const :tag "Do not use ID to create link" nil)))
1480 (defcustom org-context-in-file-links t
1481 "Non-nil means file links from `org-store-link' contain context.
1482 A search string will be added to the file name with :: as separator and
1483 used to find the context when the link is activated by the command
1484 `org-open-at-point'. When this option is t, the entire active region
1485 will be placed in the search string of the file link. If set to a
1486 positive integer, only the first n lines of context will be stored.
1488 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1489 negates this setting for the duration of the command."
1490 :group 'org-link-store
1491 :type '(choice boolean integer))
1493 (defcustom org-keep-stored-link-after-insertion nil
1494 "Non-nil means keep link in list for entire session.
1496 The command `org-store-link' adds a link pointing to the current
1497 location to an internal list. These links accumulate during a session.
1498 The command `org-insert-link' can be used to insert links into any
1499 Org-mode file (offering completion for all stored links). When this
1500 option is nil, every link which has been inserted once using \\[org-insert-link]
1501 will be removed from the list, to make completing the unused links
1502 more efficient."
1503 :group 'org-link-store
1504 :type 'boolean)
1506 (defgroup org-link-follow nil
1507 "Options concerning following links in Org-mode."
1508 :tag "Org Follow Link"
1509 :group 'org-link)
1511 (defcustom org-link-translation-function nil
1512 "Function to translate links with different syntax to Org syntax.
1513 This can be used to translate links created for example by the Planner
1514 or emacs-wiki packages to Org syntax.
1515 The function must accept two parameters, a TYPE containing the link
1516 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1517 which is everything after the link protocol. It should return a cons
1518 with possibly modified values of type and path.
1519 Org contains a function for this, so if you set this variable to
1520 `org-translate-link-from-planner', you should be able follow many
1521 links created by planner."
1522 :group 'org-link-follow
1523 :type 'function)
1525 (defcustom org-follow-link-hook nil
1526 "Hook that is run after a link has been followed."
1527 :group 'org-link-follow
1528 :type 'hook)
1530 (defcustom org-tab-follows-link nil
1531 "Non-nil means on links TAB will follow the link.
1532 Needs to be set before org.el is loaded.
1533 This really should not be used, it does not make sense, and the
1534 implementation is bad."
1535 :group 'org-link-follow
1536 :type 'boolean)
1538 (defcustom org-return-follows-link nil
1539 "Non-nil means on links RET will follow the link."
1540 :group 'org-link-follow
1541 :type 'boolean)
1543 (defcustom org-mouse-1-follows-link
1544 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1545 "Non-nil means mouse-1 on a link will follow the link.
1546 A longer mouse click will still set point. Does not work on XEmacs.
1547 Needs to be set before org.el is loaded."
1548 :group 'org-link-follow
1549 :type 'boolean)
1551 (defcustom org-mark-ring-length 4
1552 "Number of different positions to be recorded in the ring.
1553 Changing this requires a restart of Emacs to work correctly."
1554 :group 'org-link-follow
1555 :type 'integer)
1557 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1558 "Non-nil means internal links in Org files must exactly match a headline.
1559 When nil, the link search tries to match a phrase with all words
1560 in the search text."
1561 :group 'org-link-follow
1562 :version "24.1"
1563 :type '(choice
1564 (const :tag "Use fuzzy text search" nil)
1565 (const :tag "Match only exact headline" t)
1566 (const :tag "Match exact headline or query to create it"
1567 query-to-create)))
1569 (defcustom org-link-frame-setup
1570 '((vm . vm-visit-folder-other-frame)
1571 (vm-imap . vm-visit-imap-folder-other-frame)
1572 (gnus . org-gnus-no-new-news)
1573 (file . find-file-other-window)
1574 (wl . wl-other-frame))
1575 "Setup the frame configuration for following links.
1576 When following a link with Emacs, it may often be useful to display
1577 this link in another window or frame. This variable can be used to
1578 set this up for the different types of links.
1579 For VM, use any of
1580 `vm-visit-folder'
1581 `vm-visit-folder-other-window'
1582 `vm-visit-folder-other-frame'
1583 For Gnus, use any of
1584 `gnus'
1585 `gnus-other-frame'
1586 `org-gnus-no-new-news'
1587 For FILE, use any of
1588 `find-file'
1589 `find-file-other-window'
1590 `find-file-other-frame'
1591 For Wanderlust use any of
1592 `wl'
1593 `wl-other-frame'
1594 For the calendar, use the variable `calendar-setup'.
1595 For BBDB, it is currently only possible to display the matches in
1596 another window."
1597 :group 'org-link-follow
1598 :type '(list
1599 (cons (const vm)
1600 (choice
1601 (const vm-visit-folder)
1602 (const vm-visit-folder-other-window)
1603 (const vm-visit-folder-other-frame)))
1604 (cons (const gnus)
1605 (choice
1606 (const gnus)
1607 (const gnus-other-frame)
1608 (const org-gnus-no-new-news)))
1609 (cons (const file)
1610 (choice
1611 (const find-file)
1612 (const find-file-other-window)
1613 (const find-file-other-frame)))
1614 (cons (const wl)
1615 (choice
1616 (const wl)
1617 (const wl-other-frame)))))
1619 (defcustom org-display-internal-link-with-indirect-buffer nil
1620 "Non-nil means use indirect buffer to display infile links.
1621 Activating internal links (from one location in a file to another location
1622 in the same file) normally just jumps to the location. When the link is
1623 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1624 is displayed in
1625 another window. When this option is set, the other window actually displays
1626 an indirect buffer clone of the current buffer, to avoid any visibility
1627 changes to the current buffer."
1628 :group 'org-link-follow
1629 :type 'boolean)
1631 (defcustom org-open-non-existing-files nil
1632 "Non-nil means `org-open-file' will open non-existing files.
1633 When nil, an error will be generated.
1634 This variable applies only to external applications because they
1635 might choke on non-existing files. If the link is to a file that
1636 will be opened in Emacs, the variable is ignored."
1637 :group 'org-link-follow
1638 :type 'boolean)
1640 (defcustom org-open-directory-means-index-dot-org nil
1641 "Non-nil means a link to a directory really means to index.org.
1642 When nil, following a directory link will run dired or open a finder/explorer
1643 window on that directory."
1644 :group 'org-link-follow
1645 :type 'boolean)
1647 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1648 "Function and arguments to call for following mailto links.
1649 This is a list with the first element being a Lisp function, and the
1650 remaining elements being arguments to the function. In string arguments,
1651 %a will be replaced by the address, and %s will be replaced by the subject
1652 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1653 :group 'org-link-follow
1654 :type '(choice
1655 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1656 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1657 (const :tag "message-mail" (message-mail "%a" "%s"))
1658 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1660 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1661 "Non-nil means ask for confirmation before executing shell links.
1662 Shell links can be dangerous: just think about a link
1664 [[shell:rm -rf ~/*][Google Search]]
1666 This link would show up in your Org-mode document as \"Google Search\",
1667 but really it would remove your entire home directory.
1668 Therefore we advise against setting this variable to nil.
1669 Just change it to `y-or-n-p' if you want to confirm with a
1670 single keystroke rather than having to type \"yes\"."
1671 :group 'org-link-follow
1672 :type '(choice
1673 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1674 (const :tag "with y-or-n (faster)" y-or-n-p)
1675 (const :tag "no confirmation (dangerous)" nil)))
1676 (put 'org-confirm-shell-link-function
1677 'safe-local-variable
1678 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1680 (defcustom org-confirm-shell-link-not-regexp ""
1681 "A regexp to skip confirmation for shell links."
1682 :group 'org-link-follow
1683 :version "24.1"
1684 :type 'regexp)
1686 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1687 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1688 Elisp links can be dangerous: just think about a link
1690 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1692 This link would show up in your Org-mode document as \"Google Search\",
1693 but really it would remove your entire home directory.
1694 Therefore we advise against setting this variable to nil.
1695 Just change it to `y-or-n-p' if you want to confirm with a
1696 single keystroke rather than having to type \"yes\"."
1697 :group 'org-link-follow
1698 :type '(choice
1699 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1700 (const :tag "with y-or-n (faster)" y-or-n-p)
1701 (const :tag "no confirmation (dangerous)" nil)))
1702 (put 'org-confirm-shell-link-function
1703 'safe-local-variable
1704 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1706 (defcustom org-confirm-elisp-link-not-regexp ""
1707 "A regexp to skip confirmation for Elisp links."
1708 :group 'org-link-follow
1709 :version "24.1"
1710 :type 'regexp)
1712 (defconst org-file-apps-defaults-gnu
1713 '((remote . emacs)
1714 (system . mailcap)
1715 (t . mailcap))
1716 "Default file applications on a UNIX or GNU/Linux system.
1717 See `org-file-apps'.")
1719 (defconst org-file-apps-defaults-macosx
1720 '((remote . emacs)
1721 (t . "open %s")
1722 (system . "open %s")
1723 ("ps.gz" . "gv %s")
1724 ("eps.gz" . "gv %s")
1725 ("dvi" . "xdvi %s")
1726 ("fig" . "xfig %s"))
1727 "Default file applications on a MacOS X system.
1728 The system \"open\" is known as a default, but we use X11 applications
1729 for some files for which the OS does not have a good default.
1730 See `org-file-apps'.")
1732 (defconst org-file-apps-defaults-windowsnt
1733 (list
1734 '(remote . emacs)
1735 (cons t
1736 (list (if (featurep 'xemacs)
1737 'mswindows-shell-execute
1738 'w32-shell-execute)
1739 "open" 'file))
1740 (cons 'system
1741 (list (if (featurep 'xemacs)
1742 'mswindows-shell-execute
1743 'w32-shell-execute)
1744 "open" 'file)))
1745 "Default file applications on a Windows NT system.
1746 The system \"open\" is used for most files.
1747 See `org-file-apps'.")
1749 (defcustom org-file-apps
1751 (auto-mode . emacs)
1752 ("\\.mm\\'" . default)
1753 ("\\.x?html?\\'" . default)
1754 ("\\.pdf\\'" . default)
1756 "External applications for opening `file:path' items in a document.
1757 Org-mode uses system defaults for different file types, but
1758 you can use this variable to set the application for a given file
1759 extension. The entries in this list are cons cells where the car identifies
1760 files and the cdr the corresponding command. Possible values for the
1761 file identifier are
1762 \"string\" A string as a file identifier can be interpreted in different
1763 ways, depending on its contents:
1765 - Alphanumeric characters only:
1766 Match links with this file extension.
1767 Example: (\"pdf\" . \"evince %s\")
1768 to open PDFs with evince.
1770 - Regular expression: Match links where the
1771 filename matches the regexp. If you want to
1772 use groups here, use shy groups.
1774 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1775 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1776 to open *.html and *.xhtml with firefox.
1778 - Regular expression which contains (non-shy) groups:
1779 Match links where the whole link, including \"::\", and
1780 anything after that, matches the regexp.
1781 In a custom command string, %1, %2, etc. are replaced with
1782 the parts of the link that were matched by the groups.
1783 For backwards compatibility, if a command string is given
1784 that does not use any of the group matches, this case is
1785 handled identically to the second one (i.e. match against
1786 file name only).
1787 In a custom lisp form, you can access the group matches with
1788 (match-string n link).
1790 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1791 to open [[file:document.pdf::5]] with evince at page 5.
1793 `directory' Matches a directory
1794 `remote' Matches a remote file, accessible through tramp or efs.
1795 Remote files most likely should be visited through Emacs
1796 because external applications cannot handle such paths.
1797 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1798 so all files Emacs knows how to handle. Using this with
1799 command `emacs' will open most files in Emacs. Beware that this
1800 will also open html files inside Emacs, unless you add
1801 (\"html\" . default) to the list as well.
1802 t Default for files not matched by any of the other options.
1803 `system' The system command to open files, like `open' on Windows
1804 and Mac OS X, and mailcap under GNU/Linux. This is the command
1805 that will be selected if you call `C-c C-o' with a double
1806 \\[universal-argument] \\[universal-argument] prefix.
1808 Possible values for the command are:
1809 `emacs' The file will be visited by the current Emacs process.
1810 `default' Use the default application for this file type, which is the
1811 association for t in the list, most likely in the system-specific
1812 part.
1813 This can be used to overrule an unwanted setting in the
1814 system-specific variable.
1815 `system' Use the system command for opening files, like \"open\".
1816 This command is specified by the entry whose car is `system'.
1817 Most likely, the system-specific version of this variable
1818 does define this command, but you can overrule/replace it
1819 here.
1820 string A command to be executed by a shell; %s will be replaced
1821 by the path to the file.
1822 sexp A Lisp form which will be evaluated. The file path will
1823 be available in the Lisp variable `file'.
1824 For more examples, see the system specific constants
1825 `org-file-apps-defaults-macosx'
1826 `org-file-apps-defaults-windowsnt'
1827 `org-file-apps-defaults-gnu'."
1828 :group 'org-link-follow
1829 :type '(repeat
1830 (cons (choice :value ""
1831 (string :tag "Extension")
1832 (const :tag "System command to open files" system)
1833 (const :tag "Default for unrecognized files" t)
1834 (const :tag "Remote file" remote)
1835 (const :tag "Links to a directory" directory)
1836 (const :tag "Any files that have Emacs modes"
1837 auto-mode))
1838 (choice :value ""
1839 (const :tag "Visit with Emacs" emacs)
1840 (const :tag "Use default" default)
1841 (const :tag "Use the system command" system)
1842 (string :tag "Command")
1843 (sexp :tag "Lisp form")))))
1845 (defcustom org-doi-server-url "http://dx.doi.org/"
1846 "The URL of the DOI server."
1847 :type 'string
1848 :version "24.2"
1849 :group 'org-link-follow)
1851 (defgroup org-refile nil
1852 "Options concerning refiling entries in Org-mode."
1853 :tag "Org Refile"
1854 :group 'org)
1856 (defcustom org-directory "~/org"
1857 "Directory with org files.
1858 This is just a default location to look for Org files. There is no need
1859 at all to put your files into this directory. It is only used in the
1860 following situations:
1862 1. When a remember template specifies a target file that is not an
1863 absolute path. The path will then be interpreted relative to
1864 `org-directory'
1865 2. When a remember note is filed away in an interactive way (when exiting the
1866 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1867 with `org-directory' as the default path."
1868 :group 'org-refile
1869 :group 'org-remember
1870 :type 'directory)
1872 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1873 "Default target for storing notes.
1874 Used as a fall back file for org-remember.el and org-capture.el, for
1875 templates that do not specify a target file."
1876 :group 'org-refile
1877 :group 'org-remember
1878 :type '(choice
1879 (const :tag "Default from remember-data-file" nil)
1880 file))
1882 (defcustom org-goto-interface 'outline
1883 "The default interface to be used for `org-goto'.
1884 Allowed values are:
1885 outline The interface shows an outline of the relevant file
1886 and the correct heading is found by moving through
1887 the outline or by searching with incremental search.
1888 outline-path-completion Headlines in the current buffer are offered via
1889 completion. This is the interface also used by
1890 the refile command."
1891 :group 'org-refile
1892 :type '(choice
1893 (const :tag "Outline" outline)
1894 (const :tag "Outline-path-completion" outline-path-completion)))
1896 (defcustom org-goto-max-level 5
1897 "Maximum target level when running `org-goto' with refile interface."
1898 :group 'org-refile
1899 :type 'integer)
1901 (defcustom org-reverse-note-order nil
1902 "Non-nil means store new notes at the beginning of a file or entry.
1903 When nil, new notes will be filed to the end of a file or entry.
1904 This can also be a list with cons cells of regular expressions that
1905 are matched against file names, and values."
1906 :group 'org-remember
1907 :group 'org-refile
1908 :type '(choice
1909 (const :tag "Reverse always" t)
1910 (const :tag "Reverse never" nil)
1911 (repeat :tag "By file name regexp"
1912 (cons regexp boolean))))
1914 (defcustom org-log-refile nil
1915 "Information to record when a task is refiled.
1917 Possible values are:
1919 nil Don't add anything
1920 time Add a time stamp to the task
1921 note Prompt for a note and add it with template `org-log-note-headings'
1923 This option can also be set with on a per-file-basis with
1925 #+STARTUP: nologrefile
1926 #+STARTUP: logrefile
1927 #+STARTUP: lognoterefile
1929 You can have local logging settings for a subtree by setting the LOGGING
1930 property to one or more of these keywords.
1932 When bulk-refiling from the agenda, the value `note' is forbidden and
1933 will temporarily be changed to `time'."
1934 :group 'org-refile
1935 :group 'org-progress
1936 :version "24.1"
1937 :type '(choice
1938 (const :tag "No logging" nil)
1939 (const :tag "Record timestamp" time)
1940 (const :tag "Record timestamp with note." note)))
1942 (defcustom org-refile-targets nil
1943 "Targets for refiling entries with \\[org-refile].
1944 This is a list of cons cells. Each cell contains:
1945 - a specification of the files to be considered, either a list of files,
1946 or a symbol whose function or variable value will be used to retrieve
1947 a file name or a list of file names. If you use `org-agenda-files' for
1948 that, all agenda files will be scanned for targets. Nil means consider
1949 headings in the current buffer.
1950 - A specification of how to find candidate refile targets. This may be
1951 any of:
1952 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1953 This tag has to be present in all target headlines, inheritance will
1954 not be considered.
1955 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1956 todo keyword.
1957 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1958 headlines that are refiling targets.
1959 - a cons cell (:level . N). Any headline of level N is considered a target.
1960 Note that, when `org-odd-levels-only' is set, level corresponds to
1961 order in hierarchy, not to the number of stars.
1962 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1963 Note that, when `org-odd-levels-only' is set, level corresponds to
1964 order in hierarchy, not to the number of stars.
1966 Each element of this list generates a set of possible targets.
1967 The union of these sets is presented (with completion) to
1968 the user by `org-refile'.
1970 You can set the variable `org-refile-target-verify-function' to a function
1971 to verify each headline found by the simple criteria above.
1973 When this variable is nil, all top-level headlines in the current buffer
1974 are used, equivalent to the value `((nil . (:level . 1))'."
1975 :group 'org-refile
1976 :type '(repeat
1977 (cons
1978 (choice :value org-agenda-files
1979 (const :tag "All agenda files" org-agenda-files)
1980 (const :tag "Current buffer" nil)
1981 (function) (variable) (file))
1982 (choice :tag "Identify target headline by"
1983 (cons :tag "Specific tag" (const :value :tag) (string))
1984 (cons :tag "TODO keyword" (const :value :todo) (string))
1985 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1986 (cons :tag "Level number" (const :value :level) (integer))
1987 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1989 (defcustom org-refile-target-verify-function nil
1990 "Function to verify if the headline at point should be a refile target.
1991 The function will be called without arguments, with point at the
1992 beginning of the headline. It should return t and leave point
1993 where it is if the headline is a valid target for refiling.
1995 If the target should not be selected, the function must return nil.
1996 In addition to this, it may move point to a place from where the search
1997 should be continued. For example, the function may decide that the entire
1998 subtree of the current entry should be excluded and move point to the end
1999 of the subtree."
2000 :group 'org-refile
2001 :type 'function)
2003 (defcustom org-refile-use-cache nil
2004 "Non-nil means cache refile targets to speed up the process.
2005 The cache for a particular file will be updated automatically when
2006 the buffer has been killed, or when any of the marker used for flagging
2007 refile targets no longer points at a live buffer.
2008 If you have added new entries to a buffer that might themselves be targets,
2009 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2010 find that easier, `C-u C-u C-u C-c C-w'."
2011 :group 'org-refile
2012 :version "24.1"
2013 :type 'boolean)
2015 (defcustom org-refile-use-outline-path nil
2016 "Non-nil means provide refile targets as paths.
2017 So a level 3 headline will be available as level1/level2/level3.
2019 When the value is `file', also include the file name (without directory)
2020 into the path. In this case, you can also stop the completion after
2021 the file name, to get entries inserted as top level in the file.
2023 When `full-file-path', include the full file path."
2024 :group 'org-refile
2025 :type '(choice
2026 (const :tag "Not" nil)
2027 (const :tag "Yes" t)
2028 (const :tag "Start with file name" file)
2029 (const :tag "Start with full file path" full-file-path)))
2031 (defcustom org-outline-path-complete-in-steps t
2032 "Non-nil means complete the outline path in hierarchical steps.
2033 When Org-mode uses the refile interface to select an outline path
2034 \(see variable `org-refile-use-outline-path'), the completion of
2035 the path can be done is a single go, or if can be done in steps down
2036 the headline hierarchy. Going in steps is probably the best if you
2037 do not use a special completion package like `ido' or `icicles'.
2038 However, when using these packages, going in one step can be very
2039 fast, while still showing the whole path to the entry."
2040 :group 'org-refile
2041 :type 'boolean)
2043 (defcustom org-refile-allow-creating-parent-nodes nil
2044 "Non-nil means allow to create new nodes as refile targets.
2045 New nodes are then created by adding \"/new node name\" to the completion
2046 of an existing node. When the value of this variable is `confirm',
2047 new node creation must be confirmed by the user (recommended)
2048 When nil, the completion must match an existing entry.
2050 Note that, if the new heading is not seen by the criteria
2051 listed in `org-refile-targets', multiple instances of the same
2052 heading would be created by trying again to file under the new
2053 heading."
2054 :group 'org-refile
2055 :type '(choice
2056 (const :tag "Never" nil)
2057 (const :tag "Always" t)
2058 (const :tag "Prompt for confirmation" confirm)))
2060 (defcustom org-refile-active-region-within-subtree nil
2061 "Non-nil means also refile active region within a subtree.
2063 By default `org-refile' doesn't allow refiling regions if they
2064 don't contain a set of subtrees, but it might be convenient to
2065 do so sometimes: in that case, the first line of the region is
2066 converted to a headline before refiling."
2067 :group 'org-refile
2068 :version "24.1"
2069 :type 'boolean)
2071 (defgroup org-todo nil
2072 "Options concerning TODO items in Org-mode."
2073 :tag "Org TODO"
2074 :group 'org)
2076 (defgroup org-progress nil
2077 "Options concerning Progress logging in Org-mode."
2078 :tag "Org Progress"
2079 :group 'org-time)
2081 (defvar org-todo-interpretation-widgets
2082 '((:tag "Sequence (cycling hits every state)" sequence)
2083 (:tag "Type (cycling directly to DONE)" type))
2084 "The available interpretation symbols for customizing `org-todo-keywords'.
2085 Interested libraries should add to this list.")
2087 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2088 "List of TODO entry keyword sequences and their interpretation.
2089 \\<org-mode-map>This is a list of sequences.
2091 Each sequence starts with a symbol, either `sequence' or `type',
2092 indicating if the keywords should be interpreted as a sequence of
2093 action steps, or as different types of TODO items. The first
2094 keywords are states requiring action - these states will select a headline
2095 for inclusion into the global TODO list Org-mode produces. If one of
2096 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2097 signify that no further action is necessary. If \"|\" is not found,
2098 the last keyword is treated as the only DONE state of the sequence.
2100 The command \\[org-todo] cycles an entry through these states, and one
2101 additional state where no keyword is present. For details about this
2102 cycling, see the manual.
2104 TODO keywords and interpretation can also be set on a per-file basis with
2105 the special #+SEQ_TODO and #+TYP_TODO lines.
2107 Each keyword can optionally specify a letter for fast state selection
2108 \(in combination with the variable `org-use-fast-todo-selection')
2109 and specifiers for state change logging, using the same syntax that
2110 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2111 the WAIT state can be selected with the \"w\" letter. \"WAIT(w!)\"
2112 indicates to record a time stamp each time this state is selected.
2114 Each keyword may also specify if a timestamp or a note should be
2115 recorded when entering or leaving the state, by adding additional
2116 characters in the parenthesis after the keyword. This looks like this:
2117 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2118 record only the time of the state change. With X and Y being either
2119 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2120 Y when leaving the state if and only if the *target* state does not
2121 define X. You may omit any of the fast-selection key or X or /Y,
2122 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2124 For backward compatibility, this variable may also be just a list
2125 of keywords. In this case the interpretation (sequence or type) will be
2126 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2127 :group 'org-todo
2128 :group 'org-keywords
2129 :type '(choice
2130 (repeat :tag "Old syntax, just keywords"
2131 (string :tag "Keyword"))
2132 (repeat :tag "New syntax"
2133 (cons
2134 (choice
2135 :tag "Interpretation"
2136 ;;Quick and dirty way to see
2137 ;;`org-todo-interpretations'. This takes the
2138 ;;place of item arguments
2139 :convert-widget
2140 (lambda (widget)
2141 (widget-put widget
2142 :args (mapcar
2143 #'(lambda (x)
2144 (widget-convert
2145 (cons 'const x)))
2146 org-todo-interpretation-widgets))
2147 widget))
2148 (repeat
2149 (string :tag "Keyword"))))))
2151 (defvar org-todo-keywords-1 nil
2152 "All TODO and DONE keywords active in a buffer.")
2153 (make-variable-buffer-local 'org-todo-keywords-1)
2154 (defvar org-todo-keywords-for-agenda nil)
2155 (defvar org-done-keywords-for-agenda nil)
2156 (defvar org-drawers-for-agenda nil)
2157 (defvar org-todo-keyword-alist-for-agenda nil)
2158 (defvar org-tag-alist-for-agenda nil)
2159 (defvar org-agenda-contributing-files nil)
2160 (defvar org-not-done-keywords nil)
2161 (make-variable-buffer-local 'org-not-done-keywords)
2162 (defvar org-done-keywords nil)
2163 (make-variable-buffer-local 'org-done-keywords)
2164 (defvar org-todo-heads nil)
2165 (make-variable-buffer-local 'org-todo-heads)
2166 (defvar org-todo-sets nil)
2167 (make-variable-buffer-local 'org-todo-sets)
2168 (defvar org-todo-log-states nil)
2169 (make-variable-buffer-local 'org-todo-log-states)
2170 (defvar org-todo-kwd-alist nil)
2171 (make-variable-buffer-local 'org-todo-kwd-alist)
2172 (defvar org-todo-key-alist nil)
2173 (make-variable-buffer-local 'org-todo-key-alist)
2174 (defvar org-todo-key-trigger nil)
2175 (make-variable-buffer-local 'org-todo-key-trigger)
2177 (defcustom org-todo-interpretation 'sequence
2178 "Controls how TODO keywords are interpreted.
2179 This variable is in principle obsolete and is only used for
2180 backward compatibility, if the interpretation of todo keywords is
2181 not given already in `org-todo-keywords'. See that variable for
2182 more information."
2183 :group 'org-todo
2184 :group 'org-keywords
2185 :type '(choice (const sequence)
2186 (const type)))
2188 (defcustom org-use-fast-todo-selection t
2189 "Non-nil means use the fast todo selection scheme with C-c C-t.
2190 This variable describes if and under what circumstances the cycling
2191 mechanism for TODO keywords will be replaced by a single-key, direct
2192 selection scheme.
2194 When nil, fast selection is never used.
2196 When the symbol `prefix', it will be used when `org-todo' is called
2197 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2198 `C-u t' in an agenda buffer.
2200 When t, fast selection is used by default. In this case, the prefix
2201 argument forces cycling instead.
2203 In all cases, the special interface is only used if access keys have
2204 actually been assigned by the user, i.e. if keywords in the configuration
2205 are followed by a letter in parenthesis, like TODO(t)."
2206 :group 'org-todo
2207 :type '(choice
2208 (const :tag "Never" nil)
2209 (const :tag "By default" t)
2210 (const :tag "Only with C-u C-c C-t" prefix)))
2212 (defcustom org-provide-todo-statistics t
2213 "Non-nil means update todo statistics after insert and toggle.
2214 ALL-HEADLINES means update todo statistics by including headlines
2215 with no TODO keyword as well, counting them as not done.
2216 A list of TODO keywords means the same, but skip keywords that are
2217 not in this list.
2219 When this is set, todo statistics is updated in the parent of the
2220 current entry each time a todo state is changed."
2221 :group 'org-todo
2222 :type '(choice
2223 (const :tag "Yes, only for TODO entries" t)
2224 (const :tag "Yes, including all entries" 'all-headlines)
2225 (repeat :tag "Yes, for TODOs in this list"
2226 (string :tag "TODO keyword"))
2227 (other :tag "No TODO statistics" nil)))
2229 (defcustom org-hierarchical-todo-statistics t
2230 "Non-nil means TODO statistics covers just direct children.
2231 When nil, all entries in the subtree are considered.
2232 This has only an effect if `org-provide-todo-statistics' is set.
2233 To set this to nil for only a single subtree, use a COOKIE_DATA
2234 property and include the word \"recursive\" into the value."
2235 :group 'org-todo
2236 :type 'boolean)
2238 (defcustom org-after-todo-state-change-hook nil
2239 "Hook which is run after the state of a TODO item was changed.
2240 The new state (a string with a TODO keyword, or nil) is available in the
2241 Lisp variable `org-state'."
2242 :group 'org-todo
2243 :type 'hook)
2245 (defvar org-blocker-hook nil
2246 "Hook for functions that are allowed to block a state change.
2248 Each function gets as its single argument a property list, see
2249 `org-trigger-hook' for more information about this list.
2251 If any of the functions in this hook returns nil, the state change
2252 is blocked.")
2254 (defvar org-trigger-hook nil
2255 "Hook for functions that are triggered by a state change.
2257 Each function gets as its single argument a property list with at least
2258 the following elements:
2260 (:type type-of-change :position pos-at-entry-start
2261 :from old-state :to new-state)
2263 Depending on the type, more properties may be present.
2265 This mechanism is currently implemented for:
2267 TODO state changes
2268 ------------------
2269 :type todo-state-change
2270 :from previous state (keyword as a string), or nil, or a symbol
2271 'todo' or 'done', to indicate the general type of state.
2272 :to new state, like in :from")
2274 (defcustom org-enforce-todo-dependencies nil
2275 "Non-nil means undone TODO entries will block switching the parent to DONE.
2276 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2277 be blocked if any prior sibling is not yet done.
2278 Finally, if the parent is blocked because of ordered siblings of its own,
2279 the child will also be blocked."
2280 :set (lambda (var val)
2281 (set var val)
2282 (if val
2283 (add-hook 'org-blocker-hook
2284 'org-block-todo-from-children-or-siblings-or-parent)
2285 (remove-hook 'org-blocker-hook
2286 'org-block-todo-from-children-or-siblings-or-parent)))
2287 :group 'org-todo
2288 :type 'boolean)
2290 (defcustom org-enforce-todo-checkbox-dependencies nil
2291 "Non-nil means unchecked boxes will block switching the parent to DONE.
2292 When this is nil, checkboxes have no influence on switching TODO states.
2293 When non-nil, you first need to check off all check boxes before the TODO
2294 entry can be switched to DONE.
2295 This variable needs to be set before org.el is loaded, and you need to
2296 restart Emacs after a change to make the change effective. The only way
2297 to change is while Emacs is running is through the customize interface."
2298 :set (lambda (var val)
2299 (set var val)
2300 (if val
2301 (add-hook 'org-blocker-hook
2302 'org-block-todo-from-checkboxes)
2303 (remove-hook 'org-blocker-hook
2304 'org-block-todo-from-checkboxes)))
2305 :group 'org-todo
2306 :type 'boolean)
2308 (defcustom org-treat-insert-todo-heading-as-state-change nil
2309 "Non-nil means inserting a TODO heading is treated as state change.
2310 So when the command \\[org-insert-todo-heading] is used, state change
2311 logging will apply if appropriate. When nil, the new TODO item will
2312 be inserted directly, and no logging will take place."
2313 :group 'org-todo
2314 :type 'boolean)
2316 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2317 "Non-nil means switching TODO states with S-cursor counts as state change.
2318 This is the default behavior. However, setting this to nil allows a
2319 convenient way to select a TODO state and bypass any logging associated
2320 with that."
2321 :group 'org-todo
2322 :type 'boolean)
2324 (defcustom org-todo-state-tags-triggers nil
2325 "Tag changes that should be triggered by TODO state changes.
2326 This is a list. Each entry is
2328 (state-change (tag . flag) .......)
2330 State-change can be a string with a state, and empty string to indicate the
2331 state that has no TODO keyword, or it can be one of the symbols `todo'
2332 or `done', meaning any not-done or done state, respectively."
2333 :group 'org-todo
2334 :group 'org-tags
2335 :type '(repeat
2336 (cons (choice :tag "When changing to"
2337 (const :tag "Not-done state" todo)
2338 (const :tag "Done state" done)
2339 (string :tag "State"))
2340 (repeat
2341 (cons :tag "Tag action"
2342 (string :tag "Tag")
2343 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2345 (defcustom org-log-done nil
2346 "Information to record when a task moves to the DONE state.
2348 Possible values are:
2350 nil Don't add anything, just change the keyword
2351 time Add a time stamp to the task
2352 note Prompt for a note and add it with template `org-log-note-headings'
2354 This option can also be set with on a per-file-basis with
2356 #+STARTUP: nologdone
2357 #+STARTUP: logdone
2358 #+STARTUP: lognotedone
2360 You can have local logging settings for a subtree by setting the LOGGING
2361 property to one or more of these keywords."
2362 :group 'org-todo
2363 :group 'org-progress
2364 :type '(choice
2365 (const :tag "No logging" nil)
2366 (const :tag "Record CLOSED timestamp" time)
2367 (const :tag "Record CLOSED timestamp with note." note)))
2369 ;; Normalize old uses of org-log-done.
2370 (cond
2371 ((eq org-log-done t) (setq org-log-done 'time))
2372 ((and (listp org-log-done) (memq 'done org-log-done))
2373 (setq org-log-done 'note)))
2375 (defcustom org-log-reschedule nil
2376 "Information to record when the scheduling date of a tasks is modified.
2378 Possible values are:
2380 nil Don't add anything, just change the date
2381 time Add a time stamp to the task
2382 note Prompt for a note and add it with template `org-log-note-headings'
2384 This option can also be set with on a per-file-basis with
2386 #+STARTUP: nologreschedule
2387 #+STARTUP: logreschedule
2388 #+STARTUP: lognotereschedule"
2389 :group 'org-todo
2390 :group 'org-progress
2391 :type '(choice
2392 (const :tag "No logging" nil)
2393 (const :tag "Record timestamp" time)
2394 (const :tag "Record timestamp with note." note)))
2396 (defcustom org-log-redeadline nil
2397 "Information to record when the deadline date of a tasks is modified.
2399 Possible values are:
2401 nil Don't add anything, just change the date
2402 time Add a time stamp to the task
2403 note Prompt for a note and add it with template `org-log-note-headings'
2405 This option can also be set with on a per-file-basis with
2407 #+STARTUP: nologredeadline
2408 #+STARTUP: logredeadline
2409 #+STARTUP: lognoteredeadline
2411 You can have local logging settings for a subtree by setting the LOGGING
2412 property to one or more of these keywords."
2413 :group 'org-todo
2414 :group 'org-progress
2415 :type '(choice
2416 (const :tag "No logging" nil)
2417 (const :tag "Record timestamp" time)
2418 (const :tag "Record timestamp with note." note)))
2420 (defcustom org-log-note-clock-out nil
2421 "Non-nil means record a note when clocking out of an item.
2422 This can also be configured on a per-file basis by adding one of
2423 the following lines anywhere in the buffer:
2425 #+STARTUP: lognoteclock-out
2426 #+STARTUP: nolognoteclock-out"
2427 :group 'org-todo
2428 :group 'org-progress
2429 :type 'boolean)
2431 (defcustom org-log-done-with-time t
2432 "Non-nil means the CLOSED time stamp will contain date and time.
2433 When nil, only the date will be recorded."
2434 :group 'org-progress
2435 :type 'boolean)
2437 (defcustom org-log-note-headings
2438 '((done . "CLOSING NOTE %t")
2439 (state . "State %-12s from %-12S %t")
2440 (note . "Note taken on %t")
2441 (reschedule . "Rescheduled from %S on %t")
2442 (delschedule . "Not scheduled, was %S on %t")
2443 (redeadline . "New deadline from %S on %t")
2444 (deldeadline . "Removed deadline, was %S on %t")
2445 (refile . "Refiled on %t")
2446 (clock-out . ""))
2447 "Headings for notes added to entries.
2448 The value is an alist, with the car being a symbol indicating the note
2449 context, and the cdr is the heading to be used. The heading may also be the
2450 empty string.
2451 %t in the heading will be replaced by a time stamp.
2452 %T will be an active time stamp instead the default inactive one
2453 %d will be replaced by a short-format time stamp.
2454 %D will be replaced by an active short-format time stamp.
2455 %s will be replaced by the new TODO state, in double quotes.
2456 %S will be replaced by the old TODO state, in double quotes.
2457 %u will be replaced by the user name.
2458 %U will be replaced by the full user name.
2460 In fact, it is not a good idea to change the `state' entry, because
2461 agenda log mode depends on the format of these entries."
2462 :group 'org-todo
2463 :group 'org-progress
2464 :type '(list :greedy t
2465 (cons (const :tag "Heading when closing an item" done) string)
2466 (cons (const :tag
2467 "Heading when changing todo state (todo sequence only)"
2468 state) string)
2469 (cons (const :tag "Heading when just taking a note" note) string)
2470 (cons (const :tag "Heading when clocking out" clock-out) string)
2471 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2472 (cons (const :tag "Heading when rescheduling" reschedule) string)
2473 (cons (const :tag "Heading when changing deadline" redeadline) string)
2474 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2475 (cons (const :tag "Heading when refiling" refile) string)))
2477 (unless (assq 'note org-log-note-headings)
2478 (push '(note . "%t") org-log-note-headings))
2480 (defcustom org-log-into-drawer nil
2481 "Non-nil means insert state change notes and time stamps into a drawer.
2482 When nil, state changes notes will be inserted after the headline and
2483 any scheduling and clock lines, but not inside a drawer.
2485 The value of this variable should be the name of the drawer to use.
2486 LOGBOOK is proposed as the default drawer for this purpose, you can
2487 also set this to a string to define the drawer of your choice.
2489 A value of t is also allowed, representing \"LOGBOOK\".
2491 If this variable is set, `org-log-state-notes-insert-after-drawers'
2492 will be ignored.
2494 You can set the property LOG_INTO_DRAWER to overrule this setting for
2495 a subtree."
2496 :group 'org-todo
2497 :group 'org-progress
2498 :type '(choice
2499 (const :tag "Not into a drawer" nil)
2500 (const :tag "LOGBOOK" t)
2501 (string :tag "Other")))
2503 (if (fboundp 'defvaralias)
2504 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2506 (defun org-log-into-drawer ()
2507 "Return the value of `org-log-into-drawer', but let properties overrule.
2508 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2509 used instead of the default value."
2510 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2511 (cond
2512 ((or (not p) (equal p "nil")) org-log-into-drawer)
2513 ((equal p "t") "LOGBOOK")
2514 (t p))))
2516 (defcustom org-log-state-notes-insert-after-drawers nil
2517 "Non-nil means insert state change notes after any drawers in entry.
2518 Only the drawers that *immediately* follow the headline and the
2519 deadline/scheduled line are skipped.
2520 When nil, insert notes right after the heading and perhaps the line
2521 with deadline/scheduling if present.
2523 This variable will have no effect if `org-log-into-drawer' is
2524 set."
2525 :group 'org-todo
2526 :group 'org-progress
2527 :type 'boolean)
2529 (defcustom org-log-states-order-reversed t
2530 "Non-nil means the latest state note will be directly after heading.
2531 When nil, the state change notes will be ordered according to time."
2532 :group 'org-todo
2533 :group 'org-progress
2534 :type 'boolean)
2536 (defcustom org-todo-repeat-to-state nil
2537 "The TODO state to which a repeater should return the repeating task.
2538 By default this is the first task in a TODO sequence, or the previous state
2539 in a TODO_TYP set. But you can specify another task here.
2540 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2541 :group 'org-todo
2542 :version "24.1"
2543 :type '(choice (const :tag "Head of sequence" nil)
2544 (string :tag "Specific state")))
2546 (defcustom org-log-repeat 'time
2547 "Non-nil means record moving through the DONE state when triggering repeat.
2548 An auto-repeating task is immediately switched back to TODO when
2549 marked DONE. If you are not logging state changes (by adding \"@\"
2550 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2551 record a closing note, there will be no record of the task moving
2552 through DONE. This variable forces taking a note anyway.
2554 nil Don't force a record
2555 time Record a time stamp
2556 note Record a note
2558 This option can also be set with on a per-file-basis with
2560 #+STARTUP: logrepeat
2561 #+STARTUP: lognoterepeat
2562 #+STARTUP: nologrepeat
2564 You can have local logging settings for a subtree by setting the LOGGING
2565 property to one or more of these keywords."
2566 :group 'org-todo
2567 :group 'org-progress
2568 :type '(choice
2569 (const :tag "Don't force a record" nil)
2570 (const :tag "Force recording the DONE state" time)
2571 (const :tag "Force recording a note with the DONE state" note)))
2574 (defgroup org-priorities nil
2575 "Priorities in Org-mode."
2576 :tag "Org Priorities"
2577 :group 'org-todo)
2579 (defcustom org-enable-priority-commands t
2580 "Non-nil means priority commands are active.
2581 When nil, these commands will be disabled, so that you never accidentally
2582 set a priority."
2583 :group 'org-priorities
2584 :type 'boolean)
2586 (defcustom org-highest-priority ?A
2587 "The highest priority of TODO items. A character like ?A, ?B etc.
2588 Must have a smaller ASCII number than `org-lowest-priority'."
2589 :group 'org-priorities
2590 :type 'character)
2592 (defcustom org-lowest-priority ?C
2593 "The lowest priority of TODO items. A character like ?A, ?B etc.
2594 Must have a larger ASCII number than `org-highest-priority'."
2595 :group 'org-priorities
2596 :type 'character)
2598 (defcustom org-default-priority ?B
2599 "The default priority of TODO items.
2600 This is the priority an item gets if no explicit priority is given.
2601 When starting to cycle on an empty priority the first step in the cycle
2602 depends on `org-priority-start-cycle-with-default'. The resulting first
2603 step priority must not exceed the range from `org-highest-priority' to
2604 `org-lowest-priority' which means that `org-default-priority' has to be
2605 in this range exclusive or inclusive the range boundaries. Else the
2606 first step refuses to set the default and the second will fall back
2607 to (depending on the command used) the highest or lowest priority."
2608 :group 'org-priorities
2609 :type 'character)
2611 (defcustom org-priority-start-cycle-with-default t
2612 "Non-nil means start with default priority when starting to cycle.
2613 When this is nil, the first step in the cycle will be (depending on the
2614 command used) one higher or lower than the default priority.
2615 See also `org-default-priority'."
2616 :group 'org-priorities
2617 :type 'boolean)
2619 (defcustom org-get-priority-function nil
2620 "Function to extract the priority from a string.
2621 The string is normally the headline. If this is nil Org computes the
2622 priority from the priority cookie like [#A] in the headline. It returns
2623 an integer, increasing by 1000 for each priority level.
2624 The user can set a different function here, which should take a string
2625 as an argument and return the numeric priority."
2626 :group 'org-priorities
2627 :version "24.1"
2628 :type 'function)
2630 (defgroup org-time nil
2631 "Options concerning time stamps and deadlines in Org-mode."
2632 :tag "Org Time"
2633 :group 'org)
2635 (defcustom org-insert-labeled-timestamps-at-point nil
2636 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2637 When nil, these labeled time stamps are forces into the second line of an
2638 entry, just after the headline. When scheduling from the global TODO list,
2639 the time stamp will always be forced into the second line."
2640 :group 'org-time
2641 :type 'boolean)
2643 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2644 "Formats for `format-time-string' which are used for time stamps.
2645 It is not recommended to change this constant.")
2647 (defcustom org-time-stamp-rounding-minutes '(0 5)
2648 "Number of minutes to round time stamps to.
2649 These are two values, the first applies when first creating a time stamp.
2650 The second applies when changing it with the commands `S-up' and `S-down'.
2651 When changing the time stamp, this means that it will change in steps
2652 of N minutes, as given by the second value.
2654 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2655 numbers should be factors of 60, so for example 5, 10, 15.
2657 When this is larger than 1, you can still force an exact time stamp by using
2658 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2659 and by using a prefix arg to `S-up/down' to specify the exact number
2660 of minutes to shift."
2661 :group 'org-time
2662 :get #'(lambda (var) ; Make sure both elements are there
2663 (if (integerp (default-value var))
2664 (list (default-value var) 5)
2665 (default-value var)))
2666 :type '(list
2667 (integer :tag "when inserting times")
2668 (integer :tag "when modifying times")))
2670 ;; Normalize old customizations of this variable.
2671 (when (integerp org-time-stamp-rounding-minutes)
2672 (setq org-time-stamp-rounding-minutes
2673 (list org-time-stamp-rounding-minutes
2674 org-time-stamp-rounding-minutes)))
2676 (defcustom org-display-custom-times nil
2677 "Non-nil means overlay custom formats over all time stamps.
2678 The formats are defined through the variable `org-time-stamp-custom-formats'.
2679 To turn this on on a per-file basis, insert anywhere in the file:
2680 #+STARTUP: customtime"
2681 :group 'org-time
2682 :set 'set-default
2683 :type 'sexp)
2684 (make-variable-buffer-local 'org-display-custom-times)
2686 (defcustom org-time-stamp-custom-formats
2687 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2688 "Custom formats for time stamps. See `format-time-string' for the syntax.
2689 These are overlaid over the default ISO format if the variable
2690 `org-display-custom-times' is set. Time like %H:%M should be at the
2691 end of the second format. The custom formats are also honored by export
2692 commands, if custom time display is turned on at the time of export."
2693 :group 'org-time
2694 :type 'sexp)
2696 (defun org-time-stamp-format (&optional long inactive)
2697 "Get the right format for a time string."
2698 (let ((f (if long (cdr org-time-stamp-formats)
2699 (car org-time-stamp-formats))))
2700 (if inactive
2701 (concat "[" (substring f 1 -1) "]")
2702 f)))
2704 (defcustom org-time-clocksum-format "%d:%02d"
2705 "The format string used when creating CLOCKSUM lines.
2706 This is also used when org-mode generates a time duration."
2707 :group 'org-time
2708 :type 'string)
2710 (defcustom org-time-clocksum-use-fractional nil
2711 "If non-nil, \\[org-clock-display] uses fractional times.
2712 org-mode generates a time duration."
2713 :group 'org-time
2714 :type 'boolean)
2716 (defcustom org-time-clocksum-fractional-format "%.2f"
2717 "The format string used when creating CLOCKSUM lines, or when
2718 org-mode generates a time duration."
2719 :group 'org-time
2720 :type 'string)
2722 (defcustom org-deadline-warning-days 14
2723 "No. of days before expiration during which a deadline becomes active.
2724 This variable governs the display in sparse trees and in the agenda.
2725 When 0 or negative, it means use this number (the absolute value of it)
2726 even if a deadline has a different individual lead time specified.
2728 Custom commands can set this variable in the options section."
2729 :group 'org-time
2730 :group 'org-agenda-daily/weekly
2731 :type 'integer)
2733 (defcustom org-read-date-prefer-future t
2734 "Non-nil means assume future for incomplete date input from user.
2735 This affects the following situations:
2736 1. The user gives a month but not a year.
2737 For example, if it is April and you enter \"feb 2\", this will be read
2738 as Feb 2, *next* year. \"May 5\", however, will be this year.
2739 2. The user gives a day, but no month.
2740 For example, if today is the 15th, and you enter \"3\", Org-mode will
2741 read this as the third of *next* month. However, if you enter \"17\",
2742 it will be considered as *this* month.
2744 If you set this variable to the symbol `time', then also the following
2745 will work:
2747 3. If the user gives a time, but no day. If the time is before now,
2748 to will be interpreted as tomorrow.
2750 Currently none of this works for ISO week specifications.
2752 When this option is nil, the current day, month and year will always be
2753 used as defaults.
2755 See also `org-agenda-jump-prefer-future'."
2756 :group 'org-time
2757 :type '(choice
2758 (const :tag "Never" nil)
2759 (const :tag "Check month and day" t)
2760 (const :tag "Check month, day, and time" time)))
2762 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2763 "Should the agenda jump command prefer the future for incomplete dates?
2764 The default is to do the same as configured in `org-read-date-prefer-future'.
2765 But you can also set a deviating value here.
2766 This may t or nil, or the symbol `org-read-date-prefer-future'."
2767 :group 'org-agenda
2768 :group 'org-time
2769 :version "24.1"
2770 :type '(choice
2771 (const :tag "Use org-read-date-prefer-future"
2772 org-read-date-prefer-future)
2773 (const :tag "Never" nil)
2774 (const :tag "Always" t)))
2776 (defcustom org-read-date-force-compatible-dates t
2777 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2779 Depending on the system Emacs is running on, certain dates cannot
2780 be represented with the type used internally to represent time.
2781 Dates between 1970-1-1 and 2038-1-1 can always be represented
2782 correctly. Some systems allow for earlier dates, some for later,
2783 some for both. One way to find out it to insert any date into an
2784 Org buffer, putting the cursor on the year and hitting S-up and
2785 S-down to test the range.
2787 When this variable is set to t, the date/time prompt will not let
2788 you specify dates outside the 1970-2037 range, so it is certain that
2789 these dates will work in whatever version of Emacs you are
2790 running, and also that you can move a file from one Emacs implementation
2791 to another. WHenever Org is forcing the year for you, it will display
2792 a message and beep.
2794 When this variable is nil, Org will check if the date is
2795 representable in the specific Emacs implementation you are using.
2796 If not, it will force a year, usually the current year, and beep
2797 to remind you. Currently this setting is not recommended because
2798 the likelihood that you will open your Org files in an Emacs that
2799 has limited date range is not negligible.
2801 A workaround for this problem is to use diary sexp dates for time
2802 stamps outside of this range."
2803 :group 'org-time
2804 :version "24.1"
2805 :type 'boolean)
2807 (defcustom org-read-date-display-live t
2808 "Non-nil means display current interpretation of date prompt live.
2809 This display will be in an overlay, in the minibuffer."
2810 :group 'org-time
2811 :type 'boolean)
2813 (defcustom org-read-date-popup-calendar t
2814 "Non-nil means pop up a calendar when prompting for a date.
2815 In the calendar, the date can be selected with mouse-1. However, the
2816 minibuffer will also be active, and you can simply enter the date as well.
2817 When nil, only the minibuffer will be available."
2818 :group 'org-time
2819 :type 'boolean)
2820 (if (fboundp 'defvaralias)
2821 (defvaralias 'org-popup-calendar-for-date-prompt
2822 'org-read-date-popup-calendar))
2824 (defcustom org-read-date-minibuffer-setup-hook nil
2825 "Hook to be used to set up keys for the date/time interface.
2826 Add key definitions to `minibuffer-local-map', which will be a temporary
2827 copy."
2828 :group 'org-time
2829 :type 'hook)
2831 (defcustom org-extend-today-until 0
2832 "The hour when your day really ends. Must be an integer.
2833 This has influence for the following applications:
2834 - When switching the agenda to \"today\". It it is still earlier than
2835 the time given here, the day recognized as TODAY is actually yesterday.
2836 - When a date is read from the user and it is still before the time given
2837 here, the current date and time will be assumed to be yesterday, 23:59.
2838 Also, timestamps inserted in remember templates follow this rule.
2840 IMPORTANT: This is a feature whose implementation is and likely will
2841 remain incomplete. Really, it is only here because past midnight seems to
2842 be the favorite working time of John Wiegley :-)"
2843 :group 'org-time
2844 :type 'integer)
2846 (defcustom org-use-effective-time nil
2847 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2848 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2849 \"effective time\" of any timestamps between midnight and 8am will be
2850 23:59 of the previous day."
2851 :group 'org-time
2852 :version "24.1"
2853 :type 'boolean)
2855 (defcustom org-edit-timestamp-down-means-later nil
2856 "Non-nil means S-down will increase the time in a time stamp.
2857 When nil, S-up will increase."
2858 :group 'org-time
2859 :type 'boolean)
2861 (defcustom org-calendar-follow-timestamp-change t
2862 "Non-nil means make the calendar window follow timestamp changes.
2863 When a timestamp is modified and the calendar window is visible, it will be
2864 moved to the new date."
2865 :group 'org-time
2866 :type 'boolean)
2868 (defgroup org-tags nil
2869 "Options concerning tags in Org-mode."
2870 :tag "Org Tags"
2871 :group 'org)
2873 (defcustom org-tag-alist nil
2874 "List of tags allowed in Org-mode files.
2875 When this list is nil, Org-mode will base TAG input on what is already in the
2876 buffer.
2877 The value of this variable is an alist, the car of each entry must be a
2878 keyword as a string, the cdr may be a character that is used to select
2879 that tag through the fast-tag-selection interface.
2880 See the manual for details."
2881 :group 'org-tags
2882 :type '(repeat
2883 (choice
2884 (cons (string :tag "Tag name")
2885 (character :tag "Access char"))
2886 (list :tag "Start radio group"
2887 (const :startgroup)
2888 (option (string :tag "Group description")))
2889 (list :tag "End radio group"
2890 (const :endgroup)
2891 (option (string :tag "Group description")))
2892 (const :tag "New line" (:newline)))))
2894 (defcustom org-tag-persistent-alist nil
2895 "List of tags that will always appear in all Org-mode files.
2896 This is in addition to any in buffer settings or customizations
2897 of `org-tag-alist'.
2898 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2899 The value of this variable is an alist, the car of each entry must be a
2900 keyword as a string, the cdr may be a character that is used to select
2901 that tag through the fast-tag-selection interface.
2902 See the manual for details.
2903 To disable these tags on a per-file basis, insert anywhere in the file:
2904 #+STARTUP: noptag"
2905 :group 'org-tags
2906 :type '(repeat
2907 (choice
2908 (cons (string :tag "Tag name")
2909 (character :tag "Access char"))
2910 (const :tag "Start radio group" (:startgroup))
2911 (const :tag "End radio group" (:endgroup))
2912 (const :tag "New line" (:newline)))))
2914 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2915 "If non-nil, always offer completion for all tags of all agenda files.
2916 Instead of customizing this variable directly, you might want to
2917 set it locally for capture buffers, because there no list of
2918 tags in that file can be created dynamically (there are none).
2920 (add-hook 'org-capture-mode-hook
2921 (lambda ()
2922 (set (make-local-variable
2923 'org-complete-tags-always-offer-all-agenda-tags)
2924 t)))"
2925 :group 'org-tags
2926 :version "24.1"
2927 :type 'boolean)
2929 (defvar org-file-tags nil
2930 "List of tags that can be inherited by all entries in the file.
2931 The tags will be inherited if the variable `org-use-tag-inheritance'
2932 says they should be.
2933 This variable is populated from #+FILETAGS lines.")
2935 (defcustom org-use-fast-tag-selection 'auto
2936 "Non-nil means use fast tag selection scheme.
2937 This is a special interface to select and deselect tags with single keys.
2938 When nil, fast selection is never used.
2939 When the symbol `auto', fast selection is used if and only if selection
2940 characters for tags have been configured, either through the variable
2941 `org-tag-alist' or through a #+TAGS line in the buffer.
2942 When t, fast selection is always used and selection keys are assigned
2943 automatically if necessary."
2944 :group 'org-tags
2945 :type '(choice
2946 (const :tag "Always" t)
2947 (const :tag "Never" nil)
2948 (const :tag "When selection characters are configured" 'auto)))
2950 (defcustom org-fast-tag-selection-single-key nil
2951 "Non-nil means fast tag selection exits after first change.
2952 When nil, you have to press RET to exit it.
2953 During fast tag selection, you can toggle this flag with `C-c'.
2954 This variable can also have the value `expert'. In this case, the window
2955 displaying the tags menu is not even shown, until you press C-c again."
2956 :group 'org-tags
2957 :type '(choice
2958 (const :tag "No" nil)
2959 (const :tag "Yes" t)
2960 (const :tag "Expert" expert)))
2962 (defvar org-fast-tag-selection-include-todo nil
2963 "Non-nil means fast tags selection interface will also offer TODO states.
2964 This is an undocumented feature, you should not rely on it.")
2966 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2967 "The column to which tags should be indented in a headline.
2968 If this number is positive, it specifies the column. If it is negative,
2969 it means that the tags should be flushright to that column. For example,
2970 -80 works well for a normal 80 character screen.
2971 When 0, place tags directly after headline text, with only one space in
2972 between."
2973 :group 'org-tags
2974 :type 'integer)
2976 (defcustom org-auto-align-tags t
2977 "Non-nil keeps tags aligned when modifying headlines.
2978 Some operations (i.e. demoting) change the length of a headline and
2979 therefore shift the tags around. With this option turned on, after
2980 each such operation the tags are again aligned to `org-tags-column'."
2981 :group 'org-tags
2982 :type 'boolean)
2984 (defcustom org-use-tag-inheritance t
2985 "Non-nil means tags in levels apply also for sublevels.
2986 When nil, only the tags directly given in a specific line apply there.
2987 This may also be a list of tags that should be inherited, or a regexp that
2988 matches tags that should be inherited. Additional control is possible
2989 with the variable `org-tags-exclude-from-inheritance' which gives an
2990 explicit list of tags to be excluded from inheritance., even if the value of
2991 `org-use-tag-inheritance' would select it for inheritance.
2993 If this option is t, a match early-on in a tree can lead to a large
2994 number of matches in the subtree when constructing the agenda or creating
2995 a sparse tree. If you only want to see the first match in a tree during
2996 a search, check out the variable `org-tags-match-list-sublevels'."
2997 :group 'org-tags
2998 :type '(choice
2999 (const :tag "Not" nil)
3000 (const :tag "Always" t)
3001 (repeat :tag "Specific tags" (string :tag "Tag"))
3002 (regexp :tag "Tags matched by regexp")))
3004 (defcustom org-tags-exclude-from-inheritance nil
3005 "List of tags that should never be inherited.
3006 This is a way to exclude a few tags from inheritance. For way to do
3007 the opposite, to actively allow inheritance for selected tags,
3008 see the variable `org-use-tag-inheritance'."
3009 :group 'org-tags
3010 :type '(repeat (string :tag "Tag")))
3012 (defun org-tag-inherit-p (tag)
3013 "Check if TAG is one that should be inherited."
3014 (cond
3015 ((member tag org-tags-exclude-from-inheritance) nil)
3016 ((eq org-use-tag-inheritance t) t)
3017 ((not org-use-tag-inheritance) nil)
3018 ((stringp org-use-tag-inheritance)
3019 (string-match org-use-tag-inheritance tag))
3020 ((listp org-use-tag-inheritance)
3021 (member tag org-use-tag-inheritance))
3022 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3024 (defcustom org-tags-match-list-sublevels t
3025 "Non-nil means list also sublevels of headlines matching a search.
3026 This variable applies to tags/property searches, and also to stuck
3027 projects because this search is based on a tags match as well.
3029 When set to the symbol `indented', sublevels are indented with
3030 leading dots.
3032 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3033 the sublevels of a headline matching a tag search often also match
3034 the same search. Listing all of them can create very long lists.
3035 Setting this variable to nil causes subtrees of a match to be skipped.
3037 This variable is semi-obsolete and probably should always be true. It
3038 is better to limit inheritance to certain tags using the variables
3039 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3040 :group 'org-tags
3041 :type '(choice
3042 (const :tag "No, don't list them" nil)
3043 (const :tag "Yes, do list them" t)
3044 (const :tag "List them, indented with leading dots" indented)))
3046 (defcustom org-tags-sort-function nil
3047 "When set, tags are sorted using this function as a comparator."
3048 :group 'org-tags
3049 :type '(choice
3050 (const :tag "No sorting" nil)
3051 (const :tag "Alphabetical" string<)
3052 (const :tag "Reverse alphabetical" string>)
3053 (function :tag "Custom function" nil)))
3055 (defvar org-tags-history nil
3056 "History of minibuffer reads for tags.")
3057 (defvar org-last-tags-completion-table nil
3058 "The last used completion table for tags.")
3059 (defvar org-after-tags-change-hook nil
3060 "Hook that is run after the tags in a line have changed.")
3062 (defgroup org-properties nil
3063 "Options concerning properties in Org-mode."
3064 :tag "Org Properties"
3065 :group 'org)
3067 (defcustom org-property-format "%-10s %s"
3068 "How property key/value pairs should be formatted by `indent-line'.
3069 When `indent-line' hits a property definition, it will format the line
3070 according to this format, mainly to make sure that the values are
3071 lined-up with respect to each other."
3072 :group 'org-properties
3073 :type 'string)
3075 (defcustom org-properties-postprocess-alist nil
3076 "Alist of properties and functions to adjust inserted values.
3077 Elements of this alist must be of the form
3079 ([string] [function])
3081 where [string] must be a property name and [function] must be a
3082 lambda expression: this lambda expression must take one argument,
3083 the value to adjust, and return the new value as a string.
3085 For example, this element will allow the property \"Remaining\"
3086 to be updated wrt the relation between the \"Effort\" property
3087 and the clock summary:
3089 ((\"Remaining\" (lambda(value)
3090 (let ((clocksum (org-clock-sum-current-item))
3091 (effort (org-duration-string-to-minutes
3092 (org-entry-get (point) \"Effort\"))))
3093 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3094 :group 'org-properties
3095 :version "24.1"
3096 :type '(alist :key-type (string :tag "Property")
3097 :value-type (function :tag "Function")))
3099 (defcustom org-use-property-inheritance nil
3100 "Non-nil means properties apply also for sublevels.
3102 This setting is chiefly used during property searches. Turning it on can
3103 cause significant overhead when doing a search, which is why it is not
3104 on by default.
3106 When nil, only the properties directly given in the current entry count.
3107 When t, every property is inherited. The value may also be a list of
3108 properties that should have inheritance, or a regular expression matching
3109 properties that should be inherited.
3111 However, note that some special properties use inheritance under special
3112 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3113 and the properties ending in \"_ALL\" when they are used as descriptor
3114 for valid values of a property.
3116 Note for programmers:
3117 When querying an entry with `org-entry-get', you can control if inheritance
3118 should be used. By default, `org-entry-get' looks only at the local
3119 properties. You can request inheritance by setting the inherit argument
3120 to t (to force inheritance) or to `selective' (to respect the setting
3121 in this variable)."
3122 :group 'org-properties
3123 :type '(choice
3124 (const :tag "Not" nil)
3125 (const :tag "Always" t)
3126 (repeat :tag "Specific properties" (string :tag "Property"))
3127 (regexp :tag "Properties matched by regexp")))
3129 (defun org-property-inherit-p (property)
3130 "Check if PROPERTY is one that should be inherited."
3131 (cond
3132 ((eq org-use-property-inheritance t) t)
3133 ((not org-use-property-inheritance) nil)
3134 ((stringp org-use-property-inheritance)
3135 (string-match org-use-property-inheritance property))
3136 ((listp org-use-property-inheritance)
3137 (member property org-use-property-inheritance))
3138 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3140 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3141 "The default column format, if no other format has been defined.
3142 This variable can be set on the per-file basis by inserting a line
3144 #+COLUMNS: %25ITEM ....."
3145 :group 'org-properties
3146 :type 'string)
3148 (defcustom org-columns-ellipses ".."
3149 "The ellipses to be used when a field in column view is truncated.
3150 When this is the empty string, as many characters as possible are shown,
3151 but then there will be no visual indication that the field has been truncated.
3152 When this is a string of length N, the last N characters of a truncated
3153 field are replaced by this string. If the column is narrower than the
3154 ellipses string, only part of the ellipses string will be shown."
3155 :group 'org-properties
3156 :type 'string)
3158 (defcustom org-columns-modify-value-for-display-function nil
3159 "Function that modifies values for display in column view.
3160 For example, it can be used to cut out a certain part from a time stamp.
3161 The function must take 2 arguments:
3163 column-title The title of the column (*not* the property name)
3164 value The value that should be modified.
3166 The function should return the value that should be displayed,
3167 or nil if the normal value should be used."
3168 :group 'org-properties
3169 :type 'function)
3171 (defcustom org-effort-property "Effort"
3172 "The property that is being used to keep track of effort estimates.
3173 Effort estimates given in this property need to have the format H:MM."
3174 :group 'org-properties
3175 :group 'org-progress
3176 :type '(string :tag "Property"))
3178 (defconst org-global-properties-fixed
3179 '(("VISIBILITY_ALL" . "folded children content all")
3180 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3181 "List of property/value pairs that can be inherited by any entry.
3183 These are fixed values, for the preset properties. The user variable
3184 that can be used to add to this list is `org-global-properties'.
3186 The entries in this list are cons cells where the car is a property
3187 name and cdr is a string with the value. If the value represents
3188 multiple items like an \"_ALL\" property, separate the items by
3189 spaces.")
3191 (defcustom org-global-properties nil
3192 "List of property/value pairs that can be inherited by any entry.
3194 This list will be combined with the constant `org-global-properties-fixed'.
3196 The entries in this list are cons cells where the car is a property
3197 name and cdr is a string with the value.
3199 You can set buffer-local values for the same purpose in the variable
3200 `org-file-properties' this by adding lines like
3202 #+PROPERTY: NAME VALUE"
3203 :group 'org-properties
3204 :type '(repeat
3205 (cons (string :tag "Property")
3206 (string :tag "Value"))))
3208 (defvar org-file-properties nil
3209 "List of property/value pairs that can be inherited by any entry.
3210 Valid for the current buffer.
3211 This variable is populated from #+PROPERTY lines.")
3212 (make-variable-buffer-local 'org-file-properties)
3214 (defgroup org-agenda nil
3215 "Options concerning agenda views in Org-mode."
3216 :tag "Org Agenda"
3217 :group 'org)
3219 (defvar org-category nil
3220 "Variable used by org files to set a category for agenda display.
3221 Such files should use a file variable to set it, for example
3223 # -*- mode: org; org-category: \"ELisp\"
3225 or contain a special line
3227 #+CATEGORY: ELisp
3229 If the file does not specify a category, then file's base name
3230 is used instead.")
3231 (make-variable-buffer-local 'org-category)
3232 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3234 (defcustom org-agenda-files nil
3235 "The files to be used for agenda display.
3236 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3237 \\[org-remove-file]. You can also use customize to edit the list.
3239 If an entry is a directory, all files in that directory that are matched by
3240 `org-agenda-file-regexp' will be part of the file list.
3242 If the value of the variable is not a list but a single file name, then
3243 the list of agenda files is actually stored and maintained in that file, one
3244 agenda file per line. In this file paths can be given relative to
3245 `org-directory'. Tilde expansion and environment variable substitution
3246 are also made."
3247 :group 'org-agenda
3248 :type '(choice
3249 (repeat :tag "List of files and directories" file)
3250 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3252 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3253 "Regular expression to match files for `org-agenda-files'.
3254 If any element in the list in that variable contains a directory instead
3255 of a normal file, all files in that directory that are matched by this
3256 regular expression will be included."
3257 :group 'org-agenda
3258 :type 'regexp)
3260 (defcustom org-agenda-text-search-extra-files nil
3261 "List of extra files to be searched by text search commands.
3262 These files will be search in addition to the agenda files by the
3263 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3264 Note that these files will only be searched for text search commands,
3265 not for the other agenda views like todo lists, tag searches or the weekly
3266 agenda. This variable is intended to list notes and possibly archive files
3267 that should also be searched by these two commands.
3268 In fact, if the first element in the list is the symbol `agenda-archives',
3269 than all archive files of all agenda files will be added to the search
3270 scope."
3271 :group 'org-agenda
3272 :type '(set :greedy t
3273 (const :tag "Agenda Archives" agenda-archives)
3274 (repeat :inline t (file))))
3276 (if (fboundp 'defvaralias)
3277 (defvaralias 'org-agenda-multi-occur-extra-files
3278 'org-agenda-text-search-extra-files))
3280 (defcustom org-agenda-skip-unavailable-files nil
3281 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3282 A nil value means to remove them, after a query, from the list."
3283 :group 'org-agenda
3284 :type 'boolean)
3286 (defcustom org-calendar-to-agenda-key [?c]
3287 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3288 The command `org-calendar-goto-agenda' will be bound to this key. The
3289 default is the character `c' because then `c' can be used to switch back and
3290 forth between agenda and calendar."
3291 :group 'org-agenda
3292 :type 'sexp)
3294 (defcustom org-calendar-agenda-action-key [?k]
3295 "The key to be installed in `calendar-mode-map' for agenda-action.
3296 The command `org-agenda-action' will be bound to this key. The
3297 default is the character `k' because we use the same key in the agenda."
3298 :group 'org-agenda
3299 :type 'sexp)
3301 (defcustom org-calendar-insert-diary-entry-key [?i]
3302 "The key to be installed in `calendar-mode-map' for adding diary entries.
3303 This option is irrelevant until `org-agenda-diary-file' has been configured
3304 to point to an Org-mode file. When that is the case, the command
3305 `org-agenda-diary-entry' will be bound to the key given here, by default
3306 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3307 if you want to continue doing this, you need to change this to a different
3308 key."
3309 :group 'org-agenda
3310 :type 'sexp)
3312 (defcustom org-agenda-diary-file 'diary-file
3313 "File to which to add new entries with the `i' key in agenda and calendar.
3314 When this is the symbol `diary-file', the functionality in the Emacs
3315 calendar will be used to add entries to the `diary-file'. But when this
3316 points to a file, `org-agenda-diary-entry' will be used instead."
3317 :group 'org-agenda
3318 :type '(choice
3319 (const :tag "The standard Emacs diary file" diary-file)
3320 (file :tag "Special Org file diary entries")))
3322 (eval-after-load "calendar"
3323 '(progn
3324 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3325 'org-calendar-goto-agenda)
3326 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3327 'org-agenda-action)
3328 (add-hook 'calendar-mode-hook
3329 (lambda ()
3330 (unless (eq org-agenda-diary-file 'diary-file)
3331 (define-key calendar-mode-map
3332 org-calendar-insert-diary-entry-key
3333 'org-agenda-diary-entry))))))
3335 (defgroup org-latex nil
3336 "Options for embedding LaTeX code into Org-mode."
3337 :tag "Org LaTeX"
3338 :group 'org)
3340 (defcustom org-format-latex-options
3341 '(:foreground default :background default :scale 1.0
3342 :html-foreground "Black" :html-background "Transparent"
3343 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3344 "Options for creating images from LaTeX fragments.
3345 This is a property list with the following properties:
3346 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3347 `default' means use the foreground of the default face.
3348 :background the background color, or \"Transparent\".
3349 `default' means use the background of the default face.
3350 :scale a scaling factor for the size of the images, to get more pixels
3351 :html-foreground, :html-background, :html-scale
3352 the same numbers for HTML export.
3353 :matchers a list indicating which matchers should be used to
3354 find LaTeX fragments. Valid members of this list are:
3355 \"begin\" find environments
3356 \"$1\" find single characters surrounded by $.$
3357 \"$\" find math expressions surrounded by $...$
3358 \"$$\" find math expressions surrounded by $$....$$
3359 \"\\(\" find math expressions surrounded by \\(...\\)
3360 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3361 :group 'org-latex
3362 :type 'plist)
3364 (defcustom org-format-latex-signal-error t
3365 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3366 When nil, just push out a message."
3367 :group 'org-latex
3368 :version "24.1"
3369 :type 'boolean)
3371 (defcustom org-latex-to-mathml-jar-file nil
3372 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3373 Use this to specify additional executable file say a jar file.
3375 When using MathToWeb as the converter, specify the full-path to
3376 your mathtoweb.jar file."
3377 :group 'org-latex
3378 :version "24.1"
3379 :type '(choice
3380 (const :tag "None" nil)
3381 (file :tag "JAR file" :must-match t)))
3383 (defcustom org-latex-to-mathml-convert-command nil
3384 "Command to convert LaTeX fragments to MathML.
3385 Replace format-specifiers in the command as noted below and use
3386 `shell-command' to convert LaTeX to MathML.
3387 %j: Executable file in fully expanded form as specified by
3388 `org-latex-to-mathml-jar-file'.
3389 %I: Input LaTeX file in fully expanded form
3390 %o: Output MathML file
3391 This command is used by `org-create-math-formula'.
3393 When using MathToWeb as the converter, set this to
3394 \"java -jar %j -unicode -force -df %o %I\"."
3395 :group 'org-latex
3396 :version "24.1"
3397 :type '(choice
3398 (const :tag "None" nil)
3399 (string :tag "\nShell command")))
3401 (defcustom org-latex-create-formula-image-program 'dvipng
3402 "Program to convert LaTeX fragments with.
3404 dvipng Process the LaTeX fragments to dvi file, then convert
3405 dvi files to png files using dvipng.
3406 This will also include processing of non-math environments.
3407 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3408 to convert pdf files to png files"
3409 :group 'org-latex
3410 :version "24.1"
3411 :type '(choice
3412 (const :tag "dvipng" dvipng)
3413 (const :tag "imagemagick" imagemagick)))
3415 (defun org-format-latex-mathml-available-p ()
3416 "Return t if `org-latex-to-mathml-convert-command' is usable."
3417 (save-match-data
3418 (when (and (boundp 'org-latex-to-mathml-convert-command)
3419 org-latex-to-mathml-convert-command)
3420 (let ((executable (car (split-string
3421 org-latex-to-mathml-convert-command))))
3422 (when (executable-find executable)
3423 (if (string-match
3424 "%j" org-latex-to-mathml-convert-command)
3425 (file-readable-p org-latex-to-mathml-jar-file)
3426 t))))))
3428 (defcustom org-format-latex-header "\\documentclass{article}
3429 \\usepackage[usenames]{color}
3430 \\usepackage{amsmath}
3431 \\usepackage[mathscr]{eucal}
3432 \\pagestyle{empty} % do not remove
3433 \[PACKAGES]
3434 \[DEFAULT-PACKAGES]
3435 % The settings below are copied from fullpage.sty
3436 \\setlength{\\textwidth}{\\paperwidth}
3437 \\addtolength{\\textwidth}{-3cm}
3438 \\setlength{\\oddsidemargin}{1.5cm}
3439 \\addtolength{\\oddsidemargin}{-2.54cm}
3440 \\setlength{\\evensidemargin}{\\oddsidemargin}
3441 \\setlength{\\textheight}{\\paperheight}
3442 \\addtolength{\\textheight}{-\\headheight}
3443 \\addtolength{\\textheight}{-\\headsep}
3444 \\addtolength{\\textheight}{-\\footskip}
3445 \\addtolength{\\textheight}{-3cm}
3446 \\setlength{\\topmargin}{1.5cm}
3447 \\addtolength{\\topmargin}{-2.54cm}"
3448 "The document header used for processing LaTeX fragments.
3449 It is imperative that this header make sure that no page number
3450 appears on the page. The package defined in the variables
3451 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3452 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3453 will be appended."
3454 :group 'org-latex
3455 :type 'string)
3457 (defvar org-format-latex-header-extra nil)
3459 (defun org-set-packages-alist (var val)
3460 "Set the packages alist and make sure it has 3 elements per entry."
3461 (set var (mapcar (lambda (x)
3462 (if (and (consp x) (= (length x) 2))
3463 (list (car x) (nth 1 x) t)
3465 val)))
3467 (defun org-get-packages-alist (var)
3469 "Get the packages alist and make sure it has 3 elements per entry."
3470 (mapcar (lambda (x)
3471 (if (and (consp x) (= (length x) 2))
3472 (list (car x) (nth 1 x) t)
3474 (default-value var)))
3476 ;; The following variables are defined here because is it also used
3477 ;; when formatting latex fragments. Originally it was part of the
3478 ;; LaTeX exporter, which is why the name includes "export".
3479 (defcustom org-export-latex-default-packages-alist
3480 '(("AUTO" "inputenc" t)
3481 ("T1" "fontenc" t)
3482 ("" "fixltx2e" nil)
3483 ("" "graphicx" t)
3484 ("" "longtable" nil)
3485 ("" "float" nil)
3486 ("" "wrapfig" nil)
3487 ("" "soul" t)
3488 ("" "textcomp" t)
3489 ("" "marvosym" t)
3490 ("" "wasysym" t)
3491 ("" "latexsym" t)
3492 ("" "amssymb" t)
3493 ("" "hyperref" nil)
3494 "\\tolerance=1000"
3496 "Alist of default packages to be inserted in the header.
3497 Change this only if one of the packages here causes an incompatibility
3498 with another package you are using.
3499 The packages in this list are needed by one part or another of Org-mode
3500 to function properly.
3502 - inputenc, fontenc: for basic font and character selection
3503 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3504 for interpreting the entities in `org-entities'. You can skip some of these
3505 packages if you don't use any of the symbols in it.
3506 - graphicx: for including images
3507 - float, wrapfig: for figure placement
3508 - longtable: for long tables
3509 - hyperref: for cross references
3511 Therefore you should not modify this variable unless you know what you
3512 are doing. The one reason to change it anyway is that you might be loading
3513 some other package that conflicts with one of the default packages.
3514 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3515 If SNIPPET-FLAG is t, the package also needs to be included when
3516 compiling LaTeX snippets into images for inclusion into HTML."
3517 :group 'org-export-latex
3518 :set 'org-set-packages-alist
3519 :get 'org-get-packages-alist
3520 :version "24.1"
3521 :type '(repeat
3522 (choice
3523 (list :tag "options/package pair"
3524 (string :tag "options")
3525 (string :tag "package")
3526 (boolean :tag "Snippet"))
3527 (string :tag "A line of LaTeX"))))
3529 (defcustom org-export-latex-packages-alist nil
3530 "Alist of packages to be inserted in every LaTeX header.
3531 These will be inserted after `org-export-latex-default-packages-alist'.
3532 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3533 SNIPPET-FLAG, when t, indicates that this package is also needed when
3534 turning LaTeX snippets into images for inclusion into HTML.
3535 Make sure that you only list packages here which:
3536 - you want in every file
3537 - do not conflict with the default packages in
3538 `org-export-latex-default-packages-alist'
3539 - do not conflict with the setup in `org-format-latex-header'."
3540 :group 'org-export-latex
3541 :set 'org-set-packages-alist
3542 :get 'org-get-packages-alist
3543 :type '(repeat
3544 (choice
3545 (list :tag "options/package pair"
3546 (string :tag "options")
3547 (string :tag "package")
3548 (boolean :tag "Snippet"))
3549 (string :tag "A line of LaTeX"))))
3552 (defgroup org-appearance nil
3553 "Settings for Org-mode appearance."
3554 :tag "Org Appearance"
3555 :group 'org)
3557 (defcustom org-level-color-stars-only nil
3558 "Non-nil means fontify only the stars in each headline.
3559 When nil, the entire headline is fontified.
3560 Changing it requires restart of `font-lock-mode' to become effective
3561 also in regions already fontified."
3562 :group 'org-appearance
3563 :type 'boolean)
3565 (defcustom org-hide-leading-stars nil
3566 "Non-nil means hide the first N-1 stars in a headline.
3567 This works by using the face `org-hide' for these stars. This
3568 face is white for a light background, and black for a dark
3569 background. You may have to customize the face `org-hide' to
3570 make this work.
3571 Changing it requires restart of `font-lock-mode' to become effective
3572 also in regions already fontified.
3573 You may also set this on a per-file basis by adding one of the following
3574 lines to the buffer:
3576 #+STARTUP: hidestars
3577 #+STARTUP: showstars"
3578 :group 'org-appearance
3579 :type 'boolean)
3581 (defcustom org-hidden-keywords nil
3582 "List of symbols corresponding to keywords to be hidden the org buffer.
3583 For example, a value '(title) for this list will make the document's title
3584 appear in the buffer without the initial #+TITLE: keyword."
3585 :group 'org-appearance
3586 :version "24.1"
3587 :type '(set (const :tag "#+AUTHOR" author)
3588 (const :tag "#+DATE" date)
3589 (const :tag "#+EMAIL" email)
3590 (const :tag "#+TITLE" title)))
3592 (defcustom org-fontify-done-headline nil
3593 "Non-nil means change the face of a headline if it is marked DONE.
3594 Normally, only the TODO/DONE keyword indicates the state of a headline.
3595 When this is non-nil, the headline after the keyword is set to the
3596 `org-headline-done' as an additional indication."
3597 :group 'org-appearance
3598 :type 'boolean)
3600 (defcustom org-fontify-emphasized-text t
3601 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3602 Changing this variable requires a restart of Emacs to take effect."
3603 :group 'org-appearance
3604 :type 'boolean)
3606 (defcustom org-fontify-whole-heading-line nil
3607 "Non-nil means fontify the whole line for headings.
3608 This is useful when setting a background color for the
3609 org-level-* faces."
3610 :group 'org-appearance
3611 :type 'boolean)
3613 (defcustom org-highlight-latex-fragments-and-specials nil
3614 "Non-nil means fontify what is treated specially by the exporters."
3615 :group 'org-appearance
3616 :type 'boolean)
3618 (defcustom org-hide-emphasis-markers nil
3619 "Non-nil mean font-lock should hide the emphasis marker characters."
3620 :group 'org-appearance
3621 :type 'boolean)
3623 (defcustom org-pretty-entities nil
3624 "Non-nil means show entities as UTF8 characters.
3625 When nil, the \\name form remains in the buffer."
3626 :group 'org-appearance
3627 :version "24.1"
3628 :type 'boolean)
3630 (defcustom org-pretty-entities-include-sub-superscripts t
3631 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3632 :group 'org-appearance
3633 :version "24.1"
3634 :type 'boolean)
3636 (defvar org-emph-re nil
3637 "Regular expression for matching emphasis.
3638 After a match, the match groups contain these elements:
3639 0 The match of the full regular expression, including the characters
3640 before and after the proper match
3641 1 The character before the proper match, or empty at beginning of line
3642 2 The proper match, including the leading and trailing markers
3643 3 The leading marker like * or /, indicating the type of highlighting
3644 4 The text between the emphasis markers, not including the markers
3645 5 The character after the match, empty at the end of a line")
3646 (defvar org-verbatim-re nil
3647 "Regular expression for matching verbatim text.")
3648 (defvar org-emphasis-regexp-components) ; defined just below
3649 (defvar org-emphasis-alist) ; defined just below
3650 (defun org-set-emph-re (var val)
3651 "Set variable and compute the emphasis regular expression."
3652 (set var val)
3653 (when (and (boundp 'org-emphasis-alist)
3654 (boundp 'org-emphasis-regexp-components)
3655 org-emphasis-alist org-emphasis-regexp-components)
3656 (let* ((e org-emphasis-regexp-components)
3657 (pre (car e))
3658 (post (nth 1 e))
3659 (border (nth 2 e))
3660 (body (nth 3 e))
3661 (nl (nth 4 e))
3662 (body1 (concat body "*?"))
3663 (markers (mapconcat 'car org-emphasis-alist ""))
3664 (vmarkers (mapconcat
3665 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3666 org-emphasis-alist "")))
3667 ;; make sure special characters appear at the right position in the class
3668 (if (string-match "\\^" markers)
3669 (setq markers (concat (replace-match "" t t markers) "^")))
3670 (if (string-match "-" markers)
3671 (setq markers (concat (replace-match "" t t markers) "-")))
3672 (if (string-match "\\^" vmarkers)
3673 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3674 (if (string-match "-" vmarkers)
3675 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3676 (if (> nl 0)
3677 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3678 (int-to-string nl) "\\}")))
3679 ;; Make the regexp
3680 (setq org-emph-re
3681 (concat "\\([" pre "]\\|^\\)"
3682 "\\("
3683 "\\([" markers "]\\)"
3684 "\\("
3685 "[^" border "]\\|"
3686 "[^" border "]"
3687 body1
3688 "[^" border "]"
3689 "\\)"
3690 "\\3\\)"
3691 "\\([" post "]\\|$\\)"))
3692 (setq org-verbatim-re
3693 (concat "\\([" pre "]\\|^\\)"
3694 "\\("
3695 "\\([" vmarkers "]\\)"
3696 "\\("
3697 "[^" border "]\\|"
3698 "[^" border "]"
3699 body1
3700 "[^" border "]"
3701 "\\)"
3702 "\\3\\)"
3703 "\\([" post "]\\|$\\)")))))
3705 (defcustom org-emphasis-regexp-components
3706 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3707 "Components used to build the regular expression for emphasis.
3708 This is a list with five entries. Terminology: In an emphasis string
3709 like \" *strong word* \", we call the initial space PREMATCH, the final
3710 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3711 and \"trong wor\" is the body. The different components in this variable
3712 specify what is allowed/forbidden in each part:
3714 pre Chars allowed as prematch. Beginning of line will be allowed too.
3715 post Chars allowed as postmatch. End of line will be allowed too.
3716 border The chars *forbidden* as border characters.
3717 body-regexp A regexp like \".\" to match a body character. Don't use
3718 non-shy groups here, and don't allow newline here.
3719 newline The maximum number of newlines allowed in an emphasis exp.
3721 Use customize to modify this, or restart Emacs after changing it."
3722 :group 'org-appearance
3723 :set 'org-set-emph-re
3724 :type '(list
3725 (sexp :tag "Allowed chars in pre ")
3726 (sexp :tag "Allowed chars in post ")
3727 (sexp :tag "Forbidden chars in border ")
3728 (sexp :tag "Regexp for body ")
3729 (integer :tag "number of newlines allowed")
3730 (option (boolean :tag "Please ignore this button"))))
3732 (defcustom org-emphasis-alist
3733 `(("*" bold "<b>" "</b>")
3734 ("/" italic "<i>" "</i>")
3735 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3736 ("=" org-code "<code>" "</code>" verbatim)
3737 ("~" org-verbatim "<code>" "</code>" verbatim)
3738 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3739 "<del>" "</del>")
3741 "Special syntax for emphasized text.
3742 Text starting and ending with a special character will be emphasized, for
3743 example *bold*, _underlined_ and /italic/. This variable sets the marker
3744 characters, the face to be used by font-lock for highlighting in Org-mode
3745 Emacs buffers, and the HTML tags to be used for this.
3746 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3747 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3748 Use customize to modify this, or restart Emacs after changing it."
3749 :group 'org-appearance
3750 :set 'org-set-emph-re
3751 :type '(repeat
3752 (list
3753 (string :tag "Marker character")
3754 (choice
3755 (face :tag "Font-lock-face")
3756 (plist :tag "Face property list"))
3757 (string :tag "HTML start tag")
3758 (string :tag "HTML end tag")
3759 (option (const verbatim)))))
3761 (defvar org-protecting-blocks
3762 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3763 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3764 This is needed for font-lock setup.")
3766 ;;; Miscellaneous options
3768 (defgroup org-completion nil
3769 "Completion in Org-mode."
3770 :tag "Org Completion"
3771 :group 'org)
3773 (defcustom org-completion-use-ido nil
3774 "Non-nil means use ido completion wherever possible.
3775 Note that `ido-mode' must be active for this variable to be relevant.
3776 If you decide to turn this variable on, you might well want to turn off
3777 `org-outline-path-complete-in-steps'.
3778 See also `org-completion-use-iswitchb'."
3779 :group 'org-completion
3780 :type 'boolean)
3782 (defcustom org-completion-use-iswitchb nil
3783 "Non-nil means use iswitchb completion wherever possible.
3784 Note that `iswitchb-mode' must be active for this variable to be relevant.
3785 If you decide to turn this variable on, you might well want to turn off
3786 `org-outline-path-complete-in-steps'.
3787 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3788 :group 'org-completion
3789 :type 'boolean)
3791 (defcustom org-completion-fallback-command 'hippie-expand
3792 "The expansion command called by \\[pcomplete] in normal context.
3793 Normal means, no org-mode-specific context."
3794 :group 'org-completion
3795 :type 'function)
3797 ;;; Functions and variables from their packages
3798 ;; Declared here to avoid compiler warnings
3800 ;; XEmacs only
3801 (defvar outline-mode-menu-heading)
3802 (defvar outline-mode-menu-show)
3803 (defvar outline-mode-menu-hide)
3804 (defvar zmacs-regions) ; XEmacs regions
3806 ;; Emacs only
3807 (defvar mark-active)
3809 ;; Various packages
3810 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3811 (declare-function calendar-forward-day "cal-move" (arg))
3812 (declare-function calendar-goto-date "cal-move" (date))
3813 (declare-function calendar-goto-today "cal-move" ())
3814 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3815 (defvar calc-embedded-close-formula)
3816 (defvar calc-embedded-open-formula)
3817 (declare-function cdlatex-tab "ext:cdlatex" ())
3818 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3819 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3820 (defvar font-lock-unfontify-region-function)
3821 (declare-function iswitchb-read-buffer "iswitchb"
3822 (prompt &optional default require-match start matches-set))
3823 (defvar iswitchb-temp-buflist)
3824 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3825 (defvar org-agenda-tags-todo-honor-ignore-options)
3826 (declare-function org-agenda-skip "org-agenda" ())
3827 (declare-function
3828 org-agenda-format-item "org-agenda"
3829 (extra txt &optional category tags dotime noprefix remove-re habitp))
3830 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3831 (declare-function org-agenda-change-all-lines "org-agenda"
3832 (newhead hdmarker &optional fixface just-this))
3833 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3834 (declare-function org-agenda-maybe-redo "org-agenda" ())
3835 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3836 (beg end))
3837 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3838 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3839 "org-agenda" (&optional end))
3840 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3841 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3842 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3843 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3844 (declare-function org-indent-mode "org-indent" (&optional arg))
3845 (declare-function parse-time-string "parse-time" (string))
3846 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3847 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3848 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3849 (defvar remember-data-file)
3850 (defvar texmathp-why)
3851 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3852 (declare-function table--at-cell-p "table" (position &optional object at-column))
3854 (defvar w3m-current-url)
3855 (defvar w3m-current-title)
3857 (defvar org-latex-regexps)
3859 ;;; Autoload and prepare some org modules
3861 ;; Some table stuff that needs to be defined here, because it is used
3862 ;; by the functions setting up org-mode or checking for table context.
3864 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3865 "Detect an org-type or table-type table.")
3866 (defconst org-table-line-regexp "^[ \t]*|"
3867 "Detect an org-type table line.")
3868 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3869 "Detect an org-type table line.")
3870 (defconst org-table-hline-regexp "^[ \t]*|-"
3871 "Detect an org-type table hline.")
3872 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3873 "Detect a table-type table hline.")
3874 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3875 "Detect the first line outside a table when searching from within it.
3876 This works for both table types.")
3878 ;; Autoload the functions in org-table.el that are needed by functions here.
3880 (eval-and-compile
3881 (org-autoload "org-table"
3882 '(org-table-align org-table-begin org-table-blank-field
3883 org-table-convert org-table-convert-region org-table-copy-down
3884 org-table-copy-region org-table-create
3885 org-table-create-or-convert-from-region
3886 org-table-create-with-table.el org-table-current-dline
3887 org-table-cut-region org-table-delete-column org-table-edit-field
3888 org-table-edit-formulas org-table-end org-table-eval-formula
3889 org-table-export org-table-field-info
3890 org-table-get-stored-formulas org-table-goto-column
3891 org-table-hline-and-move org-table-import org-table-insert-column
3892 org-table-insert-hline org-table-insert-row org-table-iterate
3893 org-table-justify-field-maybe org-table-kill-row
3894 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3895 org-table-move-column org-table-move-column-left
3896 org-table-move-column-right org-table-move-row
3897 org-table-move-row-down org-table-move-row-up
3898 org-table-next-field org-table-next-row org-table-paste-rectangle
3899 org-table-previous-field org-table-recalculate
3900 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3901 org-table-toggle-coordinate-overlays
3902 org-table-toggle-formula-debugger org-table-wrap-region
3903 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3904 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3905 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3907 (defun org-at-table-p (&optional table-type)
3908 "Return t if the cursor is inside an org-type table.
3909 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3910 (if org-enable-table-editor
3911 (save-excursion
3912 (beginning-of-line 1)
3913 (looking-at (if table-type org-table-any-line-regexp
3914 org-table-line-regexp)))
3915 nil))
3916 (defsubst org-table-p () (org-at-table-p))
3918 (defun org-at-table.el-p ()
3919 "Return t if and only if we are at a table.el table."
3920 (and (org-at-table-p 'any)
3921 (save-excursion
3922 (goto-char (org-table-begin 'any))
3923 (looking-at org-table1-hline-regexp))))
3924 (defun org-table-recognize-table.el ()
3925 "If there is a table.el table nearby, recognize it and move into it."
3926 (if org-table-tab-recognizes-table.el
3927 (if (org-at-table.el-p)
3928 (progn
3929 (beginning-of-line 1)
3930 (if (looking-at org-table-dataline-regexp)
3932 (if (looking-at org-table1-hline-regexp)
3933 (progn
3934 (beginning-of-line 2)
3935 (if (looking-at org-table-any-border-regexp)
3936 (beginning-of-line -1)))))
3937 (if (re-search-forward "|" (org-table-end t) t)
3938 (progn
3939 (require 'table)
3940 (if (table--at-cell-p (point))
3942 (message "recognizing table.el table...")
3943 (table-recognize-table)
3944 (message "recognizing table.el table...done")))
3945 (error "This should not happen"))
3947 nil)
3948 nil))
3950 (defun org-at-table-hline-p ()
3951 "Return t if the cursor is inside a hline in a table."
3952 (if org-enable-table-editor
3953 (save-excursion
3954 (beginning-of-line 1)
3955 (looking-at org-table-hline-regexp))
3956 nil))
3958 (defvar org-table-clean-did-remove-column nil)
3960 (defun org-table-map-tables (function &optional quietly)
3961 "Apply FUNCTION to the start of all tables in the buffer."
3962 (save-excursion
3963 (save-restriction
3964 (widen)
3965 (goto-char (point-min))
3966 (while (re-search-forward org-table-any-line-regexp nil t)
3967 (unless quietly
3968 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3969 (beginning-of-line 1)
3970 (when (and (looking-at org-table-line-regexp)
3971 ;; Exclude tables in src/example/verbatim/clocktable blocks
3972 (not (org-in-block-p '("src" "example"))))
3973 (save-excursion (funcall function))
3974 (or (looking-at org-table-line-regexp)
3975 (forward-char 1)))
3976 (re-search-forward org-table-any-border-regexp nil 1))))
3977 (unless quietly (message "Mapping tables: done")))
3979 ;; Declare and autoload functions from org-exp.el & Co
3981 (declare-function org-default-export-plist "org-exp")
3982 (declare-function org-infile-export-plist "org-exp")
3983 (declare-function org-get-current-options "org-exp")
3984 (eval-and-compile
3985 (org-autoload "org-exp"
3986 '(org-export org-export-visible
3987 org-insert-export-options-template
3988 org-table-clean-before-export))
3989 (org-autoload "org-ascii"
3990 '(org-export-as-ascii org-export-ascii-preprocess
3991 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3992 org-export-region-as-ascii))
3993 (org-autoload "org-latex"
3994 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3995 org-replace-region-by-latex org-export-region-as-latex
3996 org-export-as-latex org-export-as-pdf
3997 org-export-as-pdf-and-open))
3998 (org-autoload "org-html"
3999 '(org-export-as-html-and-open
4000 org-export-as-html-batch org-export-as-html-to-buffer
4001 org-replace-region-by-html org-export-region-as-html
4002 org-export-as-html))
4003 (org-autoload "org-docbook"
4004 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4005 org-replace-region-by-docbook org-export-region-as-docbook
4006 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4007 org-export-as-docbook))
4008 (org-autoload "org-icalendar"
4009 '(org-export-icalendar-this-file
4010 org-export-icalendar-all-agenda-files
4011 org-export-icalendar-combine-agenda-files))
4012 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4013 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4015 ;; Declare and autoload functions from org-agenda.el
4017 (eval-and-compile
4018 (org-autoload "org-agenda"
4019 '(org-agenda org-agenda-list org-search-view
4020 org-todo-list org-tags-view org-agenda-list-stuck-projects
4021 org-diary org-agenda-to-appt
4022 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4024 ;; Autoload org-remember
4026 (eval-and-compile
4027 (org-autoload "org-remember"
4028 '(org-remember-insinuate org-remember-annotation
4029 org-remember-apply-template org-remember org-remember-handler)))
4031 (eval-and-compile
4032 (org-autoload "org-capture"
4033 '(org-capture org-capture-insert-template-here
4034 org-capture-import-remember-templates)))
4036 ;; Autoload org-clock.el
4038 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4039 (beg end))
4040 (declare-function org-clock-update-mode-line "org-clock" ())
4041 (declare-function org-resolve-clocks "org-clock"
4042 (&optional also-non-dangling-p prompt last-valid))
4043 (defvar org-clock-start-time)
4044 (defvar org-clock-marker (make-marker)
4045 "Marker recording the last clock-in.")
4046 (defvar org-clock-hd-marker (make-marker)
4047 "Marker recording the last clock-in, but the headline position.")
4048 (defvar org-clock-heading ""
4049 "The heading of the current clock entry.")
4050 (defun org-clock-is-active ()
4051 "Return non-nil if clock is currently running.
4052 The return value is actually the clock marker."
4053 (marker-buffer org-clock-marker))
4055 (eval-and-compile
4056 (org-autoload
4057 "org-clock"
4058 '(org-clock-in org-clock-out org-clock-cancel
4059 org-clock-goto org-clock-sum org-clock-display
4060 org-clock-remove-overlays org-clock-report
4061 org-clocktable-shift org-dblock-write:clocktable
4062 org-get-clocktable org-resolve-clocks)))
4064 (defun org-clock-update-time-maybe ()
4065 "If this is a CLOCK line, update it and return t.
4066 Otherwise, return nil."
4067 (interactive)
4068 (save-excursion
4069 (beginning-of-line 1)
4070 (skip-chars-forward " \t")
4071 (when (looking-at org-clock-string)
4072 (let ((re (concat "[ \t]*" org-clock-string
4073 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4074 "\\([ \t]*=>.*\\)?\\)?"))
4075 ts te h m s neg)
4076 (cond
4077 ((not (looking-at re))
4078 nil)
4079 ((not (match-end 2))
4080 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4081 (> org-clock-marker (point))
4082 (<= org-clock-marker (point-at-eol)))
4083 ;; The clock is running here
4084 (setq org-clock-start-time
4085 (apply 'encode-time
4086 (org-parse-time-string (match-string 1))))
4087 (org-clock-update-mode-line)))
4089 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4090 (end-of-line 1)
4091 (setq ts (match-string 1)
4092 te (match-string 3))
4093 (setq s (- (org-float-time
4094 (apply 'encode-time (org-parse-time-string te)))
4095 (org-float-time
4096 (apply 'encode-time (org-parse-time-string ts))))
4097 neg (< s 0)
4098 s (abs s)
4099 h (floor (/ s 3600))
4100 s (- s (* 3600 h))
4101 m (floor (/ s 60))
4102 s (- s (* 60 s)))
4103 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4104 t))))))
4106 (defun org-check-running-clock ()
4107 "Check if the current buffer contains the running clock.
4108 If yes, offer to stop it and to save the buffer with the changes."
4109 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4110 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4111 (buffer-name))))
4112 (org-clock-out)
4113 (when (y-or-n-p "Save changed buffer?")
4114 (save-buffer))))
4116 (defun org-clocktable-try-shift (dir n)
4117 "Check if this line starts a clock table, if yes, shift the time block."
4118 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4119 (org-clocktable-shift dir n)))
4121 ;; Autoload org-timer.el
4123 (eval-and-compile
4124 (org-autoload
4125 "org-timer"
4126 '(org-timer-start org-timer org-timer-item
4127 org-timer-change-times-in-region
4128 org-timer-set-timer
4129 org-timer-reset-timers
4130 org-timer-show-remaining-time)))
4132 ;; Autoload org-feed.el
4134 (eval-and-compile
4135 (org-autoload
4136 "org-feed"
4137 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4140 ;; Autoload org-indent.el
4142 ;; Define the variable already here, to make sure we have it.
4143 (defvar org-indent-mode nil
4144 "Non-nil if Org-Indent mode is enabled.
4145 Use the command `org-indent-mode' to change this variable.")
4147 (eval-and-compile
4148 (org-autoload
4149 "org-indent"
4150 '(org-indent-mode)))
4152 ;; Autoload org-mobile.el
4154 (eval-and-compile
4155 (org-autoload
4156 "org-mobile"
4157 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4159 ;; Autoload archiving code
4160 ;; The stuff that is needed for cycling and tags has to be defined here.
4162 (defgroup org-archive nil
4163 "Options concerning archiving in Org-mode."
4164 :tag "Org Archive"
4165 :group 'org-structure)
4167 (defcustom org-archive-location "%s_archive::"
4168 "The location where subtrees should be archived.
4170 The value of this variable is a string, consisting of two parts,
4171 separated by a double-colon. The first part is a filename and
4172 the second part is a headline.
4174 When the filename is omitted, archiving happens in the same file.
4175 %s in the filename will be replaced by the current file
4176 name (without the directory part). Archiving to a different file
4177 is useful to keep archived entries from contributing to the
4178 Org-mode Agenda.
4180 The archived entries will be filed as subtrees of the specified
4181 headline. When the headline is omitted, the subtrees are simply
4182 filed away at the end of the file, as top-level entries. Also in
4183 the heading you can use %s to represent the file name, this can be
4184 useful when using the same archive for a number of different files.
4186 Here are a few examples:
4187 \"%s_archive::\"
4188 If the current file is Projects.org, archive in file
4189 Projects.org_archive, as top-level trees. This is the default.
4191 \"::* Archived Tasks\"
4192 Archive in the current file, under the top-level headline
4193 \"* Archived Tasks\".
4195 \"~/org/archive.org::\"
4196 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4198 \"~/org/archive.org::* From %s\"
4199 Archive in file ~/org/archive.org (absolute path), under headlines
4200 \"From FILENAME\" where file name is the current file name.
4202 \"~/org/datetree.org::datetree/* Finished Tasks\"
4203 The \"datetree/\" string is special, signifying to archive
4204 items to the datetree. Items are placed in either the CLOSED
4205 date of the item, or the current date if there is no CLOSED date.
4206 The heading will be a subentry to the current date. There doesn't
4207 need to be a heading, but there always needs to be a slash after
4208 datetree. For example, to store archived items directly in the
4209 datetree, use \"~/org/datetree.org::datetree/\".
4211 \"basement::** Finished Tasks\"
4212 Archive in file ./basement (relative path), as level 3 trees
4213 below the level 2 heading \"** Finished Tasks\".
4215 You may set this option on a per-file basis by adding to the buffer a
4216 line like
4218 #+ARCHIVE: basement::** Finished Tasks
4220 You may also define it locally for a subtree by setting an ARCHIVE property
4221 in the entry. If such a property is found in an entry, or anywhere up
4222 the hierarchy, it will be used."
4223 :group 'org-archive
4224 :type 'string)
4226 (defcustom org-archive-tag "ARCHIVE"
4227 "The tag that marks a subtree as archived.
4228 An archived subtree does not open during visibility cycling, and does
4229 not contribute to the agenda listings.
4230 After changing this, font-lock must be restarted in the relevant buffers to
4231 get the proper fontification."
4232 :group 'org-archive
4233 :group 'org-keywords
4234 :type 'string)
4236 (defcustom org-agenda-skip-archived-trees t
4237 "Non-nil means the agenda will skip any items located in archived trees.
4238 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4239 variable is no longer recommended, you should leave it at the value t.
4240 Instead, use the key `v' to cycle the archives-mode in the agenda."
4241 :group 'org-archive
4242 :group 'org-agenda-skip
4243 :type 'boolean)
4245 (defcustom org-columns-skip-archived-trees t
4246 "Non-nil means ignore archived trees when creating column view."
4247 :group 'org-archive
4248 :group 'org-properties
4249 :type 'boolean)
4251 (defcustom org-cycle-open-archived-trees nil
4252 "Non-nil means `org-cycle' will open archived trees.
4253 An archived tree is a tree marked with the tag ARCHIVE.
4254 When nil, archived trees will stay folded. You can still open them with
4255 normal outline commands like `show-all', but not with the cycling commands."
4256 :group 'org-archive
4257 :group 'org-cycle
4258 :type 'boolean)
4260 (defcustom org-sparse-tree-open-archived-trees nil
4261 "Non-nil means sparse tree construction shows matches in archived trees.
4262 When nil, matches in these trees are highlighted, but the trees are kept in
4263 collapsed state."
4264 :group 'org-archive
4265 :group 'org-sparse-trees
4266 :type 'boolean)
4268 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4269 "The default date type when building a sparse tree.
4270 When this is nil, a date is a scheduled or a deadline timestamp.
4271 Otherwise, these types are allowed:
4273 all: all timestamps
4274 active: only active timestamps (<...>)
4275 inactive: only inactive timestamps (<...)
4276 scheduled: only scheduled timestamps
4277 deadline: only deadline timestamps"
4278 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4279 (const :tag "All timestamps" all)
4280 (const :tag "Only active timestamps" active)
4281 (const :tag "Only inactive timestamps" inactive)
4282 (const :tag "Only scheduled timestamps" scheduled)
4283 (const :tag "Only deadline timestamps" deadline))
4284 :group 'org-sparse-trees
4285 :version "24.2")
4287 (defun org-cycle-hide-archived-subtrees (state)
4288 "Re-hide all archived subtrees after a visibility state change."
4289 (when (and (not org-cycle-open-archived-trees)
4290 (not (memq state '(overview folded))))
4291 (save-excursion
4292 (let* ((globalp (memq state '(contents all)))
4293 (beg (if globalp (point-min) (point)))
4294 (end (if globalp (point-max) (org-end-of-subtree t))))
4295 (org-hide-archived-subtrees beg end)
4296 (goto-char beg)
4297 (if (looking-at (concat ".*:" org-archive-tag ":"))
4298 (message "%s" (substitute-command-keys
4299 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4301 (defun org-force-cycle-archived ()
4302 "Cycle subtree even if it is archived."
4303 (interactive)
4304 (setq this-command 'org-cycle)
4305 (let ((org-cycle-open-archived-trees t))
4306 (call-interactively 'org-cycle)))
4308 (defun org-hide-archived-subtrees (beg end)
4309 "Re-hide all archived subtrees after a visibility state change."
4310 (save-excursion
4311 (let* ((re (concat ":" org-archive-tag ":")))
4312 (goto-char beg)
4313 (while (re-search-forward re end t)
4314 (when (org-at-heading-p)
4315 (org-flag-subtree t)
4316 (org-end-of-subtree t))))))
4318 (defun org-flag-subtree (flag)
4319 (save-excursion
4320 (org-back-to-heading t)
4321 (outline-end-of-heading)
4322 (outline-flag-region (point)
4323 (progn (org-end-of-subtree t) (point))
4324 flag)))
4326 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4328 (eval-and-compile
4329 (org-autoload "org-archive"
4330 '(org-add-archive-files org-archive-subtree
4331 org-archive-to-archive-sibling org-toggle-archive-tag
4332 org-archive-subtree-default
4333 org-archive-subtree-default-with-confirmation)))
4335 ;; Autoload Column View Code
4337 (declare-function org-columns-number-to-string "org-colview")
4338 (declare-function org-columns-get-format-and-top-level "org-colview")
4339 (declare-function org-columns-compute "org-colview")
4341 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4342 '(org-columns-number-to-string org-columns-get-format-and-top-level
4343 org-columns-compute org-agenda-columns org-columns-remove-overlays
4344 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4346 ;; Autoload ID code
4348 (declare-function org-id-store-link "org-id")
4349 (declare-function org-id-locations-load "org-id")
4350 (declare-function org-id-locations-save "org-id")
4351 (defvar org-id-track-globally)
4352 (org-autoload "org-id"
4353 '(org-id-get-create org-id-new org-id-copy org-id-get
4354 org-id-get-with-outline-path-completion
4355 org-id-get-with-outline-drilling org-id-store-link
4356 org-id-goto org-id-find org-id-store-link))
4358 ;; Autoload Plotting Code
4360 (org-autoload "org-plot"
4361 '(org-plot/gnuplot))
4363 ;;; Variables for pre-computed regular expressions, all buffer local
4365 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4366 "Matches first line of a hidden block.")
4367 (make-variable-buffer-local 'org-drawer-regexp)
4368 (defvar org-todo-regexp nil
4369 "Matches any of the TODO state keywords.")
4370 (make-variable-buffer-local 'org-todo-regexp)
4371 (defvar org-not-done-regexp nil
4372 "Matches any of the TODO state keywords except the last one.")
4373 (make-variable-buffer-local 'org-not-done-regexp)
4374 (defvar org-not-done-heading-regexp nil
4375 "Matches a TODO headline that is not done.")
4376 (make-variable-buffer-local 'org-not-done-regexp)
4377 (defvar org-todo-line-regexp nil
4378 "Matches a headline and puts TODO state into group 2 if present.")
4379 (make-variable-buffer-local 'org-todo-line-regexp)
4380 (defvar org-complex-heading-regexp nil
4381 "Matches a headline and puts everything into groups:
4382 group 1: the stars
4383 group 2: The todo keyword, maybe
4384 group 3: Priority cookie
4385 group 4: True headline
4386 group 5: Tags")
4387 (make-variable-buffer-local 'org-complex-heading-regexp)
4388 (defvar org-complex-heading-regexp-format nil
4389 "Printf format to make regexp to match an exact headline.
4390 This regexp will match the headline of any node which has the
4391 exact headline text that is put into the format, but may have any
4392 TODO state, priority and tags.")
4393 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4394 (defvar org-todo-line-tags-regexp nil
4395 "Matches a headline and puts TODO state into group 2 if present.
4396 Also put tags into group 4 if tags are present.")
4397 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4398 (defvar org-ds-keyword-length 12
4399 "Maximum length of the Deadline and SCHEDULED keywords.")
4400 (make-variable-buffer-local 'org-ds-keyword-length)
4401 (defvar org-deadline-regexp nil
4402 "Matches the DEADLINE keyword.")
4403 (make-variable-buffer-local 'org-deadline-regexp)
4404 (defvar org-deadline-time-regexp nil
4405 "Matches the DEADLINE keyword together with a time stamp.")
4406 (make-variable-buffer-local 'org-deadline-time-regexp)
4407 (defvar org-deadline-line-regexp nil
4408 "Matches the DEADLINE keyword and the rest of the line.")
4409 (make-variable-buffer-local 'org-deadline-line-regexp)
4410 (defvar org-scheduled-regexp nil
4411 "Matches the SCHEDULED keyword.")
4412 (make-variable-buffer-local 'org-scheduled-regexp)
4413 (defvar org-scheduled-time-regexp nil
4414 "Matches the SCHEDULED keyword together with a time stamp.")
4415 (make-variable-buffer-local 'org-scheduled-time-regexp)
4416 (defvar org-closed-time-regexp nil
4417 "Matches the CLOSED keyword together with a time stamp.")
4418 (make-variable-buffer-local 'org-closed-time-regexp)
4420 (defvar org-keyword-time-regexp nil
4421 "Matches any of the 4 keywords, together with the time stamp.")
4422 (make-variable-buffer-local 'org-keyword-time-regexp)
4423 (defvar org-keyword-time-not-clock-regexp nil
4424 "Matches any of the 3 keywords, together with the time stamp.")
4425 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4426 (defvar org-maybe-keyword-time-regexp nil
4427 "Matches a timestamp, possibly preceded by a keyword.")
4428 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4429 (defvar org-all-time-keywords nil
4430 "List of time keywords.")
4431 (make-variable-buffer-local 'org-all-time-keywords)
4433 (defconst org-plain-time-of-day-regexp
4434 (concat
4435 "\\(\\<[012]?[0-9]"
4436 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4437 "\\(--?"
4438 "\\(\\<[012]?[0-9]"
4439 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4440 "\\)?")
4441 "Regular expression to match a plain time or time range.
4442 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4443 groups carry important information:
4444 0 the full match
4445 1 the first time, range or not
4446 8 the second time, if it is a range.")
4448 (defconst org-plain-time-extension-regexp
4449 (concat
4450 "\\(\\<[012]?[0-9]"
4451 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4452 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4453 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4454 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4455 groups carry important information:
4456 0 the full match
4457 7 hours of duration
4458 9 minutes of duration")
4460 (defconst org-stamp-time-of-day-regexp
4461 (concat
4462 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4463 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4464 "\\(--?"
4465 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4466 "Regular expression to match a timestamp time or time range.
4467 After a match, the following groups carry important information:
4468 0 the full match
4469 1 date plus weekday, for back referencing to make sure both times are on the same day
4470 2 the first time, range or not
4471 4 the second time, if it is a range.")
4473 (defconst org-startup-options
4474 '(("fold" org-startup-folded t)
4475 ("overview" org-startup-folded t)
4476 ("nofold" org-startup-folded nil)
4477 ("showall" org-startup-folded nil)
4478 ("showeverything" org-startup-folded showeverything)
4479 ("content" org-startup-folded content)
4480 ("indent" org-startup-indented t)
4481 ("noindent" org-startup-indented nil)
4482 ("hidestars" org-hide-leading-stars t)
4483 ("showstars" org-hide-leading-stars nil)
4484 ("odd" org-odd-levels-only t)
4485 ("oddeven" org-odd-levels-only nil)
4486 ("align" org-startup-align-all-tables t)
4487 ("noalign" org-startup-align-all-tables nil)
4488 ("inlineimages" org-startup-with-inline-images t)
4489 ("noinlineimages" org-startup-with-inline-images nil)
4490 ("customtime" org-display-custom-times t)
4491 ("logdone" org-log-done time)
4492 ("lognotedone" org-log-done note)
4493 ("nologdone" org-log-done nil)
4494 ("lognoteclock-out" org-log-note-clock-out t)
4495 ("nolognoteclock-out" org-log-note-clock-out nil)
4496 ("logrepeat" org-log-repeat state)
4497 ("lognoterepeat" org-log-repeat note)
4498 ("nologrepeat" org-log-repeat nil)
4499 ("logreschedule" org-log-reschedule time)
4500 ("lognotereschedule" org-log-reschedule note)
4501 ("nologreschedule" org-log-reschedule nil)
4502 ("logredeadline" org-log-redeadline time)
4503 ("lognoteredeadline" org-log-redeadline note)
4504 ("nologredeadline" org-log-redeadline nil)
4505 ("logrefile" org-log-refile time)
4506 ("lognoterefile" org-log-refile note)
4507 ("nologrefile" org-log-refile nil)
4508 ("fninline" org-footnote-define-inline t)
4509 ("nofninline" org-footnote-define-inline nil)
4510 ("fnlocal" org-footnote-section nil)
4511 ("fnauto" org-footnote-auto-label t)
4512 ("fnprompt" org-footnote-auto-label nil)
4513 ("fnconfirm" org-footnote-auto-label confirm)
4514 ("fnplain" org-footnote-auto-label plain)
4515 ("fnadjust" org-footnote-auto-adjust t)
4516 ("nofnadjust" org-footnote-auto-adjust nil)
4517 ("constcgs" constants-unit-system cgs)
4518 ("constSI" constants-unit-system SI)
4519 ("noptag" org-tag-persistent-alist nil)
4520 ("hideblocks" org-hide-block-startup t)
4521 ("nohideblocks" org-hide-block-startup nil)
4522 ("beamer" org-startup-with-beamer-mode t)
4523 ("entitiespretty" org-pretty-entities t)
4524 ("entitiesplain" org-pretty-entities nil))
4525 "Variable associated with STARTUP options for org-mode.
4526 Each element is a list of three items: the startup options (as written
4527 in the #+STARTUP line), the corresponding variable, and the value to set
4528 this variable to if the option is found. An optional forth element PUSH
4529 means to push this value onto the list in the variable.")
4531 (defun org-update-property-plist (key val props)
4532 "Update PROPS with KEY and VAL."
4533 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4534 (key (if appending (substring key 0 (- (length key) 1)) key))
4535 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4536 (previous (cdr (assoc key props))))
4537 (if appending
4538 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4539 (cons (cons key val) remainder))))
4541 (defconst org-block-regexp
4542 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4543 "Regular expression for hiding blocks.")
4544 (defconst org-heading-keyword-regexp-format
4545 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4546 "Printf format for a regexp matching an headline with some keyword.
4547 This regexp will match the headline of any node which has the
4548 exact keyword that is put into the format. The keyword isn't in
4549 any group by default, but the stars and the body are.")
4550 (defconst org-heading-keyword-maybe-regexp-format
4551 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4552 "Printf format for a regexp matching an headline, possibly with some keyword.
4553 This regexp can match any headline with the specified keyword, or
4554 without a keyword. The keyword isn't in any group by default,
4555 but the stars and the body are.")
4557 (defun org-set-regexps-and-options ()
4558 "Precompute regular expressions for current buffer."
4559 (when (derived-mode-p 'org-mode)
4560 (org-set-local 'org-todo-kwd-alist nil)
4561 (org-set-local 'org-todo-key-alist nil)
4562 (org-set-local 'org-todo-key-trigger nil)
4563 (org-set-local 'org-todo-keywords-1 nil)
4564 (org-set-local 'org-done-keywords nil)
4565 (org-set-local 'org-todo-heads nil)
4566 (org-set-local 'org-todo-sets nil)
4567 (org-set-local 'org-todo-log-states nil)
4568 (org-set-local 'org-file-properties nil)
4569 (org-set-local 'org-file-tags nil)
4570 (let ((re (org-make-options-regexp
4571 '("CATEGORY" "TODO" "COLUMNS"
4572 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4573 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4574 "OPTIONS")
4575 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4576 (splitre "[ \t]+")
4577 (scripts org-use-sub-superscripts)
4578 kwds kws0 kwsa key log value cat arch tags const links hw dws
4579 tail sep kws1 prio props ftags drawers beamer-p
4580 ext-setup-or-nil setup-contents (start 0))
4581 (save-excursion
4582 (save-restriction
4583 (widen)
4584 (goto-char (point-min))
4585 (while (or (and ext-setup-or-nil
4586 (string-match re ext-setup-or-nil start)
4587 (setq start (match-end 0)))
4588 (and (setq ext-setup-or-nil nil start 0)
4589 (re-search-forward re nil t)))
4590 (setq key (upcase (match-string 1 ext-setup-or-nil))
4591 value (org-match-string-no-properties 2 ext-setup-or-nil))
4592 (if (stringp value) (setq value (org-trim value)))
4593 (cond
4594 ((equal key "CATEGORY")
4595 (setq cat value))
4596 ((member key '("SEQ_TODO" "TODO"))
4597 (push (cons 'sequence (org-split-string value splitre)) kwds))
4598 ((equal key "TYP_TODO")
4599 (push (cons 'type (org-split-string value splitre)) kwds))
4600 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4601 ;; general TODO-like setup
4602 (push (cons (intern (downcase (match-string 1 key)))
4603 (org-split-string value splitre)) kwds))
4604 ((equal key "TAGS")
4605 (setq tags (append tags (if tags '("\\n") nil)
4606 (org-split-string value splitre))))
4607 ((equal key "COLUMNS")
4608 (org-set-local 'org-columns-default-format value))
4609 ((equal key "LINK")
4610 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4611 (push (cons (match-string 1 value)
4612 (org-trim (match-string 2 value)))
4613 links)))
4614 ((equal key "PRIORITIES")
4615 (setq prio (org-split-string value " +")))
4616 ((equal key "PROPERTY")
4617 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4618 (setq props (org-update-property-plist (match-string 1 value)
4619 (match-string 2 value)
4620 props))))
4621 ((equal key "FILETAGS")
4622 (when (string-match "\\S-" value)
4623 (setq ftags
4624 (append
4625 ftags
4626 (apply 'append
4627 (mapcar (lambda (x) (org-split-string x ":"))
4628 (org-split-string value)))))))
4629 ((equal key "DRAWERS")
4630 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4631 ((equal key "CONSTANTS")
4632 (setq const (append const (org-split-string value splitre))))
4633 ((equal key "STARTUP")
4634 (let ((opts (org-split-string value splitre))
4635 l var val)
4636 (while (setq l (pop opts))
4637 (when (setq l (assoc l org-startup-options))
4638 (setq var (nth 1 l) val (nth 2 l))
4639 (if (not (nth 3 l))
4640 (set (make-local-variable var) val)
4641 (if (not (listp (symbol-value var)))
4642 (set (make-local-variable var) nil))
4643 (set (make-local-variable var) (symbol-value var))
4644 (add-to-list var val))))))
4645 ((equal key "ARCHIVE")
4646 (setq arch value)
4647 (remove-text-properties 0 (length arch)
4648 '(face t fontified t) arch))
4649 ((equal key "LATEX_CLASS")
4650 (setq beamer-p (equal value "beamer")))
4651 ((equal key "OPTIONS")
4652 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4653 (setq scripts (read (match-string 2 value)))))
4654 ((equal key "SETUPFILE")
4655 (setq setup-contents (org-file-contents
4656 (expand-file-name
4657 (org-remove-double-quotes value))
4658 'noerror))
4659 (if (not ext-setup-or-nil)
4660 (setq ext-setup-or-nil setup-contents start 0)
4661 (setq ext-setup-or-nil
4662 (concat (substring ext-setup-or-nil 0 start)
4663 "\n" setup-contents "\n"
4664 (substring ext-setup-or-nil start)))))))
4665 ;; search for property blocks
4666 (goto-char (point-min))
4667 (while (re-search-forward org-block-regexp nil t)
4668 (when (equal "PROPERTY" (upcase (match-string 1)))
4669 (setq value (replace-regexp-in-string
4670 "[\n\r]" " " (match-string 4)))
4671 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4672 (setq props (org-update-property-plist (match-string 1 value)
4673 (match-string 2 value)
4674 props)))))))
4675 (org-set-local 'org-use-sub-superscripts scripts)
4676 (when cat
4677 (org-set-local 'org-category (intern cat))
4678 (push (cons "CATEGORY" cat) props))
4679 (when prio
4680 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4681 (setq prio (mapcar 'string-to-char prio))
4682 (org-set-local 'org-highest-priority (nth 0 prio))
4683 (org-set-local 'org-lowest-priority (nth 1 prio))
4684 (org-set-local 'org-default-priority (nth 2 prio)))
4685 (and props (org-set-local 'org-file-properties (nreverse props)))
4686 (and ftags (org-set-local 'org-file-tags
4687 (mapcar 'org-add-prop-inherited ftags)))
4688 (and drawers (org-set-local 'org-drawers drawers))
4689 (and arch (org-set-local 'org-archive-location arch))
4690 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4691 ;; Process the TODO keywords
4692 (unless kwds
4693 ;; Use the global values as if they had been given locally.
4694 (setq kwds (default-value 'org-todo-keywords))
4695 (if (stringp (car kwds))
4696 (setq kwds (list (cons org-todo-interpretation
4697 (default-value 'org-todo-keywords)))))
4698 (setq kwds (reverse kwds)))
4699 (setq kwds (nreverse kwds))
4700 (let (inter kws kw)
4701 (while (setq kws (pop kwds))
4702 (let ((kws (or
4703 (run-hook-with-args-until-success
4704 'org-todo-setup-filter-hook kws)
4705 kws)))
4706 (setq inter (pop kws) sep (member "|" kws)
4707 kws0 (delete "|" (copy-sequence kws))
4708 kwsa nil
4709 kws1 (mapcar
4710 (lambda (x)
4711 ;; 1 2
4712 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4713 (progn
4714 (setq kw (match-string 1 x)
4715 key (and (match-end 2) (match-string 2 x))
4716 log (org-extract-log-state-settings x))
4717 (push (cons kw (and key (string-to-char key))) kwsa)
4718 (and log (push log org-todo-log-states))
4720 (error "Invalid TODO keyword %s" x)))
4721 kws0)
4722 kwsa (if kwsa (append '((:startgroup))
4723 (nreverse kwsa)
4724 '((:endgroup))))
4725 hw (car kws1)
4726 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4727 tail (list inter hw (car dws) (org-last dws))))
4728 (add-to-list 'org-todo-heads hw 'append)
4729 (push kws1 org-todo-sets)
4730 (setq org-done-keywords (append org-done-keywords dws nil))
4731 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4732 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4733 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4734 (setq org-todo-sets (nreverse org-todo-sets)
4735 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4736 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4737 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4738 ;; Process the constants
4739 (when const
4740 (let (e cst)
4741 (while (setq e (pop const))
4742 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4743 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4744 (setq org-table-formula-constants-local cst)))
4746 ;; Process the tags.
4747 (when tags
4748 (let (e tgs)
4749 (while (setq e (pop tags))
4750 (cond
4751 ((equal e "{") (push '(:startgroup) tgs))
4752 ((equal e "}") (push '(:endgroup) tgs))
4753 ((equal e "\\n") (push '(:newline) tgs))
4754 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4755 (push (cons (match-string 1 e)
4756 (string-to-char (match-string 2 e)))
4757 tgs))
4758 (t (push (list e) tgs))))
4759 (org-set-local 'org-tag-alist nil)
4760 (while (setq e (pop tgs))
4761 (or (and (stringp (car e))
4762 (assoc (car e) org-tag-alist))
4763 (push e org-tag-alist)))))
4765 ;; Compute the regular expressions and other local variables.
4766 ;; Using `org-outline-regexp-bol' would complicate them much,
4767 ;; because of the fixed white space at the end of that string.
4768 (if (not org-done-keywords)
4769 (setq org-done-keywords (and org-todo-keywords-1
4770 (list (org-last org-todo-keywords-1)))))
4771 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4772 (length org-scheduled-string)
4773 (length org-clock-string)
4774 (length org-closed-string)))
4775 org-drawer-regexp
4776 (concat "^[ \t]*:\\("
4777 (mapconcat 'regexp-quote org-drawers "\\|")
4778 "\\):[ \t]*$")
4779 org-not-done-keywords
4780 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4781 org-todo-regexp
4782 (concat "\\("
4783 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4784 "\\)")
4785 org-not-done-regexp
4786 (concat "\\("
4787 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4788 "\\)")
4789 org-not-done-heading-regexp
4790 (format org-heading-keyword-regexp-format org-not-done-regexp)
4791 org-todo-line-regexp
4792 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4793 org-complex-heading-regexp
4794 (concat "^\\(\\*+\\)"
4795 "\\(?: +" org-todo-regexp "\\)?"
4796 "\\(?: +\\(\\[#.\\]\\)\\)?"
4797 "\\(?: +\\(.*?\\)\\)?"
4798 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4799 "[ \t]*$")
4800 org-complex-heading-regexp-format
4801 (concat "^\\(\\*+\\)"
4802 "\\(?: +" org-todo-regexp "\\)?"
4803 "\\(?: +\\(\\[#.\\]\\)\\)?"
4804 "\\(?: +"
4805 ;; Stats cookies can be stuck to body.
4806 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4807 "\\(%s\\)"
4808 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4809 "\\)"
4810 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4811 "[ \t]*$")
4812 org-todo-line-tags-regexp
4813 (concat "^\\(\\*+\\)"
4814 "\\(?: +" org-todo-regexp "\\)?"
4815 "\\(?: +\\(.*?\\)\\)?"
4816 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4817 "[ \t]*$")
4818 org-deadline-regexp (concat "\\<" org-deadline-string)
4819 org-deadline-time-regexp
4820 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4821 org-deadline-line-regexp
4822 (concat "\\<\\(" org-deadline-string "\\).*")
4823 org-scheduled-regexp
4824 (concat "\\<" org-scheduled-string)
4825 org-scheduled-time-regexp
4826 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4827 org-closed-time-regexp
4828 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4829 org-keyword-time-regexp
4830 (concat "\\<\\(" org-scheduled-string
4831 "\\|" org-deadline-string
4832 "\\|" org-closed-string
4833 "\\|" org-clock-string "\\)"
4834 " *[[<]\\([^]>]+\\)[]>]")
4835 org-keyword-time-not-clock-regexp
4836 (concat "\\<\\(" org-scheduled-string
4837 "\\|" org-deadline-string
4838 "\\|" org-closed-string
4839 "\\)"
4840 " *[[<]\\([^]>]+\\)[]>]")
4841 org-maybe-keyword-time-regexp
4842 (concat "\\(\\<\\(" org-scheduled-string
4843 "\\|" org-deadline-string
4844 "\\|" org-closed-string
4845 "\\|" org-clock-string "\\)\\)?"
4846 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4847 org-all-time-keywords
4848 (mapcar (lambda (w) (substring w 0 -1))
4849 (list org-scheduled-string org-deadline-string
4850 org-clock-string org-closed-string))
4852 (org-compute-latex-and-specials-regexp)
4853 (org-set-font-lock-defaults))))
4855 (defun org-file-contents (file &optional noerror)
4856 "Return the contents of FILE, as a string."
4857 (if (or (not file)
4858 (not (file-readable-p file)))
4859 (if noerror
4860 (progn
4861 (message "Cannot read file \"%s\"" file)
4862 (ding) (sit-for 2)
4864 (error "Cannot read file \"%s\"" file))
4865 (with-temp-buffer
4866 (insert-file-contents file)
4867 (buffer-string))))
4869 (defun org-extract-log-state-settings (x)
4870 "Extract the log state setting from a TODO keyword string.
4871 This will extract info from a string like \"WAIT(w@/!)\"."
4872 (let (kw key log1 log2)
4873 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4874 (setq kw (match-string 1 x)
4875 key (and (match-end 2) (match-string 2 x))
4876 log1 (and (match-end 3) (match-string 3 x))
4877 log2 (and (match-end 4) (match-string 4 x)))
4878 (and (or log1 log2)
4879 (list kw
4880 (and log1 (if (equal log1 "!") 'time 'note))
4881 (and log2 (if (equal log2 "!") 'time 'note)))))))
4883 (defun org-remove-keyword-keys (list)
4884 "Remove a pair of parenthesis at the end of each string in LIST."
4885 (mapcar (lambda (x)
4886 (if (string-match "(.*)$" x)
4887 (substring x 0 (match-beginning 0))
4889 list))
4891 (defun org-assign-fast-keys (alist)
4892 "Assign fast keys to a keyword-key alist.
4893 Respect keys that are already there."
4894 (let (new e (alt ?0))
4895 (while (setq e (pop alist))
4896 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4897 (cdr e)) ;; Key already assigned.
4898 (push e new)
4899 (let ((clist (string-to-list (downcase (car e))))
4900 (used (append new alist)))
4901 (when (= (car clist) ?@)
4902 (pop clist))
4903 (while (and clist (rassoc (car clist) used))
4904 (pop clist))
4905 (unless clist
4906 (while (rassoc alt used)
4907 (incf alt)))
4908 (push (cons (car e) (or (car clist) alt)) new))))
4909 (nreverse new)))
4911 ;;; Some variables used in various places
4913 (defvar org-window-configuration nil
4914 "Used in various places to store a window configuration.")
4915 (defvar org-selected-window nil
4916 "Used in various places to store a window configuration.")
4917 (defvar org-finish-function nil
4918 "Function to be called when `C-c C-c' is used.
4919 This is for getting out of special buffers like remember.")
4922 ;; FIXME: Occasionally check by commenting these, to make sure
4923 ;; no other functions uses these, forgetting to let-bind them.
4924 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4925 (defvar org-last-state)
4926 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4928 ;; Defined somewhere in this file, but used before definition.
4929 (defvar org-entities) ;; defined in org-entities.el
4930 (defvar org-struct-menu)
4931 (defvar org-org-menu)
4932 (defvar org-tbl-menu)
4934 ;;;; Define the Org-mode
4936 ;; We use a before-change function to check if a table might need
4937 ;; an update.
4938 (defvar org-table-may-need-update t
4939 "Indicates that a table might need an update.
4940 This variable is set by `org-before-change-function'.
4941 `org-table-align' sets it back to nil.")
4942 (defun org-before-change-function (beg end)
4943 "Every change indicates that a table might need an update."
4944 (setq org-table-may-need-update t))
4945 (defvar org-mode-map)
4946 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4947 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4948 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4949 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4950 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4951 (defvar org-table-buffer-is-an nil)
4953 (defvar bidi-paragraph-direction)
4954 (defvar buffer-face-mode-face)
4956 (require 'outline)
4957 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4958 (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"))
4959 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4961 ;; Other stuff we need.
4962 (require 'time-date)
4963 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4964 (require 'easymenu)
4965 (require 'overlay)
4967 (require 'org-macs)
4968 (require 'org-entities)
4969 (require 'org-compat)
4970 (require 'org-faces)
4971 (require 'org-list)
4972 (require 'org-pcomplete)
4973 (require 'org-src)
4974 (require 'org-footnote)
4975 (require 'org-element)
4977 ;; babel
4978 (require 'ob)
4979 (require 'ob-table)
4980 (require 'ob-lob)
4981 (require 'ob-ref)
4982 (require 'ob-tangle)
4983 (require 'ob-comint)
4984 (require 'ob-keys)
4986 ;;;###autoload
4987 (define-derived-mode org-mode outline-mode "Org"
4988 "Outline-based notes management and organizer, alias
4989 \"Carsten's outline-mode for keeping track of everything.\"
4991 Org-mode develops organizational tasks around a NOTES file which
4992 contains information about projects as plain text. Org-mode is
4993 implemented on top of outline-mode, which is ideal to keep the content
4994 of large files well structured. It supports ToDo items, deadlines and
4995 time stamps, which magically appear in the diary listing of the Emacs
4996 calendar. Tables are easily created with a built-in table editor.
4997 Plain text URL-like links connect to websites, emails (VM), Usenet
4998 messages (Gnus), BBDB entries, and any files related to the project.
4999 For printing and sharing of notes, an Org-mode file (or a part of it)
5000 can be exported as a structured ASCII or HTML file.
5002 The following commands are available:
5004 \\{org-mode-map}"
5006 ;; Get rid of Outline menus, they are not needed
5007 ;; Need to do this here because define-derived-mode sets up
5008 ;; the keymap so late. Still, it is a waste to call this each time
5009 ;; we switch another buffer into org-mode.
5010 (if (featurep 'xemacs)
5011 (when (boundp 'outline-mode-menu-heading)
5012 ;; Assume this is Greg's port, it uses easymenu
5013 (easy-menu-remove outline-mode-menu-heading)
5014 (easy-menu-remove outline-mode-menu-show)
5015 (easy-menu-remove outline-mode-menu-hide))
5016 (define-key org-mode-map [menu-bar headings] 'undefined)
5017 (define-key org-mode-map [menu-bar hide] 'undefined)
5018 (define-key org-mode-map [menu-bar show] 'undefined))
5020 (org-load-modules-maybe)
5021 (easy-menu-add org-org-menu)
5022 (easy-menu-add org-tbl-menu)
5023 (org-install-agenda-files-menu)
5024 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5025 (add-to-invisibility-spec '(org-cwidth))
5026 (add-to-invisibility-spec '(org-hide-block . t))
5027 (when (featurep 'xemacs)
5028 (org-set-local 'line-move-ignore-invisible t))
5029 (org-set-local 'outline-regexp org-outline-regexp)
5030 (org-set-local 'outline-level 'org-outline-level)
5031 (setq bidi-paragraph-direction 'left-to-right)
5032 (when (and org-ellipsis
5033 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5034 (fboundp 'make-glyph-code))
5035 (unless org-display-table
5036 (setq org-display-table (make-display-table)))
5037 (set-display-table-slot
5038 org-display-table 4
5039 (vconcat (mapcar
5040 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5041 org-ellipsis)))
5042 (if (stringp org-ellipsis) org-ellipsis "..."))))
5043 (setq buffer-display-table org-display-table))
5044 (org-set-regexps-and-options)
5045 (when (and org-tag-faces (not org-tags-special-faces-re))
5046 ;; tag faces set outside customize.... force initialization.
5047 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5048 ;; Calc embedded
5049 (org-set-local 'calc-embedded-open-mode "# ")
5050 (modify-syntax-entry ?@ "w")
5051 (if org-startup-truncated (setq truncate-lines t))
5052 (org-set-local 'font-lock-unfontify-region-function
5053 'org-unfontify-region)
5054 ;; Activate before-change-function
5055 (org-set-local 'org-table-may-need-update t)
5056 (org-add-hook 'before-change-functions 'org-before-change-function nil
5057 'local)
5058 ;; Check for running clock before killing a buffer
5059 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5060 ;; Paragraphs and auto-filling
5061 (org-set-autofill-regexps)
5062 (org-set-local 'indent-line-function 'org-indent-line)
5063 (org-set-local 'indent-region-function 'org-indent-region)
5064 (org-update-radio-target-regexp)
5065 ;; Comments
5066 (org-set-local 'comment-use-syntax nil)
5067 (org-set-local 'comment-start "#")
5068 (org-set-local 'comment-start-skip "# ?")
5069 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
5070 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
5071 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region)
5072 ;; Beginning/end of defun
5073 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
5074 (org-set-local 'end-of-defun-function 'org-end-of-defun)
5075 ;; Next error for sparse trees
5076 (org-set-local 'next-error-function 'org-occur-next-match)
5077 ;; Make sure dependence stuff works reliably, even for users who set it
5078 ;; too late :-(
5079 (if org-enforce-todo-dependencies
5080 (add-hook 'org-blocker-hook
5081 'org-block-todo-from-children-or-siblings-or-parent)
5082 (remove-hook 'org-blocker-hook
5083 'org-block-todo-from-children-or-siblings-or-parent))
5084 (if org-enforce-todo-checkbox-dependencies
5085 (add-hook 'org-blocker-hook
5086 'org-block-todo-from-checkboxes)
5087 (remove-hook 'org-blocker-hook
5088 'org-block-todo-from-checkboxes))
5090 ;; Align options lines
5091 (org-set-local
5092 'align-mode-rules-list
5093 '((org-in-buffer-settings
5094 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5095 (modes . '(org-mode)))))
5097 ;; Imenu
5098 (org-set-local 'imenu-create-index-function
5099 'org-imenu-get-tree)
5101 ;; Make isearch reveal context
5102 (if (or (featurep 'xemacs)
5103 (not (boundp 'outline-isearch-open-invisible-function)))
5104 ;; Emacs 21 and XEmacs make use of the hook
5105 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5106 ;; Emacs 22 deals with this through a special variable
5107 (org-set-local 'outline-isearch-open-invisible-function
5108 (lambda (&rest ignore) (org-show-context 'isearch))))
5110 ;; Turn on org-beamer-mode?
5111 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5113 ;; Setup the pcomplete hooks
5114 (set (make-local-variable 'pcomplete-command-completion-function)
5115 'org-pcomplete-initial)
5116 (set (make-local-variable 'pcomplete-command-name-function)
5117 'org-command-at-point)
5118 (set (make-local-variable 'pcomplete-default-completion-function)
5119 'ignore)
5120 (set (make-local-variable 'pcomplete-parse-arguments-function)
5121 'org-parse-arguments)
5122 (set (make-local-variable 'pcomplete-termination-string) "")
5123 (when (>= emacs-major-version 23)
5124 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5126 ;; If empty file that did not turn on org-mode automatically, make it to.
5127 (if (and org-insert-mode-line-in-empty-file
5128 (org-called-interactively-p 'any)
5129 (= (point-min) (point-max)))
5130 (insert "# -*- mode: org -*-\n\n"))
5131 (unless org-inhibit-startup
5132 (when org-startup-align-all-tables
5133 (let ((bmp (buffer-modified-p)))
5134 (org-table-map-tables 'org-table-align 'quietly)
5135 (set-buffer-modified-p bmp)))
5136 (when org-startup-with-inline-images
5137 (org-display-inline-images))
5138 (when org-startup-indented
5139 (require 'org-indent)
5140 (org-indent-mode 1))
5141 (unless org-inhibit-startup-visibility-stuff
5142 (org-set-startup-visibility))))
5144 (when (fboundp 'abbrev-table-put)
5145 (abbrev-table-put org-mode-abbrev-table
5146 :parents (list text-mode-abbrev-table)))
5148 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5150 (defun org-current-time ()
5151 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5152 (if (> (car org-time-stamp-rounding-minutes) 1)
5153 (let ((r (car org-time-stamp-rounding-minutes))
5154 (time (decode-time)))
5155 (apply 'encode-time
5156 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5157 (nthcdr 2 time))))
5158 (current-time)))
5160 (defun org-today ()
5161 "Return today date, considering `org-extend-today-until'."
5162 (time-to-days
5163 (time-subtract (current-time)
5164 (list 0 (* 3600 org-extend-today-until) 0))))
5166 ;;;; Font-Lock stuff, including the activators
5168 (defvar org-mouse-map (make-sparse-keymap))
5169 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5170 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5171 (when org-mouse-1-follows-link
5172 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5173 (when org-tab-follows-link
5174 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5175 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5177 (require 'font-lock)
5179 (defconst org-non-link-chars "]\t\n\r<>")
5180 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5181 "shell" "elisp" "doi" "message"))
5182 (defvar org-link-types-re nil
5183 "Matches a link that has a url-like prefix like \"http:\"")
5184 (defvar org-link-re-with-space nil
5185 "Matches a link with spaces, optional angular brackets around it.")
5186 (defvar org-link-re-with-space2 nil
5187 "Matches a link with spaces, optional angular brackets around it.")
5188 (defvar org-link-re-with-space3 nil
5189 "Matches a link with spaces, only for internal part in bracket links.")
5190 (defvar org-angle-link-re nil
5191 "Matches link with angular brackets, spaces are allowed.")
5192 (defvar org-plain-link-re nil
5193 "Matches plain link, without spaces.")
5194 (defvar org-bracket-link-regexp nil
5195 "Matches a link in double brackets.")
5196 (defvar org-bracket-link-analytic-regexp nil
5197 "Regular expression used to analyze links.
5198 Here is what the match groups contain after a match:
5199 1: http:
5200 2: http
5201 3: path
5202 4: [desc]
5203 5: desc")
5204 (defvar org-bracket-link-analytic-regexp++ nil
5205 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5206 (defvar org-any-link-re nil
5207 "Regular expression matching any link.")
5209 (defcustom org-match-sexp-depth 3
5210 "Number of stacked braces for sub/superscript matching.
5211 This has to be set before loading org.el to be effective."
5212 :group 'org-export-translation ; ??????????????????????????/
5213 :type 'integer)
5215 (defun org-create-multibrace-regexp (left right n)
5216 "Create a regular expression which will match a balanced sexp.
5217 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5218 as single character strings.
5219 The regexp returned will match the entire expression including the
5220 delimiters. It will also define a single group which contains the
5221 match except for the outermost delimiters. The maximum depth of
5222 stacked delimiters is N. Escaping delimiters is not possible."
5223 (let* ((nothing (concat "[^" left right "]*?"))
5224 (or "\\|")
5225 (re nothing)
5226 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5227 (while (> n 1)
5228 (setq n (1- n)
5229 re (concat re or next)
5230 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5231 (concat left "\\(" re "\\)" right)))
5233 (defvar org-match-substring-regexp
5234 (concat
5235 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5236 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5237 "\\|"
5238 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5239 "\\|"
5240 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5241 "The regular expression matching a sub- or superscript.")
5243 (defvar org-match-substring-with-braces-regexp
5244 (concat
5245 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5246 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5247 "\\)")
5248 "The regular expression matching a sub- or superscript, forcing braces.")
5250 (defun org-make-link-regexps ()
5251 "Update the link regular expressions.
5252 This should be called after the variable `org-link-types' has changed."
5253 (setq org-link-types-re
5254 (concat
5255 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5256 org-link-re-with-space
5257 (concat
5258 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5259 "\\([^" org-non-link-chars " ]"
5260 "[^" org-non-link-chars "]*"
5261 "[^" org-non-link-chars " ]\\)>?")
5262 org-link-re-with-space2
5263 (concat
5264 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5265 "\\([^" org-non-link-chars " ]"
5266 "[^\t\n\r]*"
5267 "[^" org-non-link-chars " ]\\)>?")
5268 org-link-re-with-space3
5269 (concat
5270 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5271 "\\([^" org-non-link-chars " ]"
5272 "[^\t\n\r]*\\)")
5273 org-angle-link-re
5274 (concat
5275 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5276 "\\([^" org-non-link-chars " ]"
5277 "[^" org-non-link-chars "]*"
5278 "\\)>")
5279 org-plain-link-re
5280 (concat
5281 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5282 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5283 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5284 org-bracket-link-regexp
5285 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5286 org-bracket-link-analytic-regexp
5287 (concat
5288 "\\[\\["
5289 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5290 "\\([^]]+\\)"
5291 "\\]"
5292 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5293 "\\]")
5294 org-bracket-link-analytic-regexp++
5295 (concat
5296 "\\[\\["
5297 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5298 "\\([^]]+\\)"
5299 "\\]"
5300 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5301 "\\]")
5302 org-any-link-re
5303 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5304 org-angle-link-re "\\)\\|\\("
5305 org-plain-link-re "\\)")))
5307 (org-make-link-regexps)
5309 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5310 "Regular expression for fast time stamp matching.")
5311 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5312 "Regular expression for fast time stamp matching.")
5313 (defconst org-ts-regexp0
5314 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5315 "Regular expression matching time strings for analysis.
5316 This one does not require the space after the date, so it can be used
5317 on a string that terminates immediately after the date.")
5318 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5319 "Regular expression matching time strings for analysis.")
5320 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5321 "Regular expression matching time stamps, with groups.")
5322 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5323 "Regular expression matching time stamps (also [..]), with groups.")
5324 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5325 "Regular expression matching a time stamp range.")
5326 (defconst org-tr-regexp-both
5327 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5328 "Regular expression matching a time stamp range.")
5329 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5330 org-ts-regexp "\\)?")
5331 "Regular expression matching a time stamp or time stamp range.")
5332 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5333 org-ts-regexp-both "\\)?")
5334 "Regular expression matching a time stamp or time stamp range.
5335 The time stamps may be either active or inactive.")
5337 (defvar org-emph-face nil)
5339 (defun org-do-emphasis-faces (limit)
5340 "Run through the buffer and add overlays to emphasized strings."
5341 (let (rtn a)
5342 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5343 (if (not (= (char-after (match-beginning 3))
5344 (char-after (match-beginning 4))))
5345 (progn
5346 (setq rtn t)
5347 (setq a (assoc (match-string 3) org-emphasis-alist))
5348 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5349 'face
5350 (nth 1 a))
5351 (and (nth 4 a)
5352 (org-remove-flyspell-overlays-in
5353 (match-beginning 0) (match-end 0)))
5354 (add-text-properties (match-beginning 2) (match-end 2)
5355 '(font-lock-multiline t org-emphasis t))
5356 (when org-hide-emphasis-markers
5357 (add-text-properties (match-end 4) (match-beginning 5)
5358 '(invisible org-link))
5359 (add-text-properties (match-beginning 3) (match-end 3)
5360 '(invisible org-link)))))
5361 (backward-char 1))
5362 rtn))
5364 (defun org-emphasize (&optional char)
5365 "Insert or change an emphasis, i.e. a font like bold or italic.
5366 If there is an active region, change that region to a new emphasis.
5367 If there is no region, just insert the marker characters and position
5368 the cursor between them.
5369 CHAR should be either the marker character, or the first character of the
5370 HTML tag associated with that emphasis. If CHAR is a space, the means
5371 to remove the emphasis of the selected region.
5372 If char is not given (for example in an interactive call) it
5373 will be prompted for."
5374 (interactive)
5375 (let ((eal org-emphasis-alist) e det
5376 (erc org-emphasis-regexp-components)
5377 (prompt "")
5378 (string "") beg end move tag c s)
5379 (if (org-region-active-p)
5380 (setq beg (region-beginning) end (region-end)
5381 string (buffer-substring beg end))
5382 (setq move t))
5384 (while (setq e (pop eal))
5385 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5386 c (aref tag 0))
5387 (push (cons c (string-to-char (car e))) det)
5388 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5389 (substring tag 1)))))
5390 (setq det (nreverse det))
5391 (unless char
5392 (message "%s" (concat "Emphasis marker or tag:" prompt))
5393 (setq char (read-char-exclusive)))
5394 (setq char (or (cdr (assoc char det)) char))
5395 (if (equal char ?\ )
5396 (setq s "" move nil)
5397 (unless (assoc (char-to-string char) org-emphasis-alist)
5398 (error "No such emphasis marker: \"%c\"" char))
5399 (setq s (char-to-string char)))
5400 (while (and (> (length string) 1)
5401 (equal (substring string 0 1) (substring string -1))
5402 (assoc (substring string 0 1) org-emphasis-alist))
5403 (setq string (substring string 1 -1)))
5404 (setq string (concat s string s))
5405 (if beg (delete-region beg end))
5406 (unless (or (bolp)
5407 (string-match (concat "[" (nth 0 erc) "\n]")
5408 (char-to-string (char-before (point)))))
5409 (insert " "))
5410 (unless (or (eobp)
5411 (string-match (concat "[" (nth 1 erc) "\n]")
5412 (char-to-string (char-after (point)))))
5413 (insert " ") (backward-char 1))
5414 (insert string)
5415 (and move (backward-char 1))))
5417 (defconst org-nonsticky-props
5418 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5420 (defsubst org-rear-nonsticky-at (pos)
5421 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5423 (defun org-activate-plain-links (limit)
5424 "Run through the buffer and add overlays to links."
5425 (catch 'exit
5426 (let (f)
5427 (if (re-search-forward org-plain-link-re limit t)
5428 (progn
5429 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5430 (setq f (get-text-property (match-beginning 0) 'face))
5431 (if (or (eq f 'org-tag)
5432 (and (listp f) (memq 'org-tag f)))
5434 (add-text-properties (match-beginning 0) (match-end 0)
5435 (list 'mouse-face 'highlight
5436 'face 'org-link
5437 'keymap org-mouse-map))
5438 (org-rear-nonsticky-at (match-end 0)))
5439 t)))))
5441 (defun org-activate-code (limit)
5442 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5443 (progn
5444 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5445 (remove-text-properties (match-beginning 0) (match-end 0)
5446 '(display t invisible t intangible t))
5447 t)))
5449 (defcustom org-src-fontify-natively nil
5450 "When non-nil, fontify code in code blocks."
5451 :type 'boolean
5452 :version "24.1"
5453 :group 'org-appearance
5454 :group 'org-babel)
5456 (defcustom org-src-prevent-auto-filling nil
5457 "When non-nil, prevent auto-filling in src blocks."
5458 :type 'boolean
5459 :version "24.1"
5460 :group 'org-appearance
5461 :group 'org-babel)
5463 (defcustom org-allow-promoting-top-level-subtree nil
5464 "When non-nil, allow promoting a top level subtree.
5465 The leading star of the top level headline will be replaced
5466 by a #."
5467 :type 'boolean
5468 :version "24.1"
5469 :group 'org-appearance)
5471 (defun org-fontify-meta-lines-and-blocks (limit)
5472 (condition-case nil
5473 (org-fontify-meta-lines-and-blocks-1 limit)
5474 (error (message "org-mode fontification error"))))
5476 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5477 "Fontify #+ lines and blocks, in the correct ways."
5478 (let ((case-fold-search t))
5479 (if (re-search-forward
5480 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5481 limit t)
5482 (let ((beg (match-beginning 0))
5483 (block-start (match-end 0))
5484 (block-end nil)
5485 (lang (match-string 7))
5486 (beg1 (line-beginning-position 2))
5487 (dc1 (downcase (match-string 2)))
5488 (dc3 (downcase (match-string 3)))
5489 end end1 quoting block-type ovl)
5490 (cond
5491 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5492 ;; a single line of backend-specific content
5493 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5494 (remove-text-properties (match-beginning 0) (match-end 0)
5495 '(display t invisible t intangible t))
5496 (add-text-properties (match-beginning 1) (match-end 3)
5497 '(font-lock-fontified t face org-meta-line))
5498 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5499 '(font-lock-fontified t face org-block))
5500 ; for backend-specific code
5502 ((and (match-end 4) (equal dc3 "+begin"))
5503 ;; Truly a block
5504 (setq block-type (downcase (match-string 5))
5505 quoting (member block-type org-protecting-blocks))
5506 (when (re-search-forward
5507 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5508 nil t) ;; on purpose, we look further than LIMIT
5509 (setq end (min (point-max) (match-end 0))
5510 end1 (min (point-max) (1- (match-beginning 0))))
5511 (setq block-end (match-beginning 0))
5512 (when quoting
5513 (remove-text-properties beg end
5514 '(display t invisible t intangible t)))
5515 (add-text-properties
5516 beg end
5517 '(font-lock-fontified t font-lock-multiline t))
5518 (add-text-properties beg beg1 '(face org-meta-line))
5519 (add-text-properties end1 (min (point-max) (1+ end))
5520 '(face org-meta-line)) ; for end_src
5521 (cond
5522 ((and lang (not (string= lang "")) org-src-fontify-natively)
5523 (org-src-font-lock-fontify-block lang block-start block-end)
5524 ;; remove old background overlays
5525 (mapc (lambda (ov)
5526 (if (eq (overlay-get ov 'face) 'org-block-background)
5527 (delete-overlay ov)))
5528 (overlays-at (/ (+ beg1 block-end) 2)))
5529 ;; add a background overlay
5530 (setq ovl (make-overlay beg1 block-end))
5531 (overlay-put ovl 'face 'org-block-background)
5532 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5533 (quoting
5534 (add-text-properties beg1 (min (point-max) (1+ end1))
5535 '(face org-block))) ; end of source block
5536 ((not org-fontify-quote-and-verse-blocks))
5537 ((string= block-type "quote")
5538 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5539 ((string= block-type "verse")
5540 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5541 (add-text-properties beg beg1 '(face org-block-begin-line))
5542 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5543 '(face org-block-end-line))
5545 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5546 (add-text-properties
5547 beg (match-end 3)
5548 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5549 '(font-lock-fontified t invisible t)
5550 '(font-lock-fontified t face org-document-info-keyword)))
5551 (add-text-properties
5552 (match-beginning 6) (match-end 6)
5553 (if (string-equal dc1 "+title:")
5554 '(font-lock-fontified t face org-document-title)
5555 '(font-lock-fontified t face org-document-info))))
5556 ((or (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5557 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5558 "+call:" "+header:" "+headers:" "+name:"))
5559 (and (match-end 4) (equal dc3 "+attr")))
5560 (add-text-properties
5561 beg (match-end 0)
5562 '(font-lock-fontified t face org-meta-line))
5564 ((member dc3 '(" " ""))
5565 (add-text-properties
5566 beg (match-end 0)
5567 '(font-lock-fontified t face font-lock-comment-face)))
5568 ((not (member (char-after beg) '(?\ ?\t)))
5569 ;; just any other in-buffer setting, but not indented
5570 (add-text-properties
5571 beg (match-end 0)
5572 '(font-lock-fontified t face org-meta-line))
5574 (t nil))))))
5576 (defun org-strip-protective-commas (beg end)
5577 "Strip protective commas between BEG and END in the current buffer."
5578 (interactive "r")
5579 (save-excursion
5580 (save-match-data
5581 (goto-char beg)
5582 (let ((front-line (save-excursion
5583 (re-search-forward
5584 "[^[:space:]]" end t)
5585 (goto-char (match-beginning 0))
5586 (current-column))))
5587 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t)
5588 (goto-char (match-beginning 1))
5589 (when (= (current-column) front-line)
5590 (replace-match "" nil nil nil 1)))))))
5592 (defun org-activate-angle-links (limit)
5593 "Run through the buffer and add overlays to links."
5594 (if (re-search-forward org-angle-link-re limit t)
5595 (progn
5596 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5597 (add-text-properties (match-beginning 0) (match-end 0)
5598 (list 'mouse-face 'highlight
5599 'keymap org-mouse-map))
5600 (org-rear-nonsticky-at (match-end 0))
5601 t)))
5603 (defun org-activate-footnote-links (limit)
5604 "Run through the buffer and add overlays to footnotes."
5605 (let ((fn (org-footnote-next-reference-or-definition limit)))
5606 (when fn
5607 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5608 (org-remove-flyspell-overlays-in beg end)
5609 (add-text-properties beg end
5610 (list 'mouse-face 'highlight
5611 'keymap org-mouse-map
5612 'help-echo
5613 (if (= (point-at-bol) beg)
5614 "Footnote definition"
5615 "Footnote reference")
5616 'font-lock-fontified t
5617 'font-lock-multiline t
5618 'face 'org-footnote))))))
5620 (defun org-activate-bracket-links (limit)
5621 "Run through the buffer and add overlays to bracketed links."
5622 (if (re-search-forward org-bracket-link-regexp limit t)
5623 (let* ((help (concat "LINK: "
5624 (org-match-string-no-properties 1)))
5625 ;; FIXME: above we should remove the escapes.
5626 ;; but that requires another match, protecting match data,
5627 ;; a lot of overhead for font-lock.
5628 (ip (org-maybe-intangible
5629 (list 'invisible 'org-link
5630 'keymap org-mouse-map 'mouse-face 'highlight
5631 'font-lock-multiline t 'help-echo help)))
5632 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5633 'font-lock-multiline t 'help-echo help)))
5634 ;; We need to remove the invisible property here. Table narrowing
5635 ;; may have made some of this invisible.
5636 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5637 (remove-text-properties (match-beginning 0) (match-end 0)
5638 '(invisible nil))
5639 (if (match-end 3)
5640 (progn
5641 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5642 (org-rear-nonsticky-at (match-beginning 3))
5643 (add-text-properties (match-beginning 3) (match-end 3) vp)
5644 (org-rear-nonsticky-at (match-end 3))
5645 (add-text-properties (match-end 3) (match-end 0) ip)
5646 (org-rear-nonsticky-at (match-end 0)))
5647 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5648 (org-rear-nonsticky-at (match-beginning 1))
5649 (add-text-properties (match-beginning 1) (match-end 1) vp)
5650 (org-rear-nonsticky-at (match-end 1))
5651 (add-text-properties (match-end 1) (match-end 0) ip)
5652 (org-rear-nonsticky-at (match-end 0)))
5653 t)))
5655 (defun org-activate-dates (limit)
5656 "Run through the buffer and add overlays to dates."
5657 (if (re-search-forward org-tsr-regexp-both limit t)
5658 (progn
5659 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5660 (add-text-properties (match-beginning 0) (match-end 0)
5661 (list 'mouse-face 'highlight
5662 'keymap org-mouse-map))
5663 (org-rear-nonsticky-at (match-end 0))
5664 (when org-display-custom-times
5665 (if (match-end 3)
5666 (org-display-custom-time (match-beginning 3) (match-end 3)))
5667 (org-display-custom-time (match-beginning 1) (match-end 1)))
5668 t)))
5670 (defvar org-target-link-regexp nil
5671 "Regular expression matching radio targets in plain text.")
5672 (make-variable-buffer-local 'org-target-link-regexp)
5673 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5674 "Regular expression matching a link target.")
5675 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5676 "Regular expression matching a radio target.")
5677 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5678 "Regular expression matching any target.")
5680 (defun org-activate-target-links (limit)
5681 "Run through the buffer and add overlays to target matches."
5682 (when org-target-link-regexp
5683 (let ((case-fold-search t))
5684 (if (re-search-forward org-target-link-regexp limit t)
5685 (progn
5686 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5687 (add-text-properties (match-beginning 0) (match-end 0)
5688 (list 'mouse-face 'highlight
5689 'keymap org-mouse-map
5690 'help-echo "Radio target link"
5691 'org-linked-text t))
5692 (org-rear-nonsticky-at (match-end 0))
5693 t)))))
5695 (defun org-update-radio-target-regexp ()
5696 "Find all radio targets in this file and update the regular expression."
5697 (interactive)
5698 (when (memq 'radio org-activate-links)
5699 (setq org-target-link-regexp
5700 (org-make-target-link-regexp (org-all-targets 'radio)))
5701 (org-restart-font-lock)))
5703 (defun org-hide-wide-columns (limit)
5704 (let (s e)
5705 (setq s (text-property-any (point) (or limit (point-max))
5706 'org-cwidth t))
5707 (when s
5708 (setq e (next-single-property-change s 'org-cwidth))
5709 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5710 (goto-char e)
5711 t)))
5713 (defvar org-latex-and-specials-regexp nil
5714 "Regular expression for highlighting export special stuff.")
5715 (defvar org-match-substring-regexp)
5716 (defvar org-match-substring-with-braces-regexp)
5718 ;; This should be with the exporter code, but we also use if for font-locking
5719 (defconst org-export-html-special-string-regexps
5720 '(("\\\\-" . "&shy;")
5721 ("---\\([^-]\\)" . "&mdash;\\1")
5722 ("--\\([^-]\\)" . "&ndash;\\1")
5723 ("\\.\\.\\." . "&hellip;"))
5724 "Regular expressions for special string conversion.")
5727 (defun org-compute-latex-and-specials-regexp ()
5728 "Compute regular expression for stuff treated specially by exporters."
5729 (if (not org-highlight-latex-fragments-and-specials)
5730 (org-set-local 'org-latex-and-specials-regexp nil)
5731 (require 'org-exp)
5732 (let*
5733 ((matchers (plist-get org-format-latex-options :matchers))
5734 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5735 org-latex-regexps)))
5736 (org-export-allow-BIND nil)
5737 (options (org-combine-plists (org-default-export-plist)
5738 (org-infile-export-plist)))
5739 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5740 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5741 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5742 (org-export-html-expand (plist-get options :expand-quoted-html))
5743 (org-export-with-special-strings (plist-get options :special-strings))
5744 (re-sub
5745 (cond
5746 ((equal org-export-with-sub-superscripts '{})
5747 (list org-match-substring-with-braces-regexp))
5748 (org-export-with-sub-superscripts
5749 (list org-match-substring-regexp))
5750 (t nil)))
5751 (re-latex
5752 (if org-export-with-LaTeX-fragments
5753 (mapcar (lambda (x) (nth 1 x)) latexs)))
5754 (re-macros
5755 (if org-export-with-TeX-macros
5756 (list (concat "\\\\"
5757 (regexp-opt
5758 (append
5760 (delq nil
5761 (mapcar 'car-safe
5762 (append org-entities-user
5763 org-entities)))
5764 (if (boundp 'org-latex-entities)
5765 (mapcar (lambda (x)
5766 (or (car-safe x) x))
5767 org-latex-entities)
5768 nil))
5769 'words))) ; FIXME
5771 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5772 (re-special (if org-export-with-special-strings
5773 (mapcar (lambda (x) (car x))
5774 org-export-html-special-string-regexps)))
5775 (re-rest
5776 (delq nil
5777 (list
5778 (if org-export-html-expand "@<[^>\n]+>")
5779 ))))
5780 (org-set-local
5781 'org-latex-and-specials-regexp
5782 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5783 re-rest) "\\|")))))
5785 (defun org-do-latex-and-special-faces (limit)
5786 "Run through the buffer and add overlays to links."
5787 (when org-latex-and-specials-regexp
5788 (let (rtn d)
5789 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5790 limit t))
5791 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5792 'face))
5793 '(org-code org-verbatim underline)))
5794 (progn
5795 (setq rtn t
5796 d (cond ((member (char-after (1+ (match-beginning 0)))
5797 '(?_ ?^)) 1)
5798 (t 0)))
5799 (font-lock-prepend-text-property
5800 (+ d (match-beginning 0)) (match-end 0)
5801 'face 'org-latex-and-export-specials)
5802 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5803 '(font-lock-multiline t)))))
5804 rtn)))
5806 (defun org-restart-font-lock ()
5807 "Restart `font-lock-mode', to force refontification."
5808 (when (and (boundp 'font-lock-mode) font-lock-mode)
5809 (font-lock-mode -1)
5810 (font-lock-mode 1)))
5812 (defun org-all-targets (&optional radio)
5813 "Return a list of all targets in this file.
5814 With optional argument RADIO, only find radio targets."
5815 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5816 rtn)
5817 (save-excursion
5818 (goto-char (point-min))
5819 (while (re-search-forward re nil t)
5820 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5821 rtn)))
5823 (defun org-make-target-link-regexp (targets)
5824 "Make regular expression matching all strings in TARGETS.
5825 The regular expression finds the targets also if there is a line break
5826 between words."
5827 (and targets
5828 (concat
5829 "\\<\\("
5830 (mapconcat
5831 (lambda (x)
5832 (setq x (regexp-quote x))
5833 (while (string-match " +" x)
5834 (setq x (replace-match "\\s-+" t t x)))
5836 targets
5837 "\\|")
5838 "\\)\\>")))
5840 (defun org-activate-tags (limit)
5841 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5842 (progn
5843 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5844 (add-text-properties (match-beginning 1) (match-end 1)
5845 (list 'mouse-face 'highlight
5846 'keymap org-mouse-map))
5847 (org-rear-nonsticky-at (match-end 1))
5848 t)))
5850 (defun org-outline-level ()
5851 "Compute the outline level of the heading at point.
5852 This function assumes that the cursor is at the beginning of a line matched
5853 by `outline-regexp'. Otherwise it returns garbage.
5854 If this is called at a normal headline, the level is the number of stars.
5855 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5856 (save-excursion
5857 (looking-at org-outline-regexp)
5858 (1- (- (match-end 0) (match-beginning 0)))))
5860 (defvar org-font-lock-keywords nil)
5862 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5863 "Regular expression matching a property line.")
5865 (defvar org-font-lock-hook nil
5866 "Functions to be called for special font lock stuff.")
5868 (defvar org-font-lock-set-keywords-hook nil
5869 "Functions that can manipulate `org-font-lock-extra-keywords'.
5870 This is called after `org-font-lock-extra-keywords' is defined, but before
5871 it is installed to be used by font lock. This can be useful if something
5872 needs to be inserted at a specific position in the font-lock sequence.")
5874 (defun org-font-lock-hook (limit)
5875 (run-hook-with-args 'org-font-lock-hook limit))
5877 (defun org-set-font-lock-defaults ()
5878 (let* ((em org-fontify-emphasized-text)
5879 (lk org-activate-links)
5880 (org-font-lock-extra-keywords
5881 (list
5882 ;; Call the hook
5883 '(org-font-lock-hook)
5884 ;; Headlines
5885 `(,(if org-fontify-whole-heading-line
5886 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5887 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5888 (1 (org-get-level-face 1))
5889 (2 (org-get-level-face 2))
5890 (3 (org-get-level-face 3)))
5891 ;; Table lines
5892 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5893 (1 'org-table t))
5894 ;; Table internals
5895 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5896 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5897 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5898 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5899 ;; Drawers
5900 (list org-drawer-regexp '(0 'org-special-keyword t))
5901 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5902 ;; Properties
5903 (list org-property-re
5904 '(1 'org-special-keyword t)
5905 '(3 'org-property-value t))
5906 ;; Links
5907 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5908 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5909 (if (memq 'plain lk) '(org-activate-plain-links))
5910 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5911 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5912 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5913 (if (memq 'footnote lk) '(org-activate-footnote-links))
5914 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5915 '(org-hide-wide-columns (0 nil append))
5916 ;; TODO keyword
5917 (list (format org-heading-keyword-regexp-format
5918 org-todo-regexp)
5919 '(2 (org-get-todo-face 2) t))
5920 ;; DONE
5921 (if org-fontify-done-headline
5922 (list (format org-heading-keyword-regexp-format
5923 (concat
5924 "\\(?:"
5925 (mapconcat 'regexp-quote org-done-keywords "\\|")
5926 "\\)"))
5927 '(2 'org-headline-done t))
5928 nil)
5929 ;; Priorities
5930 '(org-font-lock-add-priority-faces)
5931 ;; Tags
5932 '(org-font-lock-add-tag-faces)
5933 ;; Special keywords
5934 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5935 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5936 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5937 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5938 ;; Emphasis
5939 (if em
5940 (if (featurep 'xemacs)
5941 '(org-do-emphasis-faces (0 nil append))
5942 '(org-do-emphasis-faces)))
5943 ;; Checkboxes
5944 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5945 1 'org-checkbox prepend)
5946 (if (cdr (assq 'checkbox org-list-automatic-rules))
5947 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5948 (0 (org-get-checkbox-statistics-face) t)))
5949 ;; Description list items
5950 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5951 1 'org-list-dt prepend)
5952 ;; ARCHIVEd headings
5953 (list (concat
5954 org-outline-regexp-bol
5955 "\\(.*:" org-archive-tag ":.*\\)")
5956 '(1 'org-archived prepend))
5957 ;; Specials
5958 '(org-do-latex-and-special-faces)
5959 '(org-fontify-entities)
5960 '(org-raise-scripts)
5961 ;; Code
5962 '(org-activate-code (1 'org-code t))
5963 ;; COMMENT
5964 (list (format org-heading-keyword-regexp-format
5965 (concat "\\("
5966 org-comment-string "\\|" org-quote-string
5967 "\\)"))
5968 '(2 'org-special-keyword t))
5969 '("^[ \t]*#.*" (0 'font-lock-comment-face t))
5970 ;; Blocks and meta lines
5971 '(org-fontify-meta-lines-and-blocks)
5973 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5974 (run-hooks 'org-font-lock-set-keywords-hook)
5975 ;; Now set the full font-lock-keywords
5976 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5977 (org-set-local 'font-lock-defaults
5978 '(org-font-lock-keywords t nil nil backward-paragraph))
5979 (kill-local-variable 'font-lock-keywords) nil))
5981 (defun org-toggle-pretty-entities ()
5982 "Toggle the composition display of entities as UTF8 characters."
5983 (interactive)
5984 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5985 (org-restart-font-lock)
5986 (if org-pretty-entities
5987 (message "Entities are displayed as UTF8 characters")
5988 (save-restriction
5989 (widen)
5990 (org-decompose-region (point-min) (point-max))
5991 (message "Entities are displayed plain"))))
5993 (defun org-fontify-entities (limit)
5994 "Find an entity to fontify."
5995 (let (ee)
5996 (when org-pretty-entities
5997 (catch 'match
5998 (while (re-search-forward
5999 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6000 limit t)
6001 (if (and (not (org-in-indented-comment-line))
6002 (setq ee (org-entity-get (match-string 1)))
6003 (= (length (nth 6 ee)) 1))
6004 (let*
6005 ((end (if (equal (match-string 2) "{}")
6006 (match-end 2)
6007 (match-end 1))))
6008 (add-text-properties
6009 (match-beginning 0) end
6010 (list 'font-lock-fontified t))
6011 (compose-region (match-beginning 0) end
6012 (nth 6 ee) nil)
6013 (backward-char 1)
6014 (throw 'match t))))
6015 nil))))
6017 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6018 "Fontify string S like in Org-mode."
6019 (with-temp-buffer
6020 (insert s)
6021 (let ((org-odd-levels-only odd-levels))
6022 (org-mode)
6023 (font-lock-fontify-buffer)
6024 (buffer-string))))
6026 (defvar org-m nil)
6027 (defvar org-l nil)
6028 (defvar org-f nil)
6029 (defun org-get-level-face (n)
6030 "Get the right face for match N in font-lock matching of headlines."
6031 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6032 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6033 (if org-cycle-level-faces
6034 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6035 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6036 (cond
6037 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6038 ((eq n 2) org-f)
6039 (t (if org-level-color-stars-only nil org-f))))
6042 (defun org-get-todo-face (kwd)
6043 "Get the right face for a TODO keyword KWD.
6044 If KWD is a number, get the corresponding match group."
6045 (if (numberp kwd) (setq kwd (match-string kwd)))
6046 (or (org-face-from-face-or-color
6047 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6048 (and (member kwd org-done-keywords) 'org-done)
6049 'org-todo))
6051 (defun org-face-from-face-or-color (context inherit face-or-color)
6052 "Create a face list that inherits INHERIT, but sets the foreground color.
6053 When FACE-OR-COLOR is not a string, just return it."
6054 (if (stringp face-or-color)
6055 (list :inherit inherit
6056 (cdr (assoc context org-faces-easy-properties))
6057 face-or-color)
6058 face-or-color))
6060 (defun org-font-lock-add-tag-faces (limit)
6061 "Add the special tag faces."
6062 (when (and org-tag-faces org-tags-special-faces-re)
6063 (while (re-search-forward org-tags-special-faces-re limit t)
6064 (add-text-properties (match-beginning 1) (match-end 1)
6065 (list 'face (org-get-tag-face 1)
6066 'font-lock-fontified t))
6067 (backward-char 1))))
6069 (defun org-font-lock-add-priority-faces (limit)
6070 "Add the special priority faces."
6071 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6072 (when (save-match-data (org-at-heading-p))
6073 (add-text-properties
6074 (match-beginning 0) (match-end 0)
6075 (list 'face (or (org-face-from-face-or-color
6076 'priority 'org-special-keyword
6077 (cdr (assoc (char-after (match-beginning 1))
6078 org-priority-faces)))
6079 'org-special-keyword)
6080 'font-lock-fontified t)))))
6082 (defun org-get-tag-face (kwd)
6083 "Get the right face for a TODO keyword KWD.
6084 If KWD is a number, get the corresponding match group."
6085 (if (numberp kwd) (setq kwd (match-string kwd)))
6086 (or (org-face-from-face-or-color
6087 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6088 'org-tag))
6090 (defun org-unfontify-region (beg end &optional maybe_loudly)
6091 "Remove fontification and activation overlays from links."
6092 (font-lock-default-unfontify-region beg end)
6093 (let* ((buffer-undo-list t)
6094 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6095 (inhibit-modification-hooks t)
6096 deactivate-mark buffer-file-name buffer-file-truename)
6097 (org-decompose-region beg end)
6098 (remove-text-properties beg end
6099 '(mouse-face t keymap t org-linked-text t
6100 invisible t intangible t
6101 org-no-flyspell t org-emphasis t))
6102 (org-remove-font-lock-display-properties beg end)))
6104 (defconst org-script-display '(((raise -0.3) (height 0.7))
6105 ((raise 0.3) (height 0.7))
6106 ((raise -0.5))
6107 ((raise 0.5)))
6108 "Display properties for showing superscripts and subscripts.")
6110 (defun org-remove-font-lock-display-properties (beg end)
6111 "Remove specific display properties that have been added by font lock.
6112 The will remove the raise properties that are used to show superscripts
6113 and subscripts."
6114 (let (next prop)
6115 (while (< beg end)
6116 (setq next (next-single-property-change beg 'display nil end)
6117 prop (get-text-property beg 'display))
6118 (if (member prop org-script-display)
6119 (put-text-property beg next 'display nil))
6120 (setq beg next))))
6122 (defun org-raise-scripts (limit)
6123 "Add raise properties to sub/superscripts."
6124 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6125 (if (re-search-forward
6126 (if (eq org-use-sub-superscripts t)
6127 org-match-substring-regexp
6128 org-match-substring-with-braces-regexp)
6129 limit t)
6130 (let* ((pos (point)) table-p comment-p
6131 (mpos (match-beginning 3))
6132 (emph-p (get-text-property mpos 'org-emphasis))
6133 (link-p (get-text-property mpos 'mouse-face))
6134 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6135 (goto-char (point-at-bol))
6136 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6137 comment-p (org-looking-at-p "[ \t]*#"))
6138 (goto-char pos)
6139 ;; FIXME: Should we go back one character here, for a_b^c
6140 ;; (goto-char (1- pos)) ;????????????????????
6141 (if (or comment-p emph-p link-p keyw-p)
6143 (put-text-property (match-beginning 3) (match-end 0)
6144 'display
6145 (if (equal (char-after (match-beginning 2)) ?^)
6146 (nth (if table-p 3 1) org-script-display)
6147 (nth (if table-p 2 0) org-script-display)))
6148 (add-text-properties (match-beginning 2) (match-end 2)
6149 (list 'invisible t
6150 'org-dwidth t 'org-dwidth-n 1))
6151 (if (and (eq (char-after (match-beginning 3)) ?{)
6152 (eq (char-before (match-end 3)) ?}))
6153 (progn
6154 (add-text-properties
6155 (match-beginning 3) (1+ (match-beginning 3))
6156 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6157 (add-text-properties
6158 (1- (match-end 3)) (match-end 3)
6159 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6160 t)))))
6162 ;;;; Visibility cycling, including org-goto and indirect buffer
6164 ;;; Cycling
6166 (defvar org-cycle-global-status nil)
6167 (make-variable-buffer-local 'org-cycle-global-status)
6168 (defvar org-cycle-subtree-status nil)
6169 (make-variable-buffer-local 'org-cycle-subtree-status)
6171 ;;;###autoload
6173 (defvar org-inlinetask-min-level)
6175 (defun org-cycle (&optional arg)
6176 "TAB-action and visibility cycling for Org-mode.
6178 This is the command invoked in Org-mode by the TAB key. Its main purpose
6179 is outline visibility cycling, but it also invokes other actions
6180 in special contexts.
6182 - When this function is called with a prefix argument, rotate the entire
6183 buffer through 3 states (global cycling)
6184 1. OVERVIEW: Show only top-level headlines.
6185 2. CONTENTS: Show all headlines of all levels, but no body text.
6186 3. SHOW ALL: Show everything.
6187 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6188 determined by the variable `org-startup-folded', and by any VISIBILITY
6189 properties in the buffer.
6190 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6191 including any drawers.
6193 - When inside a table, re-align the table and move to the next field.
6195 - When point is at the beginning of a headline, rotate the subtree started
6196 by this line through 3 different states (local cycling)
6197 1. FOLDED: Only the main headline is shown.
6198 2. CHILDREN: The main headline and the direct children are shown.
6199 From this state, you can move to one of the children
6200 and zoom in further.
6201 3. SUBTREE: Show the entire subtree, including body text.
6202 If there is no subtree, switch directly from CHILDREN to FOLDED.
6204 - When point is at the beginning of an empty headline and the variable
6205 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6206 of the headline by demoting and promoting it to likely levels. This
6207 speeds up creation document structure by pressing TAB once or several
6208 times right after creating a new headline.
6210 - When there is a numeric prefix, go up to a heading with level ARG, do
6211 a `show-subtree' and return to the previous cursor position. If ARG
6212 is negative, go up that many levels.
6214 - When point is not at the beginning of a headline, execute the global
6215 binding for TAB, which is re-indenting the line. See the option
6216 `org-cycle-emulate-tab' for details.
6218 - Special case: if point is at the beginning of the buffer and there is
6219 no headline in line 1, this function will act as if called with prefix arg
6220 (C-u TAB, same as S-TAB) also when called without prefix arg.
6221 But only if also the variable `org-cycle-global-at-bob' is t."
6222 (interactive "P")
6223 (org-load-modules-maybe)
6224 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6225 (and org-cycle-level-after-item/entry-creation
6226 (or (org-cycle-level)
6227 (org-cycle-item-indentation))))
6228 (let* ((limit-level
6229 (or org-cycle-max-level
6230 (and (boundp 'org-inlinetask-min-level)
6231 org-inlinetask-min-level
6232 (1- org-inlinetask-min-level))))
6233 (nstars (and limit-level
6234 (if org-odd-levels-only
6235 (and limit-level (1- (* limit-level 2)))
6236 limit-level)))
6237 (org-outline-regexp
6238 (if (not (derived-mode-p 'org-mode))
6239 outline-regexp
6240 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6241 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6242 (not (looking-at org-outline-regexp))))
6243 (org-cycle-hook
6244 (if bob-special
6245 (delq 'org-optimize-window-after-visibility-change
6246 (copy-sequence org-cycle-hook))
6247 org-cycle-hook))
6248 (pos (point)))
6250 (if (or bob-special (equal arg '(4)))
6251 ;; special case: use global cycling
6252 (setq arg t))
6254 (cond
6256 ((equal arg '(16))
6257 (setq last-command 'dummy)
6258 (org-set-startup-visibility)
6259 (message "Startup visibility, plus VISIBILITY properties"))
6261 ((equal arg '(64))
6262 (show-all)
6263 (message "Entire buffer visible, including drawers"))
6265 ;; Table: enter it or move to the next field.
6266 ((org-at-table-p 'any)
6267 (if (org-at-table.el-p)
6268 (message "Use C-c ' to edit table.el tables")
6269 (if arg (org-table-edit-field t)
6270 (org-table-justify-field-maybe)
6271 (call-interactively 'org-table-next-field))))
6273 ((run-hook-with-args-until-success
6274 'org-tab-after-check-for-table-hook))
6276 ;; Global cycling: delegate to `org-cycle-internal-global'.
6277 ((eq arg t) (org-cycle-internal-global))
6279 ;; Drawers: delegate to `org-flag-drawer'.
6280 ((and org-drawers org-drawer-regexp
6281 (save-excursion
6282 (beginning-of-line 1)
6283 (looking-at org-drawer-regexp)))
6284 (org-flag-drawer ; toggle block visibility
6285 (not (get-char-property (match-end 0) 'invisible))))
6287 ;; Show-subtree, ARG levels up from here.
6288 ((integerp arg)
6289 (save-excursion
6290 (org-back-to-heading)
6291 (outline-up-heading (if (< arg 0) (- arg)
6292 (- (funcall outline-level) arg)))
6293 (org-show-subtree)))
6295 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6296 ((and (featurep 'org-inlinetask)
6297 (org-inlinetask-at-task-p)
6298 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6299 (org-inlinetask-toggle-visibility))
6301 ((org-try-cdlatex-tab))
6303 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6304 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6305 (save-excursion (beginning-of-line 1)
6306 (looking-at org-outline-regexp)))
6307 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6308 (org-cycle-internal-local))
6310 ;; From there: TAB emulation and template completion.
6311 (buffer-read-only (org-back-to-heading))
6313 ((run-hook-with-args-until-success
6314 'org-tab-after-check-for-cycling-hook))
6316 ((org-try-structure-completion))
6318 ((run-hook-with-args-until-success
6319 'org-tab-before-tab-emulation-hook))
6321 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6322 (or (not (bolp))
6323 (not (looking-at org-outline-regexp))))
6324 (call-interactively (global-key-binding "\t")))
6326 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6327 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6328 (or (and (eq org-cycle-emulate-tab 'white)
6329 (= (match-end 0) (point-at-eol)))
6330 (and (eq org-cycle-emulate-tab 'whitestart)
6331 (>= (match-end 0) pos))))
6333 (eq org-cycle-emulate-tab t))
6334 (call-interactively (global-key-binding "\t")))
6336 (t (save-excursion
6337 (org-back-to-heading)
6338 (org-cycle)))))))
6340 (defun org-cycle-internal-global ()
6341 "Do the global cycling action."
6342 ;; Hack to avoid display of messages for .org attachments in Gnus
6343 (let ((ga (string-match "\\*fontification" (buffer-name))))
6344 (cond
6345 ((and (eq last-command this-command)
6346 (eq org-cycle-global-status 'overview))
6347 ;; We just created the overview - now do table of contents
6348 ;; This can be slow in very large buffers, so indicate action
6349 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6350 (unless ga (message "CONTENTS..."))
6351 (org-content)
6352 (unless ga (message "CONTENTS...done"))
6353 (setq org-cycle-global-status 'contents)
6354 (run-hook-with-args 'org-cycle-hook 'contents))
6356 ((and (eq last-command this-command)
6357 (eq org-cycle-global-status 'contents))
6358 ;; We just showed the table of contents - now show everything
6359 (run-hook-with-args 'org-pre-cycle-hook 'all)
6360 (show-all)
6361 (unless ga (message "SHOW ALL"))
6362 (setq org-cycle-global-status 'all)
6363 (run-hook-with-args 'org-cycle-hook 'all))
6366 ;; Default action: go to overview
6367 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6368 (org-overview)
6369 (unless ga (message "OVERVIEW"))
6370 (setq org-cycle-global-status 'overview)
6371 (run-hook-with-args 'org-cycle-hook 'overview)))))
6373 (defun org-cycle-internal-local ()
6374 "Do the local cycling action."
6375 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6376 ;; First, determine end of headline (EOH), end of subtree or item
6377 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6378 (save-excursion
6379 (if (org-at-item-p)
6380 (progn
6381 (beginning-of-line)
6382 (setq struct (org-list-struct))
6383 (setq eoh (point-at-eol))
6384 (setq eos (org-list-get-item-end-before-blank (point) struct))
6385 (setq has-children (org-list-has-child-p (point) struct)))
6386 (org-back-to-heading)
6387 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6388 (setq eos (save-excursion
6389 (org-end-of-subtree t)
6390 (unless (eobp)
6391 (skip-chars-forward " \t\n"))
6392 (if (eobp) (point) (1- (point)))))
6393 (setq has-children
6394 (or (save-excursion
6395 (let ((level (funcall outline-level)))
6396 (outline-next-heading)
6397 (and (org-at-heading-p t)
6398 (> (funcall outline-level) level))))
6399 (save-excursion
6400 (org-list-search-forward (org-item-beginning-re) eos t)))))
6401 ;; Determine end invisible part of buffer (EOL)
6402 (beginning-of-line 2)
6403 ;; XEmacs doesn't have `next-single-char-property-change'
6404 (if (featurep 'xemacs)
6405 (while (and (not (eobp)) ;; this is like `next-line'
6406 (get-char-property (1- (point)) 'invisible))
6407 (beginning-of-line 2))
6408 (while (and (not (eobp)) ;; this is like `next-line'
6409 (get-char-property (1- (point)) 'invisible))
6410 (goto-char (next-single-char-property-change (point) 'invisible))
6411 (and (eolp) (beginning-of-line 2))))
6412 (setq eol (point)))
6413 ;; Find out what to do next and set `this-command'
6414 (cond
6415 ((= eos eoh)
6416 ;; Nothing is hidden behind this heading
6417 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6418 (message "EMPTY ENTRY")
6419 (setq org-cycle-subtree-status nil)
6420 (save-excursion
6421 (goto-char eos)
6422 (outline-next-heading)
6423 (if (outline-invisible-p) (org-flag-heading nil))))
6424 ((and (or (>= eol eos)
6425 (not (string-match "\\S-" (buffer-substring eol eos))))
6426 (or has-children
6427 (not (setq children-skipped
6428 org-cycle-skip-children-state-if-no-children))))
6429 ;; Entire subtree is hidden in one line: children view
6430 (run-hook-with-args 'org-pre-cycle-hook 'children)
6431 (if (org-at-item-p)
6432 (org-list-set-item-visibility (point-at-bol) struct 'children)
6433 (org-show-entry)
6434 (org-with-limited-levels (show-children))
6435 ;; FIXME: This slows down the func way too much.
6436 ;; How keep drawers hidden in subtree anyway?
6437 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6438 ;; (org-cycle-hide-drawers 'subtree))
6440 ;; Fold every list in subtree to top-level items.
6441 (when (eq org-cycle-include-plain-lists 'integrate)
6442 (save-excursion
6443 (org-back-to-heading)
6444 (while (org-list-search-forward (org-item-beginning-re) eos t)
6445 (beginning-of-line 1)
6446 (let* ((struct (org-list-struct))
6447 (prevs (org-list-prevs-alist struct))
6448 (end (org-list-get-bottom-point struct)))
6449 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6450 (org-list-get-all-items (point) struct prevs))
6451 (goto-char end))))))
6452 (message "CHILDREN")
6453 (save-excursion
6454 (goto-char eos)
6455 (outline-next-heading)
6456 (if (outline-invisible-p) (org-flag-heading nil)))
6457 (setq org-cycle-subtree-status 'children)
6458 (run-hook-with-args 'org-cycle-hook 'children))
6459 ((or children-skipped
6460 (and (eq last-command this-command)
6461 (eq org-cycle-subtree-status 'children)))
6462 ;; We just showed the children, or no children are there,
6463 ;; now show everything.
6464 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6465 (outline-flag-region eoh eos nil)
6466 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6467 (setq org-cycle-subtree-status 'subtree)
6468 (run-hook-with-args 'org-cycle-hook 'subtree))
6470 ;; Default action: hide the subtree.
6471 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6472 (outline-flag-region eoh eos t)
6473 (message "FOLDED")
6474 (setq org-cycle-subtree-status 'folded)
6475 (run-hook-with-args 'org-cycle-hook 'folded)))))
6477 ;;;###autoload
6478 (defun org-global-cycle (&optional arg)
6479 "Cycle the global visibility. For details see `org-cycle'.
6480 With \\[universal-argument] prefix arg, switch to startup visibility.
6481 With a numeric prefix, show all headlines up to that level."
6482 (interactive "P")
6483 (let ((org-cycle-include-plain-lists
6484 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6485 (cond
6486 ((integerp arg)
6487 (show-all)
6488 (hide-sublevels arg)
6489 (setq org-cycle-global-status 'contents))
6490 ((equal arg '(4))
6491 (org-set-startup-visibility)
6492 (message "Startup visibility, plus VISIBILITY properties."))
6494 (org-cycle '(4))))))
6496 (defun org-set-startup-visibility ()
6497 "Set the visibility required by startup options and properties."
6498 (cond
6499 ((eq org-startup-folded t)
6500 (org-cycle '(4)))
6501 ((eq org-startup-folded 'content)
6502 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6503 (org-cycle '(4)) (org-cycle '(4)))))
6504 (unless (eq org-startup-folded 'showeverything)
6505 (if org-hide-block-startup (org-hide-block-all))
6506 (org-set-visibility-according-to-property 'no-cleanup)
6507 (org-cycle-hide-archived-subtrees 'all)
6508 (org-cycle-hide-drawers 'all)
6509 (org-cycle-show-empty-lines t)))
6511 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6512 "Switch subtree visibilities according to :VISIBILITY: property."
6513 (interactive)
6514 (let (org-show-entry-below state)
6515 (save-excursion
6516 (goto-char (point-min))
6517 (while (re-search-forward
6518 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6519 nil t)
6520 (setq state (match-string 1))
6521 (save-excursion
6522 (org-back-to-heading t)
6523 (hide-subtree)
6524 (org-reveal)
6525 (cond
6526 ((equal state '("fold" "folded"))
6527 (hide-subtree))
6528 ((equal state "children")
6529 (org-show-hidden-entry)
6530 (show-children))
6531 ((equal state "content")
6532 (save-excursion
6533 (save-restriction
6534 (org-narrow-to-subtree)
6535 (org-content))))
6536 ((member state '("all" "showall"))
6537 (show-subtree)))))
6538 (unless no-cleanup
6539 (org-cycle-hide-archived-subtrees 'all)
6540 (org-cycle-hide-drawers 'all)
6541 (org-cycle-show-empty-lines 'all)))))
6543 ;; This function uses outline-regexp instead of the more fundamental
6544 ;; org-outline-regexp so that org-cycle-global works outside of Org
6545 ;; buffers, where outline-regexp is needed.
6546 (defun org-overview ()
6547 "Switch to overview mode, showing only top-level headlines.
6548 Really, this shows all headlines with level equal or greater than the level
6549 of the first headline in the buffer. This is important, because if the
6550 first headline is not level one, then (hide-sublevels 1) gives confusing
6551 results."
6552 (interactive)
6553 (let ((level (save-excursion
6554 (goto-char (point-min))
6555 (if (re-search-forward (concat "^" outline-regexp) nil t)
6556 (progn
6557 (goto-char (match-beginning 0))
6558 (funcall outline-level))))))
6559 (and level (hide-sublevels level))))
6561 (defun org-content (&optional arg)
6562 "Show all headlines in the buffer, like a table of contents.
6563 With numerical argument N, show content up to level N."
6564 (interactive "P")
6565 (save-excursion
6566 ;; Visit all headings and show their offspring
6567 (and (integerp arg) (org-overview))
6568 (goto-char (point-max))
6569 (catch 'exit
6570 (while (and (progn (condition-case nil
6571 (outline-previous-visible-heading 1)
6572 (error (goto-char (point-min))))
6574 (looking-at org-outline-regexp))
6575 (if (integerp arg)
6576 (show-children (1- arg))
6577 (show-branches))
6578 (if (bobp) (throw 'exit nil))))))
6581 (defun org-optimize-window-after-visibility-change (state)
6582 "Adjust the window after a change in outline visibility.
6583 This function is the default value of the hook `org-cycle-hook'."
6584 (when (get-buffer-window (current-buffer))
6585 (cond
6586 ((eq state 'content) nil)
6587 ((eq state 'all) nil)
6588 ((eq state 'folded) nil)
6589 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6590 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6592 (defun org-remove-empty-overlays-at (pos)
6593 "Remove outline overlays that do not contain non-white stuff."
6594 (mapc
6595 (lambda (o)
6596 (and (eq 'outline (overlay-get o 'invisible))
6597 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6598 (overlay-end o))))
6599 (delete-overlay o)))
6600 (overlays-at pos)))
6602 (defun org-clean-visibility-after-subtree-move ()
6603 "Fix visibility issues after moving a subtree."
6604 ;; First, find a reasonable region to look at:
6605 ;; Start two siblings above, end three below
6606 (let* ((beg (save-excursion
6607 (and (org-get-last-sibling)
6608 (org-get-last-sibling))
6609 (point)))
6610 (end (save-excursion
6611 (and (org-get-next-sibling)
6612 (org-get-next-sibling)
6613 (org-get-next-sibling))
6614 (if (org-at-heading-p)
6615 (point-at-eol)
6616 (point))))
6617 (level (looking-at "\\*+"))
6618 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6619 (save-excursion
6620 (save-restriction
6621 (narrow-to-region beg end)
6622 (when re
6623 ;; Properly fold already folded siblings
6624 (goto-char (point-min))
6625 (while (re-search-forward re nil t)
6626 (if (and (not (outline-invisible-p))
6627 (save-excursion
6628 (goto-char (point-at-eol)) (outline-invisible-p)))
6629 (hide-entry))))
6630 (org-cycle-show-empty-lines 'overview)
6631 (org-cycle-hide-drawers 'overview)))))
6633 (defun org-cycle-show-empty-lines (state)
6634 "Show empty lines above all visible headlines.
6635 The region to be covered depends on STATE when called through
6636 `org-cycle-hook'. Lisp program can use t for STATE to get the
6637 entire buffer covered. Note that an empty line is only shown if there
6638 are at least `org-cycle-separator-lines' empty lines before the headline."
6639 (when (not (= org-cycle-separator-lines 0))
6640 (save-excursion
6641 (let* ((n (abs org-cycle-separator-lines))
6642 (re (cond
6643 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6644 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6645 (t (let ((ns (number-to-string (- n 2))))
6646 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6647 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6648 beg end b e)
6649 (cond
6650 ((memq state '(overview contents t))
6651 (setq beg (point-min) end (point-max)))
6652 ((memq state '(children folded))
6653 (setq beg (point) end (progn (org-end-of-subtree t t)
6654 (beginning-of-line 2)
6655 (point)))))
6656 (when beg
6657 (goto-char beg)
6658 (while (re-search-forward re end t)
6659 (unless (get-char-property (match-end 1) 'invisible)
6660 (setq e (match-end 1))
6661 (if (< org-cycle-separator-lines 0)
6662 (setq b (save-excursion
6663 (goto-char (match-beginning 0))
6664 (org-back-over-empty-lines)
6665 (if (save-excursion
6666 (goto-char (max (point-min) (1- (point))))
6667 (org-at-heading-p))
6668 (1- (point))
6669 (point))))
6670 (setq b (match-beginning 1)))
6671 (outline-flag-region b e nil)))))))
6672 ;; Never hide empty lines at the end of the file.
6673 (save-excursion
6674 (goto-char (point-max))
6675 (outline-previous-heading)
6676 (outline-end-of-heading)
6677 (if (and (looking-at "[ \t\n]+")
6678 (= (match-end 0) (point-max)))
6679 (outline-flag-region (point) (match-end 0) nil))))
6681 (defun org-show-empty-lines-in-parent ()
6682 "Move to the parent and re-show empty lines before visible headlines."
6683 (save-excursion
6684 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6685 (org-cycle-show-empty-lines context))))
6687 (defun org-files-list ()
6688 "Return `org-agenda-files' list, plus all open org-mode files.
6689 This is useful for operations that need to scan all of a user's
6690 open and agenda-wise Org files."
6691 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6692 (dolist (buf (buffer-list))
6693 (with-current-buffer buf
6694 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6695 (let ((file (expand-file-name (buffer-file-name))))
6696 (unless (member file files)
6697 (push file files))))))
6698 files))
6700 (defsubst org-entry-beginning-position ()
6701 "Return the beginning position of the current entry."
6702 (save-excursion (outline-back-to-heading t) (point)))
6704 (defsubst org-entry-end-position ()
6705 "Return the end position of the current entry."
6706 (save-excursion (outline-next-heading) (point)))
6708 (defun org-cycle-hide-drawers (state)
6709 "Re-hide all drawers after a visibility state change."
6710 (when (and (derived-mode-p 'org-mode)
6711 (not (memq state '(overview folded contents))))
6712 (save-excursion
6713 (let* ((globalp (memq state '(contents all)))
6714 (beg (if globalp (point-min) (point)))
6715 (end (if globalp (point-max)
6716 (if (eq state 'children)
6717 (save-excursion (outline-next-heading) (point))
6718 (org-end-of-subtree t)))))
6719 (goto-char beg)
6720 (while (re-search-forward org-drawer-regexp end t)
6721 (org-flag-drawer t))))))
6723 (defun org-flag-drawer (flag)
6724 "When FLAG is non-nil, hide the drawer we are within.
6725 Otherwise make it visible."
6726 (save-excursion
6727 (beginning-of-line 1)
6728 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6729 (let ((b (match-end 0)))
6730 (if (re-search-forward
6731 "^[ \t]*:END:"
6732 (save-excursion (outline-next-heading) (point)) t)
6733 (outline-flag-region b (point-at-eol) flag)
6734 (error ":END: line missing at position %s" b))))))
6736 (defun org-subtree-end-visible-p ()
6737 "Is the end of the current subtree visible?"
6738 (pos-visible-in-window-p
6739 (save-excursion (org-end-of-subtree t) (point))))
6741 (defun org-first-headline-recenter (&optional N)
6742 "Move cursor to the first headline and recenter the headline.
6743 Optional argument N means put the headline into the Nth line of the window."
6744 (goto-char (point-min))
6745 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6746 (beginning-of-line)
6747 (recenter (prefix-numeric-value N))))
6749 ;;; Saving and restoring visibility
6751 (defun org-outline-overlay-data (&optional use-markers)
6752 "Return a list of the locations of all outline overlays.
6753 These are overlays with the `invisible' property value `outline'.
6754 The return value is a list of cons cells, with start and stop
6755 positions for each overlay.
6756 If USE-MARKERS is set, return the positions as markers."
6757 (let (beg end)
6758 (save-excursion
6759 (save-restriction
6760 (widen)
6761 (delq nil
6762 (mapcar (lambda (o)
6763 (when (eq (overlay-get o 'invisible) 'outline)
6764 (setq beg (overlay-start o)
6765 end (overlay-end o))
6766 (and beg end (> end beg)
6767 (if use-markers
6768 (cons (move-marker (make-marker) beg)
6769 (move-marker (make-marker) end))
6770 (cons beg end)))))
6771 (overlays-in (point-min) (point-max))))))))
6773 (defun org-set-outline-overlay-data (data)
6774 "Create visibility overlays for all positions in DATA.
6775 DATA should have been made by `org-outline-overlay-data'."
6776 (let (o)
6777 (save-excursion
6778 (save-restriction
6779 (widen)
6780 (show-all)
6781 (mapc (lambda (c)
6782 (outline-flag-region (car c) (cdr c) t))
6783 data)))))
6785 ;;; Folding of blocks
6787 (defvar org-hide-block-overlays nil
6788 "Overlays hiding blocks.")
6789 (make-variable-buffer-local 'org-hide-block-overlays)
6791 (defun org-block-map (function &optional start end)
6792 "Call FUNCTION at the head of all source blocks in the current buffer.
6793 Optional arguments START and END can be used to limit the range."
6794 (let ((start (or start (point-min)))
6795 (end (or end (point-max))))
6796 (save-excursion
6797 (goto-char start)
6798 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6799 (save-excursion
6800 (save-match-data
6801 (goto-char (match-beginning 0))
6802 (funcall function)))))))
6804 (defun org-hide-block-toggle-all ()
6805 "Toggle the visibility of all blocks in the current buffer."
6806 (org-block-map #'org-hide-block-toggle))
6808 (defun org-hide-block-all ()
6809 "Fold all blocks in the current buffer."
6810 (interactive)
6811 (org-show-block-all)
6812 (org-block-map #'org-hide-block-toggle-maybe))
6814 (defun org-show-block-all ()
6815 "Unfold all blocks in the current buffer."
6816 (interactive)
6817 (mapc 'delete-overlay org-hide-block-overlays)
6818 (setq org-hide-block-overlays nil))
6820 (defun org-hide-block-toggle-maybe ()
6821 "Toggle visibility of block at point."
6822 (interactive)
6823 (let ((case-fold-search t))
6824 (if (save-excursion
6825 (beginning-of-line 1)
6826 (looking-at org-block-regexp))
6827 (progn (org-hide-block-toggle)
6828 t) ;; to signal that we took action
6829 nil))) ;; to signal that we did not
6831 (defun org-hide-block-toggle (&optional force)
6832 "Toggle the visibility of the current block."
6833 (interactive)
6834 (save-excursion
6835 (beginning-of-line)
6836 (if (re-search-forward org-block-regexp nil t)
6837 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6838 (end (match-end 0)) ;; end of entire body
6840 (if (memq t (mapcar (lambda (overlay)
6841 (eq (overlay-get overlay 'invisible)
6842 'org-hide-block))
6843 (overlays-at start)))
6844 (if (or (not force) (eq force 'off))
6845 (mapc (lambda (ov)
6846 (when (member ov org-hide-block-overlays)
6847 (setq org-hide-block-overlays
6848 (delq ov org-hide-block-overlays)))
6849 (when (eq (overlay-get ov 'invisible)
6850 'org-hide-block)
6851 (delete-overlay ov)))
6852 (overlays-at start)))
6853 (setq ov (make-overlay start end))
6854 (overlay-put ov 'invisible 'org-hide-block)
6855 ;; make the block accessible to isearch
6856 (overlay-put
6857 ov 'isearch-open-invisible
6858 (lambda (ov)
6859 (when (member ov org-hide-block-overlays)
6860 (setq org-hide-block-overlays
6861 (delq ov org-hide-block-overlays)))
6862 (when (eq (overlay-get ov 'invisible)
6863 'org-hide-block)
6864 (delete-overlay ov))))
6865 (push ov org-hide-block-overlays)))
6866 (error "Not looking at a source block"))))
6868 ;; org-tab-after-check-for-cycling-hook
6869 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6870 ;; Remove overlays when changing major mode
6871 (add-hook 'org-mode-hook
6872 (lambda () (org-add-hook 'change-major-mode-hook
6873 'org-show-block-all 'append 'local)))
6875 ;;; Org-goto
6877 (defvar org-goto-window-configuration nil)
6878 (defvar org-goto-marker nil)
6879 (defvar org-goto-map
6880 (let ((map (make-sparse-keymap)))
6881 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6882 (while (setq cmd (pop cmds))
6883 (substitute-key-definition cmd cmd map global-map)))
6884 (suppress-keymap map)
6885 (org-defkey map "\C-m" 'org-goto-ret)
6886 (org-defkey map [(return)] 'org-goto-ret)
6887 (org-defkey map [(left)] 'org-goto-left)
6888 (org-defkey map [(right)] 'org-goto-right)
6889 (org-defkey map [(control ?g)] 'org-goto-quit)
6890 (org-defkey map "\C-i" 'org-cycle)
6891 (org-defkey map [(tab)] 'org-cycle)
6892 (org-defkey map [(down)] 'outline-next-visible-heading)
6893 (org-defkey map [(up)] 'outline-previous-visible-heading)
6894 (if org-goto-auto-isearch
6895 (if (fboundp 'define-key-after)
6896 (define-key-after map [t] 'org-goto-local-auto-isearch)
6897 nil)
6898 (org-defkey map "q" 'org-goto-quit)
6899 (org-defkey map "n" 'outline-next-visible-heading)
6900 (org-defkey map "p" 'outline-previous-visible-heading)
6901 (org-defkey map "f" 'outline-forward-same-level)
6902 (org-defkey map "b" 'outline-backward-same-level)
6903 (org-defkey map "u" 'outline-up-heading))
6904 (org-defkey map "/" 'org-occur)
6905 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6906 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6907 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6908 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6909 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6910 map))
6912 (defconst org-goto-help
6913 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6914 RET=jump to location [Q]uit and return to previous location
6915 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6917 (defvar org-goto-start-pos) ; dynamically scoped parameter
6919 ;; FIXME: Docstring does not mention both interfaces
6920 (defun org-goto (&optional alternative-interface)
6921 "Look up a different location in the current file, keeping current visibility.
6923 When you want look-up or go to a different location in a
6924 document, the fastest way is often to fold the entire buffer and
6925 then dive into the tree. This method has the disadvantage, that
6926 the previous location will be folded, which may not be what you
6927 want.
6929 This command works around this by showing a copy of the current
6930 buffer in an indirect buffer, in overview mode. You can dive
6931 into the tree in that copy, use org-occur and incremental search
6932 to find a location. When pressing RET or `Q', the command
6933 returns to the original buffer in which the visibility is still
6934 unchanged. After RET it will also jump to the location selected
6935 in the indirect buffer and expose the headline hierarchy above.
6937 With a prefix argument, use the alternative interface: e.g. if
6938 `org-goto-interface' is 'outline use 'outline-path-completion."
6939 (interactive "P")
6940 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6941 (org-refile-use-outline-path t)
6942 (org-refile-target-verify-function nil)
6943 (interface
6944 (if (not alternative-interface)
6945 org-goto-interface
6946 (if (eq org-goto-interface 'outline)
6947 'outline-path-completion
6948 'outline)))
6949 (org-goto-start-pos (point))
6950 (selected-point
6951 (if (eq interface 'outline)
6952 (car (org-get-location (current-buffer) org-goto-help))
6953 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6954 (org-refile-check-position pa)
6955 (nth 3 pa)))))
6956 (if selected-point
6957 (progn
6958 (org-mark-ring-push org-goto-start-pos)
6959 (goto-char selected-point)
6960 (if (or (outline-invisible-p) (org-invisible-p2))
6961 (org-show-context 'org-goto)))
6962 (message "Quit"))))
6964 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6965 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6966 (defvar org-goto-local-auto-isearch-map) ; defined below
6968 (defun org-get-location (buf help)
6969 "Let the user select a location in the Org-mode buffer BUF.
6970 This function uses a recursive edit. It returns the selected position
6971 or nil."
6972 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6973 (isearch-hide-immediately nil)
6974 (isearch-search-fun-function
6975 (lambda () 'org-goto-local-search-headings))
6976 (org-goto-selected-point org-goto-exit-command)
6977 (pop-up-frames nil)
6978 (special-display-buffer-names nil)
6979 (special-display-regexps nil)
6980 (special-display-function nil))
6981 (save-excursion
6982 (save-window-excursion
6983 (delete-other-windows)
6984 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6985 (org-pop-to-buffer-same-window
6986 (condition-case nil
6987 (make-indirect-buffer (current-buffer) "*org-goto*")
6988 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6989 (with-output-to-temp-buffer "*Help*"
6990 (princ help))
6991 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6992 (setq buffer-read-only nil)
6993 (let ((org-startup-truncated t)
6994 (org-startup-folded nil)
6995 (org-startup-align-all-tables nil))
6996 (org-mode)
6997 (org-overview))
6998 (setq buffer-read-only t)
6999 (if (and (boundp 'org-goto-start-pos)
7000 (integer-or-marker-p org-goto-start-pos))
7001 (let ((org-show-hierarchy-above t)
7002 (org-show-siblings t)
7003 (org-show-following-heading t))
7004 (goto-char org-goto-start-pos)
7005 (and (outline-invisible-p) (org-show-context)))
7006 (goto-char (point-min)))
7007 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7008 (message "Select location and press RET")
7009 (use-local-map org-goto-map)
7010 (recursive-edit)
7012 (kill-buffer "*org-goto*")
7013 (cons org-goto-selected-point org-goto-exit-command)))
7015 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7016 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7017 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7018 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7020 (defun org-goto-local-search-headings (string bound noerror)
7021 "Search and make sure that any matches are in headlines."
7022 (catch 'return
7023 (while (if isearch-forward
7024 (search-forward string bound noerror)
7025 (search-backward string bound noerror))
7026 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7027 (and (member :headline context)
7028 (not (member :tags context))))
7029 (throw 'return (point))))))
7031 (defun org-goto-local-auto-isearch ()
7032 "Start isearch."
7033 (interactive)
7034 (goto-char (point-min))
7035 (let ((keys (this-command-keys)))
7036 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7037 (isearch-mode t)
7038 (isearch-process-search-char (string-to-char keys)))))
7040 (defun org-goto-ret (&optional arg)
7041 "Finish `org-goto' by going to the new location."
7042 (interactive "P")
7043 (setq org-goto-selected-point (point)
7044 org-goto-exit-command 'return)
7045 (throw 'exit nil))
7047 (defun org-goto-left ()
7048 "Finish `org-goto' by going to the new location."
7049 (interactive)
7050 (if (org-at-heading-p)
7051 (progn
7052 (beginning-of-line 1)
7053 (setq org-goto-selected-point (point)
7054 org-goto-exit-command 'left)
7055 (throw 'exit nil))
7056 (error "Not on a heading")))
7058 (defun org-goto-right ()
7059 "Finish `org-goto' by going to the new location."
7060 (interactive)
7061 (if (org-at-heading-p)
7062 (progn
7063 (setq org-goto-selected-point (point)
7064 org-goto-exit-command 'right)
7065 (throw 'exit nil))
7066 (error "Not on a heading")))
7068 (defun org-goto-quit ()
7069 "Finish `org-goto' without cursor motion."
7070 (interactive)
7071 (setq org-goto-selected-point nil)
7072 (setq org-goto-exit-command 'quit)
7073 (throw 'exit nil))
7075 ;;; Indirect buffer display of subtrees
7077 (defvar org-indirect-dedicated-frame nil
7078 "This is the frame being used for indirect tree display.")
7079 (defvar org-last-indirect-buffer nil)
7081 (defun org-tree-to-indirect-buffer (&optional arg)
7082 "Create indirect buffer and narrow it to current subtree.
7083 With numerical prefix ARG, go up to this level and then take that tree.
7084 If ARG is negative, go up that many levels.
7085 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7086 indirect buffer previously made with this command, to avoid proliferation of
7087 indirect buffers. However, when you call the command with a \
7088 \\[universal-argument] prefix, or
7089 when `org-indirect-buffer-display' is `new-frame', the last buffer
7090 is kept so that you can work with several indirect buffers at the same time.
7091 If `org-indirect-buffer-display' is `dedicated-frame', the \
7092 \\[universal-argument] prefix also
7093 requests that a new frame be made for the new buffer, so that the dedicated
7094 frame is not changed."
7095 (interactive "P")
7096 (let ((cbuf (current-buffer))
7097 (cwin (selected-window))
7098 (pos (point))
7099 beg end level heading ibuf)
7100 (save-excursion
7101 (org-back-to-heading t)
7102 (when (numberp arg)
7103 (setq level (org-outline-level))
7104 (if (< arg 0) (setq arg (+ level arg)))
7105 (while (> (setq level (org-outline-level)) arg)
7106 (outline-up-heading 1 t)))
7107 (setq beg (point)
7108 heading (org-get-heading))
7109 (org-end-of-subtree t t)
7110 (if (org-at-heading-p) (backward-char 1))
7111 (setq end (point)))
7112 (if (and (buffer-live-p org-last-indirect-buffer)
7113 (not (eq org-indirect-buffer-display 'new-frame))
7114 (not arg))
7115 (kill-buffer org-last-indirect-buffer))
7116 (setq ibuf (org-get-indirect-buffer cbuf)
7117 org-last-indirect-buffer ibuf)
7118 (cond
7119 ((or (eq org-indirect-buffer-display 'new-frame)
7120 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7121 (select-frame (make-frame))
7122 (delete-other-windows)
7123 (org-pop-to-buffer-same-window ibuf)
7124 (org-set-frame-title heading))
7125 ((eq org-indirect-buffer-display 'dedicated-frame)
7126 (raise-frame
7127 (select-frame (or (and org-indirect-dedicated-frame
7128 (frame-live-p org-indirect-dedicated-frame)
7129 org-indirect-dedicated-frame)
7130 (setq org-indirect-dedicated-frame (make-frame)))))
7131 (delete-other-windows)
7132 (org-pop-to-buffer-same-window ibuf)
7133 (org-set-frame-title (concat "Indirect: " heading)))
7134 ((eq org-indirect-buffer-display 'current-window)
7135 (org-pop-to-buffer-same-window ibuf))
7136 ((eq org-indirect-buffer-display 'other-window)
7137 (pop-to-buffer ibuf))
7138 (t (error "Invalid value")))
7139 (if (featurep 'xemacs)
7140 (save-excursion (org-mode) (turn-on-font-lock)))
7141 (narrow-to-region beg end)
7142 (show-all)
7143 (goto-char pos)
7144 (run-hook-with-args 'org-cycle-hook 'all)
7145 (and (window-live-p cwin) (select-window cwin))))
7147 (defun org-get-indirect-buffer (&optional buffer)
7148 (setq buffer (or buffer (current-buffer)))
7149 (let ((n 1) (base (buffer-name buffer)) bname)
7150 (while (buffer-live-p
7151 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7152 (setq n (1+ n)))
7153 (condition-case nil
7154 (make-indirect-buffer buffer bname 'clone)
7155 (error (make-indirect-buffer buffer bname)))))
7157 (defun org-set-frame-title (title)
7158 "Set the title of the current frame to the string TITLE."
7159 ;; FIXME: how to name a single frame in XEmacs???
7160 (unless (featurep 'xemacs)
7161 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7163 ;;;; Structure editing
7165 ;;; Inserting headlines
7167 (defun org-previous-line-empty-p ()
7168 (save-excursion
7169 (and (not (bobp))
7170 (or (beginning-of-line 0) t)
7171 (save-match-data
7172 (looking-at "[ \t]*$")))))
7174 (defun org-insert-heading (&optional force-heading invisible-ok)
7175 "Insert a new heading or item with same depth at point.
7176 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7177 If point is at the beginning of a headline, insert a sibling before the
7178 current headline. If point is not at the beginning, split the line,
7179 create the new headline with the text in the current line after point
7180 \(but see also the variable `org-M-RET-may-split-line').
7182 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7183 This is important for non-interactive uses of the command."
7184 (interactive "P")
7185 (if (or (= (buffer-size) 0)
7186 (and (not (save-excursion
7187 (and (ignore-errors (org-back-to-heading invisible-ok))
7188 (org-at-heading-p))))
7189 (or force-heading (not (org-in-item-p)))))
7190 (progn
7191 (insert "\n* ")
7192 (run-hooks 'org-insert-heading-hook))
7193 (when (or force-heading (not (org-insert-item)))
7194 (let* ((empty-line-p nil)
7195 (level nil)
7196 (on-heading (org-at-heading-p))
7197 (head (save-excursion
7198 (condition-case nil
7199 (progn
7200 (org-back-to-heading invisible-ok)
7201 (when (and (not on-heading)
7202 (featurep 'org-inlinetask)
7203 (integerp org-inlinetask-min-level)
7204 (>= (length (match-string 0))
7205 org-inlinetask-min-level))
7206 ;; Find a heading level before the inline task
7207 (while (and (setq level (org-up-heading-safe))
7208 (>= level org-inlinetask-min-level)))
7209 (if (org-at-heading-p)
7210 (org-back-to-heading invisible-ok)
7211 (error "This should not happen")))
7212 (setq empty-line-p (org-previous-line-empty-p))
7213 (match-string 0))
7214 (error "*"))))
7215 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7216 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7217 pos hide-previous previous-pos)
7218 (cond
7219 ((and (org-at-heading-p) (bolp)
7220 (or (bobp)
7221 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7222 ;; insert before the current line
7223 (open-line (if blank 2 1)))
7224 ((and (bolp)
7225 (not org-insert-heading-respect-content)
7226 (or (bobp)
7227 (save-excursion
7228 (backward-char 1) (not (outline-invisible-p)))))
7229 ;; insert right here
7230 nil)
7232 ;; somewhere in the line
7233 (save-excursion
7234 (setq previous-pos (point-at-bol))
7235 (end-of-line)
7236 (setq hide-previous (outline-invisible-p)))
7237 (and org-insert-heading-respect-content (org-show-subtree))
7238 (let ((split
7239 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7240 (save-excursion
7241 (let ((p (point)))
7242 (goto-char (point-at-bol))
7243 (and (looking-at org-complex-heading-regexp)
7244 (match-beginning 4)
7245 (> p (match-beginning 4)))))))
7246 tags pos)
7247 (cond
7248 (org-insert-heading-respect-content
7249 (org-end-of-subtree nil t)
7250 (when (featurep 'org-inlinetask)
7251 (while (and (not (eobp))
7252 (looking-at "\\(\\*+\\)[ \t]+")
7253 (>= (length (match-string 1))
7254 org-inlinetask-min-level))
7255 (org-end-of-subtree nil t)))
7256 (or (bolp) (newline))
7257 (or (org-previous-line-empty-p)
7258 (and blank (newline)))
7259 (open-line 1))
7260 ((org-at-heading-p)
7261 (when hide-previous
7262 (show-children)
7263 (org-show-entry))
7264 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7265 (setq tags (and (match-end 2) (match-string 2)))
7266 (and (match-end 1)
7267 (delete-region (match-beginning 1) (match-end 1)))
7268 (setq pos (point-at-bol))
7269 (or split (end-of-line 1))
7270 (delete-horizontal-space)
7271 (if (string-match "\\`\\*+\\'"
7272 (buffer-substring (point-at-bol) (point)))
7273 (insert " "))
7274 (newline (if blank 2 1))
7275 (when tags
7276 (save-excursion
7277 (goto-char pos)
7278 (end-of-line 1)
7279 (insert " " tags)
7280 (org-set-tags nil 'align))))
7282 (or split (end-of-line 1))
7283 (newline (if blank 2 1)))))))
7284 (insert head) (just-one-space)
7285 (setq pos (point))
7286 (end-of-line 1)
7287 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7288 (when (and org-insert-heading-respect-content hide-previous)
7289 (save-excursion
7290 (goto-char previous-pos)
7291 (hide-subtree)))
7292 (run-hooks 'org-insert-heading-hook)))))
7294 (defun org-get-heading (&optional no-tags no-todo)
7295 "Return the heading of the current entry, without the stars.
7296 When NO-TAGS is non-nil, don't include tags.
7297 When NO-TODO is non-nil, don't include TODO keywords."
7298 (save-excursion
7299 (org-back-to-heading t)
7300 (cond
7301 ((and no-tags no-todo)
7302 (looking-at org-complex-heading-regexp)
7303 (match-string 4))
7304 (no-tags
7305 (looking-at (concat org-outline-regexp
7306 "\\(.*?\\)"
7307 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7308 (match-string 1))
7309 (no-todo
7310 (looking-at org-todo-line-regexp)
7311 (match-string 3))
7312 (t (looking-at org-heading-regexp)
7313 (match-string 2)))))
7315 (defun org-heading-components ()
7316 "Return the components of the current heading.
7317 This is a list with the following elements:
7318 - the level as an integer
7319 - the reduced level, different if `org-odd-levels-only' is set.
7320 - the TODO keyword, or nil
7321 - the priority character, like ?A, or nil if no priority is given
7322 - the headline text itself, or the tags string if no headline text
7323 - the tags string, or nil."
7324 (save-excursion
7325 (org-back-to-heading t)
7326 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7327 (list (length (match-string 1))
7328 (org-reduced-level (length (match-string 1)))
7329 (org-match-string-no-properties 2)
7330 (and (match-end 3) (aref (match-string 3) 2))
7331 (org-match-string-no-properties 4)
7332 (org-match-string-no-properties 5)))))
7334 (defun org-get-entry ()
7335 "Get the entry text, after heading, entire subtree."
7336 (save-excursion
7337 (org-back-to-heading t)
7338 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7340 (defun org-insert-heading-after-current ()
7341 "Insert a new heading with same level as current, after current subtree."
7342 (interactive)
7343 (org-back-to-heading)
7344 (org-insert-heading)
7345 (org-move-subtree-down)
7346 (end-of-line 1))
7348 (defun org-insert-heading-respect-content ()
7349 (interactive)
7350 (let ((org-insert-heading-respect-content t))
7351 (org-insert-heading t)))
7353 (defun org-insert-todo-heading-respect-content (&optional force-state)
7354 (interactive "P")
7355 (let ((org-insert-heading-respect-content t))
7356 (org-insert-todo-heading force-state t)))
7358 (defun org-insert-todo-heading (arg &optional force-heading)
7359 "Insert a new heading with the same level and TODO state as current heading.
7360 If the heading has no TODO state, or if the state is DONE, use the first
7361 state (TODO by default). Also with prefix arg, force first state."
7362 (interactive "P")
7363 (when (or force-heading (not (org-insert-item 'checkbox)))
7364 (org-insert-heading force-heading)
7365 (save-excursion
7366 (org-back-to-heading)
7367 (outline-previous-heading)
7368 (looking-at org-todo-line-regexp))
7369 (let*
7370 ((new-mark-x
7371 (if (or arg
7372 (not (match-beginning 2))
7373 (member (match-string 2) org-done-keywords))
7374 (car org-todo-keywords-1)
7375 (match-string 2)))
7376 (new-mark
7378 (run-hook-with-args-until-success
7379 'org-todo-get-default-hook new-mark-x nil)
7380 new-mark-x)))
7381 (beginning-of-line 1)
7382 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7383 (if org-treat-insert-todo-heading-as-state-change
7384 (org-todo new-mark)
7385 (insert new-mark " "))))
7386 (when org-provide-todo-statistics
7387 (org-update-parent-todo-statistics))))
7389 (defun org-insert-subheading (arg)
7390 "Insert a new subheading and demote it.
7391 Works for outline headings and for plain lists alike."
7392 (interactive "P")
7393 (org-insert-heading arg)
7394 (cond
7395 ((org-at-heading-p) (org-do-demote))
7396 ((org-at-item-p) (org-indent-item))))
7398 (defun org-insert-todo-subheading (arg)
7399 "Insert a new subheading with TODO keyword or checkbox and demote it.
7400 Works for outline headings and for plain lists alike."
7401 (interactive "P")
7402 (org-insert-todo-heading arg)
7403 (cond
7404 ((org-at-heading-p) (org-do-demote))
7405 ((org-at-item-p) (org-indent-item))))
7407 ;;; Promotion and Demotion
7409 (defvar org-after-demote-entry-hook nil
7410 "Hook run after an entry has been demoted.
7411 The cursor will be at the beginning of the entry.
7412 When a subtree is being demoted, the hook will be called for each node.")
7414 (defvar org-after-promote-entry-hook nil
7415 "Hook run after an entry has been promoted.
7416 The cursor will be at the beginning of the entry.
7417 When a subtree is being promoted, the hook will be called for each node.")
7419 (defun org-promote-subtree ()
7420 "Promote the entire subtree.
7421 See also `org-promote'."
7422 (interactive)
7423 (save-excursion
7424 (org-with-limited-levels (org-map-tree 'org-promote)))
7425 (org-fix-position-after-promote))
7427 (defun org-demote-subtree ()
7428 "Demote the entire subtree. See `org-demote'.
7429 See also `org-promote'."
7430 (interactive)
7431 (save-excursion
7432 (org-with-limited-levels (org-map-tree 'org-demote)))
7433 (org-fix-position-after-promote))
7436 (defun org-do-promote ()
7437 "Promote the current heading higher up the tree.
7438 If the region is active in `transient-mark-mode', promote all headings
7439 in the region."
7440 (interactive)
7441 (save-excursion
7442 (if (org-region-active-p)
7443 (org-map-region 'org-promote (region-beginning) (region-end))
7444 (org-promote)))
7445 (org-fix-position-after-promote))
7447 (defun org-do-demote ()
7448 "Demote the current heading lower down the tree.
7449 If the region is active in `transient-mark-mode', demote all headings
7450 in the region."
7451 (interactive)
7452 (save-excursion
7453 (if (org-region-active-p)
7454 (org-map-region 'org-demote (region-beginning) (region-end))
7455 (org-demote)))
7456 (org-fix-position-after-promote))
7458 (defun org-fix-position-after-promote ()
7459 "Make sure that after pro/demotion cursor position is right."
7460 (let ((pos (point)))
7461 (when (save-excursion
7462 (beginning-of-line 1)
7463 (looking-at org-todo-line-regexp)
7464 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7465 (cond ((eobp) (insert " "))
7466 ((eolp) (insert " "))
7467 ((equal (char-after) ?\ ) (forward-char 1))))))
7469 (defun org-current-level ()
7470 "Return the level of the current entry, or nil if before the first headline.
7471 The level is the number of stars at the beginning of the headline."
7472 (save-excursion
7473 (org-with-limited-levels
7474 (if (ignore-errors (org-back-to-heading t))
7475 (funcall outline-level)))))
7477 (defun org-get-previous-line-level ()
7478 "Return the outline depth of the last headline before the current line.
7479 Returns 0 for the first headline in the buffer, and nil if before the
7480 first headline."
7481 (let ((current-level (org-current-level))
7482 (prev-level (when (> (line-number-at-pos) 1)
7483 (save-excursion
7484 (beginning-of-line 0)
7485 (org-current-level)))))
7486 (cond ((null current-level) nil) ; Before first headline
7487 ((null prev-level) 0) ; At first headline
7488 (prev-level))))
7490 (defun org-reduced-level (l)
7491 "Compute the effective level of a heading.
7492 This takes into account the setting of `org-odd-levels-only'."
7493 (cond
7494 ((zerop l) 0)
7495 (org-odd-levels-only (1+ (floor (/ l 2))))
7496 (t l)))
7498 (defun org-level-increment ()
7499 "Return the number of stars that will be added or removed at a
7500 time to headlines when structure editing, based on the value of
7501 `org-odd-levels-only'."
7502 (if org-odd-levels-only 2 1))
7504 (defun org-get-valid-level (level &optional change)
7505 "Rectify a level change under the influence of `org-odd-levels-only'
7506 LEVEL is a current level, CHANGE is by how much the level should be
7507 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7508 even level numbers will become the next higher odd number."
7509 (if org-odd-levels-only
7510 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7511 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7512 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7513 (max 1 (+ level (or change 0)))))
7515 (if (boundp 'define-obsolete-function-alias)
7516 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7517 (define-obsolete-function-alias 'org-get-legal-level
7518 'org-get-valid-level)
7519 (define-obsolete-function-alias 'org-get-legal-level
7520 'org-get-valid-level "23.1")))
7522 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7523 ;; ̀org-with-limited-levels'
7524 (defun org-promote ()
7525 "Promote the current heading higher up the tree.
7526 If the region is active in `transient-mark-mode', promote all headings
7527 in the region."
7528 (org-back-to-heading t)
7529 (let* ((level (save-match-data (funcall outline-level)))
7530 (after-change-functions (remove 'flyspell-after-change-function
7531 after-change-functions))
7532 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7533 (diff (abs (- level (length up-head) -1))))
7534 (cond ((and (= level 1) org-called-with-limited-levels
7535 org-allow-promoting-top-level-subtree)
7536 (replace-match "# " nil t))
7537 ((= level 1)
7538 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7539 (t (replace-match up-head nil t)))
7540 ;; Fixup tag positioning
7541 (unless (= level 1)
7542 (and org-auto-align-tags (org-set-tags nil t))
7543 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7544 (run-hooks 'org-after-promote-entry-hook)))
7546 (defun org-demote ()
7547 "Demote the current heading lower down the tree.
7548 If the region is active in `transient-mark-mode', demote all headings
7549 in the region."
7550 (org-back-to-heading t)
7551 (let* ((level (save-match-data (funcall outline-level)))
7552 (after-change-functions (remove 'flyspell-after-change-function
7553 after-change-functions))
7554 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7555 (diff (abs (- level (length down-head) -1))))
7556 (replace-match down-head nil t)
7557 ;; Fixup tag positioning
7558 (and org-auto-align-tags (org-set-tags nil t))
7559 (if org-adapt-indentation (org-fixup-indentation diff))
7560 (run-hooks 'org-after-demote-entry-hook)))
7562 (defun org-cycle-level ()
7563 "Cycle the level of an empty headline through possible states.
7564 This goes first to child, then to parent, level, then up the hierarchy.
7565 After top level, it switches back to sibling level."
7566 (interactive)
7567 (let ((org-adapt-indentation nil))
7568 (when (org-point-at-end-of-empty-headline)
7569 (setq this-command 'org-cycle-level) ; Only needed for caching
7570 (let ((cur-level (org-current-level))
7571 (prev-level (org-get-previous-line-level)))
7572 (cond
7573 ;; If first headline in file, promote to top-level.
7574 ((= prev-level 0)
7575 (loop repeat (/ (- cur-level 1) (org-level-increment))
7576 do (org-do-promote)))
7577 ;; If same level as prev, demote one.
7578 ((= prev-level cur-level)
7579 (org-do-demote))
7580 ;; If parent is top-level, promote to top level if not already.
7581 ((= prev-level 1)
7582 (loop repeat (/ (- cur-level 1) (org-level-increment))
7583 do (org-do-promote)))
7584 ;; If top-level, return to prev-level.
7585 ((= cur-level 1)
7586 (loop repeat (/ (- prev-level 1) (org-level-increment))
7587 do (org-do-demote)))
7588 ;; If less than prev-level, promote one.
7589 ((< cur-level prev-level)
7590 (org-do-promote))
7591 ;; If deeper than prev-level, promote until higher than
7592 ;; prev-level.
7593 ((> cur-level prev-level)
7594 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7595 do (org-do-promote))))
7596 t))))
7598 (defun org-map-tree (fun)
7599 "Call FUN for every heading underneath the current one."
7600 (org-back-to-heading)
7601 (let ((level (funcall outline-level)))
7602 (save-excursion
7603 (funcall fun)
7604 (while (and (progn
7605 (outline-next-heading)
7606 (> (funcall outline-level) level))
7607 (not (eobp)))
7608 (funcall fun)))))
7610 (defun org-map-region (fun beg end)
7611 "Call FUN for every heading between BEG and END."
7612 (let ((org-ignore-region t))
7613 (save-excursion
7614 (setq end (copy-marker end))
7615 (goto-char beg)
7616 (if (and (re-search-forward org-outline-regexp-bol nil t)
7617 (< (point) end))
7618 (funcall fun))
7619 (while (and (progn
7620 (outline-next-heading)
7621 (< (point) end))
7622 (not (eobp)))
7623 (funcall fun)))))
7625 (defvar org-property-end-re) ; silence byte-compiler
7626 (defun org-fixup-indentation (diff)
7627 "Change the indentation in the current entry by DIFF.
7628 However, if any line in the current entry has no indentation, or if it
7629 would end up with no indentation after the change, nothing at all is done."
7630 (save-excursion
7631 (let ((end (save-excursion (outline-next-heading)
7632 (point-marker)))
7633 (prohibit (if (> diff 0)
7634 "^\\S-"
7635 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7636 col)
7637 (unless (save-excursion (end-of-line 1)
7638 (re-search-forward prohibit end t))
7639 (while (and (< (point) end)
7640 (re-search-forward "^[ \t]+" end t))
7641 (goto-char (match-end 0))
7642 (setq col (current-column))
7643 (if (< diff 0) (replace-match ""))
7644 (org-indent-to-column (+ diff col))))
7645 (move-marker end nil))))
7647 (defun org-convert-to-odd-levels ()
7648 "Convert an org-mode file with all levels allowed to one with odd levels.
7649 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7650 level 5 etc."
7651 (interactive)
7652 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7653 (let ((outline-level 'org-outline-level)
7654 (org-odd-levels-only nil) n)
7655 (save-excursion
7656 (goto-char (point-min))
7657 (while (re-search-forward "^\\*\\*+ " nil t)
7658 (setq n (- (length (match-string 0)) 2))
7659 (while (>= (setq n (1- n)) 0)
7660 (org-demote))
7661 (end-of-line 1))))))
7663 (defun org-convert-to-oddeven-levels ()
7664 "Convert an org-mode file with only odd levels to one with odd/even levels.
7665 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7666 file contains a section with an even level, conversion would
7667 destroy the structure of the file. An error is signaled in this
7668 case."
7669 (interactive)
7670 (goto-char (point-min))
7671 ;; First check if there are no even levels
7672 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7673 (org-show-context t)
7674 (error "Not all levels are odd in this file. Conversion not possible"))
7675 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7676 (let ((outline-regexp org-outline-regexp)
7677 (outline-level 'org-outline-level)
7678 (org-odd-levels-only nil) n)
7679 (save-excursion
7680 (goto-char (point-min))
7681 (while (re-search-forward "^\\*\\*+ " nil t)
7682 (setq n (/ (1- (length (match-string 0))) 2))
7683 (while (>= (setq n (1- n)) 0)
7684 (org-promote))
7685 (end-of-line 1))))))
7687 (defun org-tr-level (n)
7688 "Make N odd if required."
7689 (if org-odd-levels-only (1+ (/ n 2)) n))
7691 ;;; Vertical tree motion, cutting and pasting of subtrees
7693 (defun org-move-subtree-up (&optional arg)
7694 "Move the current subtree up past ARG headlines of the same level."
7695 (interactive "p")
7696 (org-move-subtree-down (- (prefix-numeric-value arg))))
7698 (defun org-move-subtree-down (&optional arg)
7699 "Move the current subtree down past ARG headlines of the same level."
7700 (interactive "p")
7701 (setq arg (prefix-numeric-value arg))
7702 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7703 'org-get-last-sibling))
7704 (ins-point (make-marker))
7705 (cnt (abs arg))
7706 (col (current-column))
7707 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7708 ;; Select the tree
7709 (org-back-to-heading)
7710 (setq beg0 (point))
7711 (save-excursion
7712 (setq ne-beg (org-back-over-empty-lines))
7713 (setq beg (point)))
7714 (save-match-data
7715 (save-excursion (outline-end-of-heading)
7716 (setq folded (outline-invisible-p)))
7717 (outline-end-of-subtree))
7718 (outline-next-heading)
7719 (setq ne-end (org-back-over-empty-lines))
7720 (setq end (point))
7721 (goto-char beg0)
7722 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7723 ;; include less whitespace
7724 (save-excursion
7725 (goto-char beg)
7726 (forward-line (- ne-beg ne-end))
7727 (setq beg (point))))
7728 ;; Find insertion point, with error handling
7729 (while (> cnt 0)
7730 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7731 (progn (goto-char beg0)
7732 (error "Cannot move past superior level or buffer limit")))
7733 (setq cnt (1- cnt)))
7734 (if (> arg 0)
7735 ;; Moving forward - still need to move over subtree
7736 (progn (org-end-of-subtree t t)
7737 (save-excursion
7738 (org-back-over-empty-lines)
7739 (or (bolp) (newline)))))
7740 (setq ne-ins (org-back-over-empty-lines))
7741 (move-marker ins-point (point))
7742 (setq txt (buffer-substring beg end))
7743 (org-save-markers-in-region beg end)
7744 (delete-region beg end)
7745 (org-remove-empty-overlays-at beg)
7746 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7747 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7748 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7749 (let ((bbb (point)))
7750 (insert-before-markers txt)
7751 (org-reinstall-markers-in-region bbb)
7752 (move-marker ins-point bbb))
7753 (or (bolp) (insert "\n"))
7754 (setq ins-end (point))
7755 (goto-char ins-point)
7756 (org-skip-whitespace)
7757 (when (and (< arg 0)
7758 (org-first-sibling-p)
7759 (> ne-ins ne-beg))
7760 ;; Move whitespace back to beginning
7761 (save-excursion
7762 (goto-char ins-end)
7763 (let ((kill-whole-line t))
7764 (kill-line (- ne-ins ne-beg)) (point)))
7765 (insert (make-string (- ne-ins ne-beg) ?\n)))
7766 (move-marker ins-point nil)
7767 (if folded
7768 (hide-subtree)
7769 (org-show-entry)
7770 (show-children)
7771 (org-cycle-hide-drawers 'children))
7772 (org-clean-visibility-after-subtree-move)
7773 ;; move back to the initial column we were at
7774 (move-to-column col)))
7776 (defvar org-subtree-clip ""
7777 "Clipboard for cut and paste of subtrees.
7778 This is actually only a copy of the kill, because we use the normal kill
7779 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7781 (defvar org-subtree-clip-folded nil
7782 "Was the last copied subtree folded?
7783 This is used to fold the tree back after pasting.")
7785 (defun org-cut-subtree (&optional n)
7786 "Cut the current subtree into the clipboard.
7787 With prefix arg N, cut this many sequential subtrees.
7788 This is a short-hand for marking the subtree and then cutting it."
7789 (interactive "p")
7790 (org-copy-subtree n 'cut))
7792 (defun org-copy-subtree (&optional n cut force-store-markers)
7793 "Cut the current subtree into the clipboard.
7794 With prefix arg N, cut this many sequential subtrees.
7795 This is a short-hand for marking the subtree and then copying it.
7796 If CUT is non-nil, actually cut the subtree.
7797 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7798 of some markers in the region, even if CUT is non-nil. This is
7799 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7800 (interactive "p")
7801 (let (beg end folded (beg0 (point)))
7802 (if (org-called-interactively-p 'any)
7803 (org-back-to-heading nil) ; take what looks like a subtree
7804 (org-back-to-heading t)) ; take what is really there
7805 (org-back-over-empty-lines)
7806 (setq beg (point))
7807 (skip-chars-forward " \t\r\n")
7808 (save-match-data
7809 (save-excursion (outline-end-of-heading)
7810 (setq folded (outline-invisible-p)))
7811 (condition-case nil
7812 (org-forward-same-level (1- n) t)
7813 (error nil))
7814 (org-end-of-subtree t t))
7815 (org-back-over-empty-lines)
7816 (setq end (point))
7817 (goto-char beg0)
7818 (when (> end beg)
7819 (setq org-subtree-clip-folded folded)
7820 (when (or cut force-store-markers)
7821 (org-save-markers-in-region beg end))
7822 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7823 (setq org-subtree-clip (current-kill 0))
7824 (message "%s: Subtree(s) with %d characters"
7825 (if cut "Cut" "Copied")
7826 (length org-subtree-clip)))))
7828 (defun org-paste-subtree (&optional level tree for-yank)
7829 "Paste the clipboard as a subtree, with modification of headline level.
7830 The entire subtree is promoted or demoted in order to match a new headline
7831 level.
7833 If the cursor is at the beginning of a headline, the same level as
7834 that headline is used to paste the tree
7836 If not, the new level is derived from the *visible* headings
7837 before and after the insertion point, and taken to be the inferior headline
7838 level of the two. So if the previous visible heading is level 3 and the
7839 next is level 4 (or vice versa), level 4 will be used for insertion.
7840 This makes sure that the subtree remains an independent subtree and does
7841 not swallow low level entries.
7843 You can also force a different level, either by using a numeric prefix
7844 argument, or by inserting the heading marker by hand. For example, if the
7845 cursor is after \"*****\", then the tree will be shifted to level 5.
7847 If optional TREE is given, use this text instead of the kill ring.
7849 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7850 move back over whitespace before inserting, and move point to the end of
7851 the inserted text when done."
7852 (interactive "P")
7853 (setq tree (or tree (and kill-ring (current-kill 0))))
7854 (unless (org-kill-is-subtree-p tree)
7855 (error "%s"
7856 (substitute-command-keys
7857 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7858 (org-with-limited-levels
7859 (let* ((visp (not (outline-invisible-p)))
7860 (txt tree)
7861 (^re_ "\\(\\*+\\)[ \t]*")
7862 (old-level (if (string-match org-outline-regexp-bol txt)
7863 (- (match-end 0) (match-beginning 0) 1)
7864 -1))
7865 (force-level (cond (level (prefix-numeric-value level))
7866 ((and (looking-at "[ \t]*$")
7867 (string-match
7868 "^\\*+$" (buffer-substring
7869 (point-at-bol) (point))))
7870 (- (match-end 1) (match-beginning 1)))
7871 ((and (bolp)
7872 (looking-at org-outline-regexp))
7873 (- (match-end 0) (point) 1))
7874 (t nil)))
7875 (previous-level (save-excursion
7876 (condition-case nil
7877 (progn
7878 (outline-previous-visible-heading 1)
7879 (if (looking-at ^re_)
7880 (- (match-end 0) (match-beginning 0) 1)
7882 (error 1))))
7883 (next-level (save-excursion
7884 (condition-case nil
7885 (progn
7886 (or (looking-at org-outline-regexp)
7887 (outline-next-visible-heading 1))
7888 (if (looking-at ^re_)
7889 (- (match-end 0) (match-beginning 0) 1)
7891 (error 1))))
7892 (new-level (or force-level (max previous-level next-level)))
7893 (shift (if (or (= old-level -1)
7894 (= new-level -1)
7895 (= old-level new-level))
7897 (- new-level old-level)))
7898 (delta (if (> shift 0) -1 1))
7899 (func (if (> shift 0) 'org-demote 'org-promote))
7900 (org-odd-levels-only nil)
7901 beg end newend)
7902 ;; Remove the forced level indicator
7903 (if force-level
7904 (delete-region (point-at-bol) (point)))
7905 ;; Paste
7906 (beginning-of-line (if (bolp) 1 2))
7907 (unless for-yank (org-back-over-empty-lines))
7908 (setq beg (point))
7909 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7910 (insert-before-markers txt)
7911 (unless (string-match "\n\\'" txt) (insert "\n"))
7912 (setq newend (point))
7913 (org-reinstall-markers-in-region beg)
7914 (setq end (point))
7915 (goto-char beg)
7916 (skip-chars-forward " \t\n\r")
7917 (setq beg (point))
7918 (if (and (outline-invisible-p) visp)
7919 (save-excursion (outline-show-heading)))
7920 ;; Shift if necessary
7921 (unless (= shift 0)
7922 (save-restriction
7923 (narrow-to-region beg end)
7924 (while (not (= shift 0))
7925 (org-map-region func (point-min) (point-max))
7926 (setq shift (+ delta shift)))
7927 (goto-char (point-min))
7928 (setq newend (point-max))))
7929 (when (or (org-called-interactively-p 'interactive) for-yank)
7930 (message "Clipboard pasted as level %d subtree" new-level))
7931 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7932 kill-ring
7933 (eq org-subtree-clip (current-kill 0))
7934 org-subtree-clip-folded)
7935 ;; The tree was folded before it was killed/copied
7936 (hide-subtree))
7937 (and for-yank (goto-char newend)))))
7939 (defun org-kill-is-subtree-p (&optional txt)
7940 "Check if the current kill is an outline subtree, or a set of trees.
7941 Returns nil if kill does not start with a headline, or if the first
7942 headline level is not the largest headline level in the tree.
7943 So this will actually accept several entries of equal levels as well,
7944 which is OK for `org-paste-subtree'.
7945 If optional TXT is given, check this string instead of the current kill."
7946 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7947 (re (org-get-limited-outline-regexp))
7948 (^re (concat "^" re))
7949 (start-level (and kill
7950 (string-match
7951 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7952 kill)
7953 (- (match-end 2) (match-beginning 2) 1)))
7954 (start (1+ (or (match-beginning 2) -1))))
7955 (if (not start-level)
7956 (progn
7957 nil) ;; does not even start with a heading
7958 (catch 'exit
7959 (while (setq start (string-match ^re kill (1+ start)))
7960 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7961 (throw 'exit nil)))
7962 t))))
7964 (defvar org-markers-to-move nil
7965 "Markers that should be moved with a cut-and-paste operation.
7966 Those markers are stored together with their positions relative to
7967 the start of the region.")
7969 (defun org-save-markers-in-region (beg end)
7970 "Check markers in region.
7971 If these markers are between BEG and END, record their position relative
7972 to BEG, so that after moving the block of text, we can put the markers back
7973 into place.
7974 This function gets called just before an entry or tree gets cut from the
7975 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7976 called immediately, to move the markers with the entries."
7977 (setq org-markers-to-move nil)
7978 (when (featurep 'org-clock)
7979 (org-clock-save-markers-for-cut-and-paste beg end))
7980 (when (featurep 'org-agenda)
7981 (org-agenda-save-markers-for-cut-and-paste beg end)))
7983 (defun org-check-and-save-marker (marker beg end)
7984 "Check if MARKER is between BEG and END.
7985 If yes, remember the marker and the distance to BEG."
7986 (when (and (marker-buffer marker)
7987 (equal (marker-buffer marker) (current-buffer)))
7988 (if (and (>= marker beg) (< marker end))
7989 (push (cons marker (- marker beg)) org-markers-to-move))))
7991 (defun org-reinstall-markers-in-region (beg)
7992 "Move all remembered markers to their position relative to BEG."
7993 (mapc (lambda (x)
7994 (move-marker (car x) (+ beg (cdr x))))
7995 org-markers-to-move)
7996 (setq org-markers-to-move nil))
7998 (defun org-narrow-to-subtree ()
7999 "Narrow buffer to the current subtree."
8000 (interactive)
8001 (save-excursion
8002 (save-match-data
8003 (org-with-limited-levels
8004 (narrow-to-region
8005 (progn (org-back-to-heading t) (point))
8006 (progn (org-end-of-subtree t t)
8007 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8008 (point)))))))
8010 (defun org-narrow-to-block ()
8011 "Narrow buffer to the current block."
8012 (interactive)
8013 (let* ((case-fold-search t)
8014 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8015 "^[ \t]*#\\+end_.*")))
8016 (if blockp
8017 (narrow-to-region (car blockp) (cdr blockp))
8018 (error "Not in a block"))))
8020 (eval-when-compile
8021 (defvar org-property-drawer-re))
8023 (defvar org-property-start-re) ;; defined below
8024 (defun org-clone-subtree-with-time-shift (n &optional shift)
8025 "Clone the task (subtree) at point N times.
8026 The clones will be inserted as siblings.
8028 In interactive use, the user will be prompted for the number of
8029 clones to be produced, and for a time SHIFT, which may be a
8030 repeater as used in time stamps, for example `+3d'.
8032 When a valid repeater is given and the entry contains any time
8033 stamps, the clones will become a sequence in time, with time
8034 stamps in the subtree shifted for each clone produced. If SHIFT
8035 is nil or the empty string, time stamps will be left alone. The
8036 ID property of the original subtree is removed.
8038 If the original subtree did contain time stamps with a repeater,
8039 the following will happen:
8040 - the repeater will be removed in each clone
8041 - an additional clone will be produced, with the current, unshifted
8042 date(s) in the entry.
8043 - the original entry will be placed *after* all the clones, with
8044 repeater intact.
8045 - the start days in the repeater in the original entry will be shifted
8046 to past the last clone.
8047 In this way you can spell out a number of instances of a repeating task,
8048 and still retain the repeater to cover future instances of the task."
8049 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8050 (let (beg end template task idprop
8051 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8052 (drawer-re org-drawer-regexp))
8053 (if (not (and (integerp n) (> n 0)))
8054 (error "Invalid number of replications %s" n))
8055 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8056 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8057 shift)))
8058 (error "Invalid shift specification %s" shift))
8059 (when doshift
8060 (setq shift-n (string-to-number (match-string 1 shift))
8061 shift-what (cdr (assoc (match-string 2 shift)
8062 '(("d" . day) ("w" . week)
8063 ("m" . month) ("y" . year))))))
8064 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8065 (setq nmin 1 nmax n)
8066 (org-back-to-heading t)
8067 (setq beg (point))
8068 (setq idprop (org-entry-get nil "ID"))
8069 (org-end-of-subtree t t)
8070 (or (bolp) (insert "\n"))
8071 (setq end (point))
8072 (setq template (buffer-substring beg end))
8073 (when (and doshift
8074 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8075 (delete-region beg end)
8076 (setq end beg)
8077 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8078 (goto-char end)
8079 (loop for n from nmin to nmax do
8080 ;; prepare clone
8081 (with-temp-buffer
8082 (insert template)
8083 (org-mode)
8084 (goto-char (point-min))
8085 (org-show-subtree)
8086 (and idprop (if org-clone-delete-id
8087 (org-entry-delete nil "ID")
8088 (org-id-get-create t)))
8089 (unless (= n 0)
8090 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8091 (kill-whole-line))
8092 (goto-char (point-min))
8093 (while (re-search-forward drawer-re nil t)
8094 (mapc (lambda (d)
8095 (org-remove-empty-drawer-at d (point))) org-drawers)))
8096 (goto-char (point-min))
8097 (when doshift
8098 (while (re-search-forward org-ts-regexp-both nil t)
8099 (org-timestamp-change (* n shift-n) shift-what))
8100 (unless (= n n-no-remove)
8101 (goto-char (point-min))
8102 (while (re-search-forward org-ts-regexp nil t)
8103 (save-excursion
8104 (goto-char (match-beginning 0))
8105 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8106 (delete-region (match-beginning 1) (match-end 1)))))))
8107 (setq task (buffer-string)))
8108 (insert task))
8109 (goto-char beg)))
8111 ;;; Outline Sorting
8113 (defun org-sort (with-case)
8114 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8115 Optional argument WITH-CASE means sort case-sensitively."
8116 (interactive "P")
8117 (cond
8118 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8119 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8121 (org-call-with-arg 'org-sort-entries with-case))))
8123 (defun org-sort-remove-invisible (s)
8124 (remove-text-properties 0 (length s) org-rm-props s)
8125 (while (string-match org-bracket-link-regexp s)
8126 (setq s (replace-match (if (match-end 2)
8127 (match-string 3 s)
8128 (match-string 1 s)) t t s)))
8131 (defvar org-priority-regexp) ; defined later in the file
8133 (defvar org-after-sorting-entries-or-items-hook nil
8134 "Hook that is run after a bunch of entries or items have been sorted.
8135 When children are sorted, the cursor is in the parent line when this
8136 hook gets called. When a region or a plain list is sorted, the cursor
8137 will be in the first entry of the sorted region/list.")
8139 (defun org-sort-entries
8140 (&optional with-case sorting-type getkey-func compare-func property)
8141 "Sort entries on a certain level of an outline tree.
8142 If there is an active region, the entries in the region are sorted.
8143 Else, if the cursor is before the first entry, sort the top-level items.
8144 Else, the children of the entry at point are sorted.
8146 Sorting can be alphabetically, numerically, by date/time as given by
8147 a time stamp, by a property or by priority.
8149 The command prompts for the sorting type unless it has been given to the
8150 function through the SORTING-TYPE argument, which needs to be a character,
8151 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8152 precise meaning of each character:
8154 n Numerically, by converting the beginning of the entry/item to a number.
8155 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8156 t By date/time, either the first active time stamp in the entry, or, if
8157 none exist, by the first inactive one.
8158 s By the scheduled date/time.
8159 d By deadline date/time.
8160 c By creation time, which is assumed to be the first inactive time stamp
8161 at the beginning of a line.
8162 p By priority according to the cookie.
8163 r By the value of a property.
8165 Capital letters will reverse the sort order.
8167 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8168 called with point at the beginning of the record. It must return either
8169 a string or a number that should serve as the sorting key for that record.
8171 Comparing entries ignores case by default. However, with an optional argument
8172 WITH-CASE, the sorting considers case as well."
8173 (interactive "P")
8174 (let ((case-func (if with-case 'identity 'downcase))
8175 start beg end stars re re2
8176 txt what tmp)
8177 ;; Find beginning and end of region to sort
8178 (cond
8179 ((org-region-active-p)
8180 ;; we will sort the region
8181 (setq end (region-end)
8182 what "region")
8183 (goto-char (region-beginning))
8184 (if (not (org-at-heading-p)) (outline-next-heading))
8185 (setq start (point)))
8186 ((or (org-at-heading-p)
8187 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8188 ;; we will sort the children of the current headline
8189 (org-back-to-heading)
8190 (setq start (point)
8191 end (progn (org-end-of-subtree t t)
8192 (or (bolp) (insert "\n"))
8193 (org-back-over-empty-lines)
8194 (point))
8195 what "children")
8196 (goto-char start)
8197 (show-subtree)
8198 (outline-next-heading))
8200 ;; we will sort the top-level entries in this file
8201 (goto-char (point-min))
8202 (or (org-at-heading-p) (outline-next-heading))
8203 (setq start (point))
8204 (goto-char (point-max))
8205 (beginning-of-line 1)
8206 (when (looking-at ".*?\\S-")
8207 ;; File ends in a non-white line
8208 (end-of-line 1)
8209 (insert "\n"))
8210 (setq end (point-max))
8211 (setq what "top-level")
8212 (goto-char start)
8213 (show-all)))
8215 (setq beg (point))
8216 (if (>= beg end) (error "Nothing to sort"))
8218 (looking-at "\\(\\*+\\)")
8219 (setq stars (match-string 1)
8220 re (concat "^" (regexp-quote stars) " +")
8221 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8222 txt (buffer-substring beg end))
8223 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8224 (if (and (not (equal stars "*")) (string-match re2 txt))
8225 (error "Region to sort contains a level above the first entry"))
8227 (unless sorting-type
8228 (message
8229 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8230 [t]ime [s]cheduled [d]eadline [c]reated
8231 A/N/T/S/D/C/P/O/F means reversed:"
8232 what)
8233 (setq sorting-type (read-char-exclusive))
8235 (and (= (downcase sorting-type) ?f)
8236 (setq getkey-func
8237 (org-icompleting-read "Sort using function: "
8238 obarray 'fboundp t nil nil))
8239 (setq getkey-func (intern getkey-func)))
8241 (and (= (downcase sorting-type) ?r)
8242 (setq property
8243 (org-icompleting-read "Property: "
8244 (mapcar 'list (org-buffer-property-keys t))
8245 nil t))))
8247 (message "Sorting entries...")
8249 (save-restriction
8250 (narrow-to-region start end)
8251 (let ((dcst (downcase sorting-type))
8252 (case-fold-search nil)
8253 (now (current-time)))
8254 (sort-subr
8255 (/= dcst sorting-type)
8256 ;; This function moves to the beginning character of the "record" to
8257 ;; be sorted.
8258 (lambda nil
8259 (if (re-search-forward re nil t)
8260 (goto-char (match-beginning 0))
8261 (goto-char (point-max))))
8262 ;; This function moves to the last character of the "record" being
8263 ;; sorted.
8264 (lambda nil
8265 (save-match-data
8266 (condition-case nil
8267 (outline-forward-same-level 1)
8268 (error
8269 (goto-char (point-max))))))
8270 ;; This function returns the value that gets sorted against.
8271 (lambda nil
8272 (cond
8273 ((= dcst ?n)
8274 (if (looking-at org-complex-heading-regexp)
8275 (string-to-number (match-string 4))
8276 nil))
8277 ((= dcst ?a)
8278 (if (looking-at org-complex-heading-regexp)
8279 (funcall case-func (match-string 4))
8280 nil))
8281 ((= dcst ?t)
8282 (let ((end (save-excursion (outline-next-heading) (point))))
8283 (if (or (re-search-forward org-ts-regexp end t)
8284 (re-search-forward org-ts-regexp-both end t))
8285 (org-time-string-to-seconds (match-string 0))
8286 (org-float-time now))))
8287 ((= dcst ?c)
8288 (let ((end (save-excursion (outline-next-heading) (point))))
8289 (if (re-search-forward
8290 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8291 end t)
8292 (org-time-string-to-seconds (match-string 0))
8293 (org-float-time now))))
8294 ((= dcst ?s)
8295 (let ((end (save-excursion (outline-next-heading) (point))))
8296 (if (re-search-forward org-scheduled-time-regexp end t)
8297 (org-time-string-to-seconds (match-string 1))
8298 (org-float-time now))))
8299 ((= dcst ?d)
8300 (let ((end (save-excursion (outline-next-heading) (point))))
8301 (if (re-search-forward org-deadline-time-regexp end t)
8302 (org-time-string-to-seconds (match-string 1))
8303 (org-float-time now))))
8304 ((= dcst ?p)
8305 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8306 (string-to-char (match-string 2))
8307 org-default-priority))
8308 ((= dcst ?r)
8309 (or (org-entry-get nil property) ""))
8310 ((= dcst ?o)
8311 (if (looking-at org-complex-heading-regexp)
8312 (- 9999 (length (member (match-string 2)
8313 org-todo-keywords-1)))))
8314 ((= dcst ?f)
8315 (if getkey-func
8316 (progn
8317 (setq tmp (funcall getkey-func))
8318 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8319 tmp)
8320 (error "Invalid key function `%s'" getkey-func)))
8321 (t (error "Invalid sorting type `%c'" sorting-type))))
8323 (cond
8324 ((= dcst ?a) 'string<)
8325 ((= dcst ?f) compare-func)
8326 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8327 (t nil)))))
8328 (run-hooks 'org-after-sorting-entries-or-items-hook)
8329 (message "Sorting entries...done")))
8331 (defun org-do-sort (table what &optional with-case sorting-type)
8332 "Sort TABLE of WHAT according to SORTING-TYPE.
8333 The user will be prompted for the SORTING-TYPE if the call to this
8334 function does not specify it. WHAT is only for the prompt, to indicate
8335 what is being sorted. The sorting key will be extracted from
8336 the car of the elements of the table.
8337 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8338 (unless sorting-type
8339 (message
8340 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8341 what)
8342 (setq sorting-type (read-char-exclusive)))
8343 (let ((dcst (downcase sorting-type))
8344 extractfun comparefun)
8345 ;; Define the appropriate functions
8346 (cond
8347 ((= dcst ?n)
8348 (setq extractfun 'string-to-number
8349 comparefun (if (= dcst sorting-type) '< '>)))
8350 ((= dcst ?a)
8351 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8352 (lambda(x) (downcase (org-sort-remove-invisible x))))
8353 comparefun (if (= dcst sorting-type)
8354 'string<
8355 (lambda (a b) (and (not (string< a b))
8356 (not (string= a b)))))))
8357 ((= dcst ?t)
8358 (setq extractfun
8359 (lambda (x)
8360 (if (or (string-match org-ts-regexp x)
8361 (string-match org-ts-regexp-both x))
8362 (org-float-time
8363 (org-time-string-to-time (match-string 0 x)))
8365 comparefun (if (= dcst sorting-type) '< '>)))
8366 (t (error "Invalid sorting type `%c'" sorting-type)))
8368 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8369 table)
8370 (lambda (a b) (funcall comparefun (car a) (car b))))))
8373 ;;; The orgstruct minor mode
8375 ;; Define a minor mode which can be used in other modes in order to
8376 ;; integrate the org-mode structure editing commands.
8378 ;; This is really a hack, because the org-mode structure commands use
8379 ;; keys which normally belong to the major mode. Here is how it
8380 ;; works: The minor mode defines all the keys necessary to operate the
8381 ;; structure commands, but wraps the commands into a function which
8382 ;; tests if the cursor is currently at a headline or a plain list
8383 ;; item. If that is the case, the structure command is used,
8384 ;; temporarily setting many Org-mode variables like regular
8385 ;; expressions for filling etc. However, when any of those keys is
8386 ;; used at a different location, function uses `key-binding' to look
8387 ;; up if the key has an associated command in another currently active
8388 ;; keymap (minor modes, major mode, global), and executes that
8389 ;; command. There might be problems if any of the keys is otherwise
8390 ;; used as a prefix key.
8392 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8393 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8394 ;; addresses this by checking explicitly for both bindings.
8396 (defvar orgstruct-mode-map (make-sparse-keymap)
8397 "Keymap for the minor `orgstruct-mode'.")
8399 (defvar org-local-vars nil
8400 "List of local variables, for use by `orgstruct-mode'.")
8402 ;;;###autoload
8403 (define-minor-mode orgstruct-mode
8404 "Toggle the minor mode `orgstruct-mode'.
8405 This mode is for using Org-mode structure commands in other
8406 modes. The following keys behave as if Org-mode were active, if
8407 the cursor is on a headline, or on a plain list item (both as
8408 defined by Org-mode).
8410 M-up Move entry/item up
8411 M-down Move entry/item down
8412 M-left Promote
8413 M-right Demote
8414 M-S-up Move entry/item up
8415 M-S-down Move entry/item down
8416 M-S-left Promote subtree
8417 M-S-right Demote subtree
8418 M-q Fill paragraph and items like in Org-mode
8419 C-c ^ Sort entries
8420 C-c - Cycle list bullet
8421 TAB Cycle item visibility
8422 M-RET Insert new heading/item
8423 S-M-RET Insert new TODO heading / Checkbox item
8424 C-c C-c Set tags / toggle checkbox"
8425 nil " OrgStruct" nil
8426 (org-load-modules-maybe)
8427 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8429 ;;;###autoload
8430 (defun turn-on-orgstruct ()
8431 "Unconditionally turn on `orgstruct-mode'."
8432 (orgstruct-mode 1))
8434 (defvar org-fb-vars nil)
8435 (make-variable-buffer-local 'org-fb-vars)
8436 (defun orgstruct++-mode (&optional arg)
8437 "Toggle `orgstruct-mode', the enhanced version of it.
8438 In addition to setting orgstruct-mode, this also exports all
8439 indentation and autofilling variables from org-mode into the
8440 buffer. It will also recognize item context in multiline items."
8441 (interactive "P")
8442 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8443 (if (< arg 1)
8444 (progn (orgstruct-mode -1)
8445 (mapc (lambda(v)
8446 (org-set-local (car v)
8447 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8448 org-fb-vars))
8449 (orgstruct-mode 1)
8450 (setq org-fb-vars nil)
8451 (let (var val)
8452 (mapc
8453 (lambda (x)
8454 (when (string-match
8455 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8456 (symbol-name (car x)))
8457 (setq var (car x) val (nth 1 x))
8458 (push (list var `(quote ,(eval var))) org-fb-vars)
8459 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8460 org-local-vars)
8461 (org-set-local 'orgstruct-is-++ t))))
8463 (defvar orgstruct-is-++ nil
8464 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8465 (make-variable-buffer-local 'orgstruct-is-++)
8467 ;;;###autoload
8468 (defun turn-on-orgstruct++ ()
8469 "Unconditionally turn on `orgstruct++-mode'."
8470 (orgstruct++-mode 1))
8472 (defun orgstruct-error ()
8473 "Error when there is no default binding for a structure key."
8474 (interactive)
8475 (error "This key has no function outside structure elements"))
8477 (defun orgstruct-setup ()
8478 "Setup orgstruct keymaps."
8479 (let ((nfunc 0)
8480 (bindings
8481 (list
8482 '([(meta up)] org-metaup)
8483 '([(meta down)] org-metadown)
8484 '([(meta left)] org-metaleft)
8485 '([(meta right)] org-metaright)
8486 '([(meta shift up)] org-shiftmetaup)
8487 '([(meta shift down)] org-shiftmetadown)
8488 '([(meta shift left)] org-shiftmetaleft)
8489 '([(meta shift right)] org-shiftmetaright)
8490 '([?\e (up)] org-metaup)
8491 '([?\e (down)] org-metadown)
8492 '([?\e (left)] org-metaleft)
8493 '([?\e (right)] org-metaright)
8494 '([?\e (shift up)] org-shiftmetaup)
8495 '([?\e (shift down)] org-shiftmetadown)
8496 '([?\e (shift left)] org-shiftmetaleft)
8497 '([?\e (shift right)] org-shiftmetaright)
8498 '([(shift up)] org-shiftup)
8499 '([(shift down)] org-shiftdown)
8500 '([(shift left)] org-shiftleft)
8501 '([(shift right)] org-shiftright)
8502 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8503 '("\M-q" fill-paragraph)
8504 '("\C-c^" org-sort)
8505 '("\C-c-" org-cycle-list-bullet)))
8506 elt key fun cmd)
8507 (while (setq elt (pop bindings))
8508 (setq nfunc (1+ nfunc))
8509 (setq key (org-key (car elt))
8510 fun (nth 1 elt)
8511 cmd (orgstruct-make-binding fun nfunc key))
8512 (org-defkey orgstruct-mode-map key cmd))
8514 ;; Special treatment needed for TAB and RET
8515 (org-defkey orgstruct-mode-map [(tab)]
8516 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8517 (org-defkey orgstruct-mode-map "\C-i"
8518 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8520 (org-defkey orgstruct-mode-map "\M-\C-m"
8521 (orgstruct-make-binding 'org-insert-heading 105
8522 "\M-\C-m" [(meta return)]))
8523 (org-defkey orgstruct-mode-map [(meta return)]
8524 (orgstruct-make-binding 'org-insert-heading 106
8525 [(meta return)] "\M-\C-m"))
8527 (org-defkey orgstruct-mode-map [(shift meta return)]
8528 (orgstruct-make-binding 'org-insert-todo-heading 107
8529 [(meta return)] "\M-\C-m"))
8531 (org-defkey orgstruct-mode-map "\e\C-m"
8532 (orgstruct-make-binding 'org-insert-heading 108
8533 "\e\C-m" [?\e (return)]))
8534 (org-defkey orgstruct-mode-map [?\e (return)]
8535 (orgstruct-make-binding 'org-insert-heading 109
8536 [?\e (return)] "\e\C-m"))
8537 (org-defkey orgstruct-mode-map [?\e (shift return)]
8538 (orgstruct-make-binding 'org-insert-todo-heading 110
8539 [?\e (return)] "\e\C-m"))
8541 (unless org-local-vars
8542 (setq org-local-vars (org-get-local-variables)))
8546 (defun orgstruct-make-binding (fun n &rest keys)
8547 "Create a function for binding in the structure minor mode.
8548 FUN is the command to call inside a table. N is used to create a unique
8549 command name. KEYS are keys that should be checked in for a command
8550 to execute outside of tables."
8551 (eval
8552 (list 'defun
8553 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8554 '(arg)
8555 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8556 "Outside of structure, run the binding of `"
8557 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8558 "'.")
8559 '(interactive "p")
8560 (list 'if
8561 `(org-context-p 'headline 'item
8562 (and orgstruct-is-++
8563 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8564 'item-body))
8565 (list 'org-run-like-in-org-mode (list 'quote fun))
8566 (list 'let '(orgstruct-mode)
8567 (list 'call-interactively
8568 (append '(or)
8569 (mapcar (lambda (k)
8570 (list 'key-binding k))
8571 keys)
8572 '('orgstruct-error))))))))
8574 (defun org-context-p (&rest contexts)
8575 "Check if local context is any of CONTEXTS.
8576 Possible values in the list of contexts are `table', `headline', and `item'."
8577 (let ((pos (point)))
8578 (goto-char (point-at-bol))
8579 (prog1 (or (and (memq 'table contexts)
8580 (looking-at "[ \t]*|"))
8581 (and (memq 'headline contexts)
8582 (looking-at org-outline-regexp))
8583 (and (memq 'item contexts)
8584 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8585 (and (memq 'item-body contexts)
8586 (org-in-item-p)))
8587 (goto-char pos))))
8589 (defun org-get-local-variables ()
8590 "Return a list of all local variables in an Org mode buffer."
8591 (let (varlist)
8592 (with-current-buffer (get-buffer-create "*Org tmp*")
8593 (erase-buffer)
8594 (org-mode)
8595 (setq varlist (buffer-local-variables)))
8596 (kill-buffer "*Org tmp*")
8597 (delq nil
8598 (mapcar
8599 (lambda (x)
8600 (setq x
8601 (if (symbolp x)
8602 (list x)
8603 (list (car x) (list 'quote (cdr x)))))
8604 (if (string-match
8605 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8606 (symbol-name (car x)))
8607 x nil))
8608 varlist))))
8610 (defun org-clone-local-variables (from-buffer &optional regexp)
8611 "Clone local variables from FROM-BUFFER.
8612 Optional argument REGEXP selects variables to clone."
8613 (mapc
8614 (lambda (pair)
8615 (and (symbolp (car pair))
8616 (or (null regexp)
8617 (string-match regexp (symbol-name (car pair))))
8618 (set (make-local-variable (car pair))
8619 (cdr pair))))
8620 (buffer-local-variables from-buffer)))
8622 ;;;###autoload
8623 (defun org-run-like-in-org-mode (cmd)
8624 "Run a command, pretending that the current buffer is in Org-mode.
8625 This will temporarily bind local variables that are typically bound in
8626 Org-mode to the values they have in Org-mode, and then interactively
8627 call CMD."
8628 (org-load-modules-maybe)
8629 (unless org-local-vars
8630 (setq org-local-vars (org-get-local-variables)))
8631 (eval (list 'let org-local-vars
8632 (list 'call-interactively (list 'quote cmd)))))
8634 ;;;; Archiving
8636 (defun org-get-category (&optional pos force-refresh)
8637 "Get the category applying to position POS."
8638 (save-match-data
8639 (if force-refresh (org-refresh-category-properties))
8640 (let ((pos (or pos (point))))
8641 (or (get-text-property pos 'org-category)
8642 (progn (org-refresh-category-properties)
8643 (get-text-property pos 'org-category))))))
8645 (defun org-refresh-category-properties ()
8646 "Refresh category text properties in the buffer."
8647 (let ((inhibit-read-only t)
8648 (def-cat (cond
8649 ((null org-category)
8650 (if buffer-file-name
8651 (file-name-sans-extension
8652 (file-name-nondirectory buffer-file-name))
8653 "???"))
8654 ((symbolp org-category) (symbol-name org-category))
8655 (t org-category)))
8656 beg end cat pos optionp)
8657 (org-unmodified
8658 (save-excursion
8659 (save-restriction
8660 (widen)
8661 (goto-char (point-min))
8662 (put-text-property (point) (point-max) 'org-category def-cat)
8663 (while (re-search-forward
8664 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8665 (setq pos (match-end 0)
8666 optionp (equal (char-after (match-beginning 0)) ?#)
8667 cat (org-trim (match-string 2)))
8668 (if optionp
8669 (setq beg (point-at-bol) end (point-max))
8670 (org-back-to-heading t)
8671 (setq beg (point) end (org-end-of-subtree t t)))
8672 (put-text-property beg end 'org-category cat)
8673 (put-text-property beg end 'org-category-position beg)
8674 (goto-char pos)))))))
8677 ;;;; Link Stuff
8679 ;;; Link abbreviations
8681 (defun org-link-expand-abbrev (link)
8682 "Apply replacements as defined in `org-link-abbrev-alist'."
8683 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8684 (let* ((key (match-string 1 link))
8685 (as (or (assoc key org-link-abbrev-alist-local)
8686 (assoc key org-link-abbrev-alist)))
8687 (tag (and (match-end 2) (match-string 3 link)))
8688 rpl)
8689 (if (not as)
8690 link
8691 (setq rpl (cdr as))
8692 (cond
8693 ((symbolp rpl) (funcall rpl tag))
8694 ((string-match "%(\\([^)]+\\))" rpl)
8695 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8696 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8697 ((string-match "%h" rpl)
8698 (replace-match (url-hexify-string (or tag "")) t t rpl))
8699 (t (concat rpl tag)))))
8700 link))
8702 ;;; Storing and inserting links
8704 (defvar org-insert-link-history nil
8705 "Minibuffer history for links inserted with `org-insert-link'.")
8707 (defvar org-stored-links nil
8708 "Contains the links stored with `org-store-link'.")
8710 (defvar org-store-link-plist nil
8711 "Plist with info about the most recently link created with `org-store-link'.")
8713 (defvar org-link-protocols nil
8714 "Link protocols added to Org-mode using `org-add-link-type'.")
8716 (defvar org-store-link-functions nil
8717 "List of functions that are called to create and store a link.
8718 Each function will be called in turn until one returns a non-nil
8719 value. Each function should check if it is responsible for creating
8720 this link (for example by looking at the major mode).
8721 If not, it must exit and return nil.
8722 If yes, it should return a non-nil value after a calling
8723 `org-store-link-props' with a list of properties and values.
8724 Special properties are:
8726 :type The link prefix, like \"http\". This must be given.
8727 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8728 This is obligatory as well.
8729 :description Optional default description for the second pair
8730 of brackets in an Org-mode link. The user can still change
8731 this when inserting this link into an Org-mode buffer.
8733 In addition to these, any additional properties can be specified
8734 and then used in remember templates.")
8736 (defun org-add-link-type (type &optional follow export)
8737 "Add TYPE to the list of `org-link-types'.
8738 Re-compute all regular expressions depending on `org-link-types'
8740 FOLLOW and EXPORT are two functions.
8742 FOLLOW should take the link path as the single argument and do whatever
8743 is necessary to follow the link, for example find a file or display
8744 a mail message.
8746 EXPORT should format the link path for export to one of the export formats.
8747 It should be a function accepting three arguments:
8749 path the path of the link, the text after the prefix (like \"http:\")
8750 desc the description of the link, if any, or a description added by
8751 org-export-normalize-links if there is none
8752 format the export format, a symbol like `html' or `latex' or `ascii'..
8754 The function may use the FORMAT information to return different values
8755 depending on the format. The return value will be put literally into
8756 the exported file. If the return value is nil, this means Org should
8757 do what it normally does with links which do not have EXPORT defined.
8759 Org-mode has a built-in default for exporting links. If you are happy with
8760 this default, there is no need to define an export function for the link
8761 type. For a simple example of an export function, see `org-bbdb.el'."
8762 (add-to-list 'org-link-types type t)
8763 (org-make-link-regexps)
8764 (if (assoc type org-link-protocols)
8765 (setcdr (assoc type org-link-protocols) (list follow export))
8766 (push (list type follow export) org-link-protocols)))
8768 (defvar org-agenda-buffer-name)
8770 ;;;###autoload
8771 (defun org-store-link (arg)
8772 "\\<org-mode-map>Store an org-link to the current location.
8773 This link is added to `org-stored-links' and can later be inserted
8774 into an org-buffer with \\[org-insert-link].
8776 For some link types, a prefix arg is interpreted:
8777 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8778 For file links, arg negates `org-context-in-file-links'."
8779 (interactive "P")
8780 (org-load-modules-maybe)
8781 (setq org-store-link-plist nil) ; reset
8782 (org-with-limited-levels
8783 (let (link cpltxt desc description search txt custom-id agenda-link)
8784 (cond
8786 ((run-hook-with-args-until-success 'org-store-link-functions)
8787 (setq link (plist-get org-store-link-plist :link)
8788 desc (or (plist-get org-store-link-plist :description) link)))
8790 ((org-src-edit-buffer-p)
8791 (let (label gc)
8792 (while (or (not label)
8793 (save-excursion
8794 (save-restriction
8795 (widen)
8796 (goto-char (point-min))
8797 (re-search-forward
8798 (regexp-quote (format org-coderef-label-format label))
8799 nil t))))
8800 (when label (message "Label exists already") (sit-for 2))
8801 (setq label (read-string "Code line label: " label)))
8802 (end-of-line 1)
8803 (setq link (format org-coderef-label-format label))
8804 (setq gc (- 79 (length link)))
8805 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8806 (insert link)
8807 (setq link (concat "(" label ")") desc nil)))
8809 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8810 ;; We are in the agenda, link to referenced location
8811 (let ((m (or (get-text-property (point) 'org-hd-marker)
8812 (get-text-property (point) 'org-marker))))
8813 (when m
8814 (org-with-point-at m
8815 (setq agenda-link
8816 (if (org-called-interactively-p 'any)
8817 (call-interactively 'org-store-link)
8818 (org-store-link nil)))))))
8820 ((eq major-mode 'calendar-mode)
8821 (let ((cd (calendar-cursor-to-date)))
8822 (setq link
8823 (format-time-string
8824 (car org-time-stamp-formats)
8825 (apply 'encode-time
8826 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8827 nil nil nil))))
8828 (org-store-link-props :type "calendar" :date cd)))
8830 ((eq major-mode 'w3-mode)
8831 (setq cpltxt (if (and (buffer-name)
8832 (not (string-match "Untitled" (buffer-name))))
8833 (buffer-name)
8834 (url-view-url t))
8835 link (org-make-link (url-view-url t)))
8836 (org-store-link-props :type "w3" :url (url-view-url t)))
8838 ((eq major-mode 'w3m-mode)
8839 (setq cpltxt (or w3m-current-title w3m-current-url)
8840 link (org-make-link w3m-current-url))
8841 (org-store-link-props :type "w3m" :url (url-view-url t)))
8843 ((setq search (run-hook-with-args-until-success
8844 'org-create-file-search-functions))
8845 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8846 "::" search))
8847 (setq cpltxt (or description link)))
8849 ((eq major-mode 'image-mode)
8850 (setq cpltxt (concat "file:"
8851 (abbreviate-file-name buffer-file-name))
8852 link (org-make-link cpltxt))
8853 (org-store-link-props :type "image" :file buffer-file-name))
8855 ((eq major-mode 'dired-mode)
8856 ;; link to the file in the current line
8857 (let ((file (dired-get-filename nil t)))
8858 (setq file (if file
8859 (abbreviate-file-name
8860 (expand-file-name (dired-get-filename nil t)))
8861 ;; otherwise, no file so use current directory.
8862 default-directory))
8863 (setq cpltxt (concat "file:" file)
8864 link (org-make-link cpltxt))))
8866 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8867 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8868 (cond
8869 ((org-in-regexp "<<\\(.*?\\)>>")
8870 (setq cpltxt
8871 (concat "file:"
8872 (abbreviate-file-name
8873 (buffer-file-name (buffer-base-buffer)))
8874 "::" (match-string 1))
8875 link (org-make-link cpltxt)))
8876 ((and (featurep 'org-id)
8877 (or (eq org-link-to-org-use-id t)
8878 (and (eq org-link-to-org-use-id 'create-if-interactive)
8879 (org-called-interactively-p 'any))
8880 (and (eq org-link-to-org-use-id
8881 'create-if-interactive-and-no-custom-id)
8882 (org-called-interactively-p 'any)
8883 (not custom-id))
8884 (and org-link-to-org-use-id
8885 (org-entry-get nil "ID"))))
8886 ;; We can make a link using the ID.
8887 (setq link (condition-case nil
8888 (prog1 (org-id-store-link)
8889 (setq desc (plist-get org-store-link-plist
8890 :description)))
8891 (error
8892 ;; probably before first headline, link to file only
8893 (concat "file:"
8894 (abbreviate-file-name
8895 (buffer-file-name (buffer-base-buffer))))))))
8897 ;; Just link to current headline
8898 (setq cpltxt (concat "file:"
8899 (abbreviate-file-name
8900 (buffer-file-name (buffer-base-buffer)))))
8901 ;; Add a context search string
8902 (when (org-xor org-context-in-file-links arg)
8903 (setq txt (cond
8904 ((org-at-heading-p) nil)
8905 ((org-region-active-p)
8906 (buffer-substring (region-beginning) (region-end)))
8907 (t nil)))
8908 (when (or (null txt) (string-match "\\S-" txt))
8909 (setq cpltxt
8910 (concat cpltxt "::"
8911 (condition-case nil
8912 (org-make-org-heading-search-string txt)
8913 (error "")))
8914 desc (or (nth 4 (ignore-errors
8915 (org-heading-components))) "NONE"))))
8916 (if (string-match "::\\'" cpltxt)
8917 (setq cpltxt (substring cpltxt 0 -2)))
8918 (setq link (org-make-link cpltxt)))))
8920 ((buffer-file-name (buffer-base-buffer))
8921 ;; Just link to this file here.
8922 (setq cpltxt (concat "file:"
8923 (abbreviate-file-name
8924 (buffer-file-name (buffer-base-buffer)))))
8925 ;; Add a context string
8926 (when (org-xor org-context-in-file-links arg)
8927 (setq txt (if (org-region-active-p)
8928 (buffer-substring (region-beginning) (region-end))
8929 (buffer-substring (point-at-bol) (point-at-eol))))
8930 ;; Only use search option if there is some text.
8931 (when (string-match "\\S-" txt)
8932 (setq cpltxt
8933 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8934 desc "NONE")))
8935 (setq link (org-make-link cpltxt)))
8937 ((org-called-interactively-p 'interactive)
8938 (error "Cannot link to a buffer which is not visiting a file"))
8940 (t (setq link nil)))
8942 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8943 (setq link (or link cpltxt)
8944 desc (or desc cpltxt))
8945 (if (equal desc "NONE") (setq desc nil))
8947 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8948 (progn
8949 (setq org-stored-links
8950 (cons (list link desc) org-stored-links))
8951 (message "Stored: %s" (or desc link))
8952 (when custom-id
8953 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8954 "::#" custom-id))
8955 (setq org-stored-links
8956 (cons (list link desc) org-stored-links))))
8957 (or agenda-link (and link (org-make-link-string link desc)))))))
8959 (defun org-store-link-props (&rest plist)
8960 "Store link properties, extract names and addresses."
8961 (let (x adr)
8962 (when (setq x (plist-get plist :from))
8963 (setq adr (mail-extract-address-components x))
8964 (setq plist (plist-put plist :fromname (car adr)))
8965 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8966 (when (setq x (plist-get plist :to))
8967 (setq adr (mail-extract-address-components x))
8968 (setq plist (plist-put plist :toname (car adr)))
8969 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8970 (let ((from (plist-get plist :from))
8971 (to (plist-get plist :to)))
8972 (when (and from to org-from-is-user-regexp)
8973 (setq plist
8974 (plist-put plist :fromto
8975 (if (string-match org-from-is-user-regexp from)
8976 (concat "to %t")
8977 (concat "from %f"))))))
8978 (setq org-store-link-plist plist))
8980 (defun org-add-link-props (&rest plist)
8981 "Add these properties to the link property list."
8982 (let (key value)
8983 (while plist
8984 (setq key (pop plist) value (pop plist))
8985 (setq org-store-link-plist
8986 (plist-put org-store-link-plist key value)))))
8988 (defun org-email-link-description (&optional fmt)
8989 "Return the description part of an email link.
8990 This takes information from `org-store-link-plist' and formats it
8991 according to FMT (default from `org-email-link-description-format')."
8992 (setq fmt (or fmt org-email-link-description-format))
8993 (let* ((p org-store-link-plist)
8994 (to (plist-get p :toaddress))
8995 (from (plist-get p :fromaddress))
8996 (table
8997 (list
8998 (cons "%c" (plist-get p :fromto))
8999 (cons "%F" (plist-get p :from))
9000 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9001 (cons "%T" (plist-get p :to))
9002 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9003 (cons "%s" (plist-get p :subject))
9004 (cons "%d" (plist-get p :date))
9005 (cons "%m" (plist-get p :message-id)))))
9006 (when (string-match "%c" fmt)
9007 ;; Check if the user wrote this message
9008 (if (and org-from-is-user-regexp from to
9009 (save-match-data (string-match org-from-is-user-regexp from)))
9010 (setq fmt (replace-match "to %t" t t fmt))
9011 (setq fmt (replace-match "from %f" t t fmt))))
9012 (org-replace-escapes fmt table)))
9014 (defun org-make-org-heading-search-string (&optional string heading)
9015 "Make search string for STRING or current headline."
9016 (interactive)
9017 (let ((s (or string (org-get-heading)))
9018 (lines org-context-in-file-links))
9019 (unless (and string (not heading))
9020 ;; We are using a headline, clean up garbage in there.
9021 (if (string-match org-todo-regexp s)
9022 (setq s (replace-match "" t t s)))
9023 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9024 (setq s (replace-match "" t t s)))
9025 (setq s (org-trim s))
9026 (if (string-match (concat "^\\(" org-quote-string "\\|"
9027 org-comment-string "\\)") s)
9028 (setq s (replace-match "" t t s)))
9029 (while (string-match org-ts-regexp s)
9030 (setq s (replace-match "" t t s))))
9031 (or string (setq s (concat "*" s))) ; Add * for headlines
9032 (when (and string (integerp lines) (> lines 0))
9033 (let ((slines (org-split-string s "\n")))
9034 (when (< lines (length slines))
9035 (setq s (mapconcat
9036 'identity
9037 (reverse (nthcdr (- (length slines) lines)
9038 (reverse slines))) "\n")))))
9039 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9041 (defun org-make-link (&rest strings)
9042 "Concatenate STRINGS."
9043 (apply 'concat strings))
9045 (defun org-make-link-string (link &optional description)
9046 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9047 (unless (string-match "\\S-" link)
9048 (error "Empty link"))
9049 (when (and description
9050 (stringp description)
9051 (not (string-match "\\S-" description)))
9052 (setq description nil))
9053 (when (stringp description)
9054 ;; Remove brackets from the description, they are fatal.
9055 (while (string-match "\\[" description)
9056 (setq description (replace-match "{" t t description)))
9057 (while (string-match "\\]" description)
9058 (setq description (replace-match "}" t t description))))
9059 (when (equal link description)
9060 ;; No description needed, it is identical
9061 (setq description nil))
9062 (when (and (not description)
9063 (not (string-match (org-image-file-name-regexp) link))
9064 (not (equal link (org-link-escape link))))
9065 (setq description (org-extract-attributes link)))
9066 (setq link
9067 (cond ((string-match (org-image-file-name-regexp) link) link)
9068 ((string-match org-link-types-re link)
9069 (concat (match-string 1 link)
9070 (org-link-escape (substring link (match-end 1)))))
9071 (t (org-link-escape link))))
9072 (concat "[[" link "]"
9073 (if description (concat "[" description "]") "")
9074 "]"))
9076 (defconst org-link-escape-chars
9077 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9078 "List of characters that should be escaped in link.
9079 This is the list that is used for internal purposes.")
9081 (defvar org-url-encoding-use-url-hexify nil)
9083 (defconst org-link-escape-chars-browser
9084 '(?\ )
9085 "List of escapes for characters that are problematic in links.
9086 This is the list that is used before handing over to the browser.")
9088 (defun org-link-escape (text &optional table merge)
9089 "Return percent escaped representation of TEXT.
9090 TEXT is a string with the text to escape.
9091 Optional argument TABLE is a list with characters that should be
9092 escaped. When nil, `org-link-escape-chars' is used.
9093 If optional argument MERGE is set, merge TABLE into
9094 `org-link-escape-chars'."
9095 (if (and org-url-encoding-use-url-hexify (not table))
9096 (url-hexify-string text)
9097 (cond
9098 ((and table merge)
9099 (mapc (lambda (defchr)
9100 (unless (member defchr table)
9101 (setq table (cons defchr table)))) org-link-escape-chars))
9102 ((null table)
9103 (setq table org-link-escape-chars)))
9104 (mapconcat
9105 (lambda (char)
9106 (if (or (member char table)
9107 (< char 32) (= char 37) (> char 126))
9108 (mapconcat (lambda (sequence-element)
9109 (format "%%%.2X" sequence-element))
9110 (or (encode-coding-char char 'utf-8)
9111 (error "Unable to percent escape character: %s"
9112 (char-to-string char))) "")
9113 (char-to-string char))) text "")))
9115 (defun org-link-unescape (str)
9116 "Unhex hexified Unicode strings as returned from the JavaScript function
9117 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9118 (unless (and (null str) (string= "" str))
9119 (let ((pos 0) (case-fold-search t) unhexed)
9120 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9121 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9122 (setq str (replace-match unhexed t t str))
9123 (setq pos (+ pos (length unhexed))))))
9124 str)
9126 (defun org-link-unescape-compound (hex)
9127 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9128 Note: this function also decodes single byte encodings like
9129 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9130 (save-match-data
9131 (let* ((bytes (cdr (split-string hex "%")))
9132 (ret "")
9133 (eat 0)
9134 (sum 0))
9135 (while bytes
9136 (let* ((val (string-to-number (pop bytes) 16))
9137 (shift-xor
9138 (if (= 0 eat)
9139 (cond
9140 ((>= val 252) (cons 6 252))
9141 ((>= val 248) (cons 5 248))
9142 ((>= val 240) (cons 4 240))
9143 ((>= val 224) (cons 3 224))
9144 ((>= val 192) (cons 2 192))
9145 (t (cons 0 0)))
9146 (cons 6 128))))
9147 (if (>= val 192) (setq eat (car shift-xor)))
9148 (setq val (logxor val (cdr shift-xor)))
9149 (setq sum (+ (lsh sum (car shift-xor)) val))
9150 (if (> eat 0) (setq eat (- eat 1)))
9151 (cond
9152 ((= 0 eat) ;multi byte
9153 (setq ret (concat ret (org-char-to-string sum)))
9154 (setq sum 0))
9155 ((not bytes) ; single byte(s)
9156 (setq ret (org-link-unescape-single-byte-sequence hex))))
9157 )) ;; end (while bytes
9158 ret )))
9160 (defun org-link-unescape-single-byte-sequence (hex)
9161 "Unhexify hex-encoded single byte character sequences."
9162 (mapconcat (lambda (byte)
9163 (char-to-string (string-to-number byte 16)))
9164 (cdr (split-string hex "%")) ""))
9166 (defun org-xor (a b)
9167 "Exclusive or."
9168 (if a (not b) b))
9170 (defun org-fixup-message-id-for-http (s)
9171 "Replace special characters in a message id, so it can be used in an http query."
9172 (when (string-match "%" s)
9173 (setq s (mapconcat (lambda (c)
9174 (if (eq c ?%)
9175 "%25"
9176 (char-to-string c)))
9177 s "")))
9178 (while (string-match "<" s)
9179 (setq s (replace-match "%3C" t t s)))
9180 (while (string-match ">" s)
9181 (setq s (replace-match "%3E" t t s)))
9182 (while (string-match "@" s)
9183 (setq s (replace-match "%40" t t s)))
9186 (defun org-link-prettify (link)
9187 "Return a human-readable representation of LINK.
9188 The car of LINK must be a raw link the cdr of LINK must be either
9189 a link description or nil."
9190 (let ((desc (or (cadr link) "<no description>")))
9191 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9192 "[[" (car link) "]]")))
9194 ;;;###autoload
9195 (defun org-insert-link-global ()
9196 "Insert a link like Org-mode does.
9197 This command can be called in any mode to insert a link in Org-mode syntax."
9198 (interactive)
9199 (org-load-modules-maybe)
9200 (org-run-like-in-org-mode 'org-insert-link))
9202 (defun org-insert-all-links (&optional keep)
9203 "Insert all links in `org-stored-links'."
9204 (interactive "P")
9205 (let ((links (copy-sequence org-stored-links)) l)
9206 (while (setq l (if keep (pop links) (pop org-stored-links)))
9207 (insert "- ")
9208 (org-insert-link nil (car l) (cadr l))
9209 (insert "\n"))))
9211 (defun org-insert-link (&optional complete-file link-location default-description)
9212 "Insert a link. At the prompt, enter the link.
9214 Completion can be used to insert any of the link protocol prefixes like
9215 http or ftp in use.
9217 The history can be used to select a link previously stored with
9218 `org-store-link'. When the empty string is entered (i.e. if you just
9219 press RET at the prompt), the link defaults to the most recently
9220 stored link. As SPC triggers completion in the minibuffer, you need to
9221 use M-SPC or C-q SPC to force the insertion of a space character.
9223 You will also be prompted for a description, and if one is given, it will
9224 be displayed in the buffer instead of the link.
9226 If there is already a link at point, this command will allow you to edit link
9227 and description parts.
9229 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9230 be selected using completion. The path to the file will be relative to the
9231 current directory if the file is in the current directory or a subdirectory.
9232 Otherwise, the link will be the absolute path as completed in the minibuffer
9233 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9234 option `org-link-file-path-type'.
9236 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9237 the current directory or below.
9239 With three \\[universal-argument] prefixes, negate the meaning of
9240 `org-keep-stored-link-after-insertion'.
9242 If `org-make-link-description-function' is non-nil, this function will be
9243 called with the link target, and the result will be the default
9244 link description.
9246 If the LINK-LOCATION parameter is non-nil, this value will be
9247 used as the link location instead of reading one interactively.
9249 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9250 be used as the default description."
9251 (interactive "P")
9252 (let* ((wcf (current-window-configuration))
9253 (region (if (org-region-active-p)
9254 (buffer-substring (region-beginning) (region-end))))
9255 (remove (and region (list (region-beginning) (region-end))))
9256 (desc region)
9257 tmphist ; byte-compile incorrectly complains about this
9258 (link link-location)
9259 entry file all-prefixes)
9260 (cond
9261 (link-location) ; specified by arg, just use it.
9262 ((org-in-regexp org-bracket-link-regexp 1)
9263 ;; We do have a link at point, and we are going to edit it.
9264 (setq remove (list (match-beginning 0) (match-end 0)))
9265 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9266 (setq link (read-string "Link: "
9267 (org-link-unescape
9268 (org-match-string-no-properties 1)))))
9269 ((or (org-in-regexp org-angle-link-re)
9270 (org-in-regexp org-plain-link-re))
9271 ;; Convert to bracket link
9272 (setq remove (list (match-beginning 0) (match-end 0))
9273 link (read-string "Link: "
9274 (org-remove-angle-brackets (match-string 0)))))
9275 ((member complete-file '((4) (16)))
9276 ;; Completing read for file names.
9277 (setq link (org-file-complete-link complete-file)))
9279 ;; Read link, with completion for stored links.
9280 (with-output-to-temp-buffer "*Org Links*"
9281 (princ "Insert a link.
9282 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9283 (when org-stored-links
9284 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9285 (princ (mapconcat 'org-link-prettify
9286 (reverse org-stored-links) "\n"))))
9287 (let ((cw (selected-window)))
9288 (select-window (get-buffer-window "*Org Links*" 'visible))
9289 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9290 (unless (pos-visible-in-window-p (point-max))
9291 (org-fit-window-to-buffer))
9292 (and (window-live-p cw) (select-window cw)))
9293 ;; Fake a link history, containing the stored links.
9294 (setq tmphist (append (mapcar 'car org-stored-links)
9295 org-insert-link-history))
9296 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9297 (mapcar 'car org-link-abbrev-alist)
9298 org-link-types))
9299 (unwind-protect
9300 (progn
9301 (setq link
9302 (let ((org-completion-use-ido nil)
9303 (org-completion-use-iswitchb nil))
9304 (org-completing-read
9305 "Link: "
9306 (append
9307 (mapcar (lambda (x) (list (concat x ":")))
9308 all-prefixes)
9309 (mapcar 'car org-stored-links))
9310 nil nil nil
9311 'tmphist
9312 (car (car org-stored-links)))))
9313 (if (not (string-match "\\S-" link))
9314 (error "No link selected"))
9315 (if (or (member link all-prefixes)
9316 (and (equal ":" (substring link -1))
9317 (member (substring link 0 -1) all-prefixes)
9318 (setq link (substring link 0 -1))))
9319 (setq link (org-link-try-special-completion link))))
9320 (set-window-configuration wcf)
9321 (kill-buffer "*Org Links*"))
9322 (setq entry (assoc link org-stored-links))
9323 (or entry (push link org-insert-link-history))
9324 (setq desc (or desc (nth 1 entry)))))
9326 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9327 (not org-keep-stored-link-after-insertion))
9328 (setq org-stored-links (delq (assoc link org-stored-links)
9329 org-stored-links)))
9331 (if (string-match org-plain-link-re link)
9332 ;; URL-like link, normalize the use of angular brackets.
9333 (setq link (org-make-link (org-remove-angle-brackets link))))
9335 ;; Check if we are linking to the current file with a search option
9336 ;; If yes, simplify the link by using only the search option.
9337 (when (and buffer-file-name
9338 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9339 (let* ((path (match-string 1 link))
9340 (case-fold-search nil)
9341 (search (match-string 2 link)))
9342 (save-match-data
9343 (if (equal (file-truename buffer-file-name) (file-truename path))
9344 ;; We are linking to this same file, with a search option
9345 (setq link search)))))
9347 ;; Check if we can/should use a relative path. If yes, simplify the link
9348 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9349 (let* ((type (match-string 1 link))
9350 (path (match-string 2 link))
9351 (origpath path)
9352 (case-fold-search nil))
9353 (cond
9354 ((or (eq org-link-file-path-type 'absolute)
9355 (equal complete-file '(16)))
9356 (setq path (abbreviate-file-name (expand-file-name path))))
9357 ((eq org-link-file-path-type 'noabbrev)
9358 (setq path (expand-file-name path)))
9359 ((eq org-link-file-path-type 'relative)
9360 (setq path (file-relative-name path)))
9362 (save-match-data
9363 (if (string-match (concat "^" (regexp-quote
9364 (expand-file-name
9365 (file-name-as-directory
9366 default-directory))))
9367 (expand-file-name path))
9368 ;; We are linking a file with relative path name.
9369 (setq path (substring (expand-file-name path)
9370 (match-end 0)))
9371 (setq path (abbreviate-file-name (expand-file-name path)))))))
9372 (setq link (concat type path))
9373 (if (equal desc origpath)
9374 (setq desc path))))
9376 (if org-make-link-description-function
9377 (setq desc (funcall org-make-link-description-function link desc))
9378 (if default-description (setq desc default-description)
9379 (setq desc (read-string "Description: " desc))))
9381 (unless (string-match "\\S-" desc) (setq desc nil))
9382 (if remove (apply 'delete-region remove))
9383 (insert (org-make-link-string link desc))))
9385 (defun org-link-try-special-completion (type)
9386 "If there is completion support for link type TYPE, offer it."
9387 (let ((fun (intern (concat "org-" type "-complete-link"))))
9388 (if (functionp fun)
9389 (funcall fun)
9390 (read-string "Link (no completion support): " (concat type ":")))))
9392 (defun org-file-complete-link (&optional arg)
9393 "Create a file link using completion."
9394 (let (file link)
9395 (setq file (read-file-name "File: "))
9396 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9397 (pwd1 (file-name-as-directory (abbreviate-file-name
9398 (expand-file-name ".")))))
9399 (cond
9400 ((equal arg '(16))
9401 (setq link (org-make-link
9402 "file:"
9403 (abbreviate-file-name (expand-file-name file)))))
9404 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9405 (setq link (org-make-link "file:" (match-string 1 file))))
9406 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9407 (expand-file-name file))
9408 (setq link (org-make-link
9409 "file:" (match-string 1 (expand-file-name file)))))
9410 (t (setq link (org-make-link "file:" file)))))
9411 link))
9413 (defun org-completing-read (&rest args)
9414 "Completing-read with SPACE being a normal character."
9415 (let ((enable-recursive-minibuffers t)
9416 (minibuffer-local-completion-map
9417 (copy-keymap minibuffer-local-completion-map)))
9418 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9419 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9420 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9421 (apply 'org-icompleting-read args)))
9423 (defun org-completing-read-no-i (&rest args)
9424 (let (org-completion-use-ido org-completion-use-iswitchb)
9425 (apply 'org-completing-read args)))
9427 (defun org-iswitchb-completing-read (prompt choices &rest args)
9428 "Use iswitch as a completing-read replacement to choose from choices.
9429 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9430 from."
9431 (let* ((iswitchb-use-virtual-buffers nil)
9432 (iswitchb-make-buflist-hook
9433 (lambda ()
9434 (setq iswitchb-temp-buflist choices))))
9435 (iswitchb-read-buffer prompt)))
9437 (defun org-icompleting-read (&rest args)
9438 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9439 (org-without-partial-completion
9440 (if (and org-completion-use-ido
9441 (fboundp 'ido-completing-read)
9442 (boundp 'ido-mode) ido-mode
9443 (listp (second args)))
9444 (let ((ido-enter-matching-directory nil))
9445 (apply 'ido-completing-read (concat (car args))
9446 (if (consp (car (nth 1 args)))
9447 (mapcar 'car (nth 1 args))
9448 (nth 1 args))
9449 (cddr args)))
9450 (if (and org-completion-use-iswitchb
9451 (boundp 'iswitchb-mode) iswitchb-mode
9452 (listp (second args)))
9453 (apply 'org-iswitchb-completing-read (concat (car args))
9454 (if (consp (car (nth 1 args)))
9455 (mapcar 'car (nth 1 args))
9456 (nth 1 args))
9457 (cddr args))
9458 (apply 'completing-read args)))))
9460 (defun org-extract-attributes (s)
9461 "Extract the attributes cookie from a string and set as text property."
9462 (let (a attr (start 0) key value)
9463 (save-match-data
9464 (when (string-match "{{\\([^}]+\\)}}$" s)
9465 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9466 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9467 (setq key (match-string 1 a) value (match-string 2 a)
9468 start (match-end 0)
9469 attr (plist-put attr (intern key) value))))
9470 (org-add-props s nil 'org-attr attr))
9473 (defun org-extract-attributes-from-string (tag)
9474 (let (key value attr)
9475 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9476 (setq key (match-string 1 tag) value (match-string 2 tag)
9477 tag (replace-match "" t t tag)
9478 attr (plist-put attr (intern key) value)))
9479 (cons tag attr)))
9481 (defun org-attributes-to-string (plist)
9482 "Format a property list into an HTML attribute list."
9483 (let ((s "") key value)
9484 (while plist
9485 (setq key (pop plist) value (pop plist))
9486 (and value
9487 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9490 ;;; Opening/following a link
9492 (defvar org-link-search-failed nil)
9494 (defvar org-open-link-functions nil
9495 "Hook for functions finding a plain text link.
9496 These functions must take a single argument, the link content.
9497 They will be called for links that look like [[link text][description]]
9498 when LINK TEXT does not have a protocol like \"http:\" and does not look
9499 like a filename (e.g. \"./blue.png\").
9501 These functions will be called *before* Org attempts to resolve the
9502 link by doing text searches in the current buffer - so if you want a
9503 link \"[[target]]\" to still find \"<<target>>\", your function should
9504 handle this as a special case.
9506 When the function does handle the link, it must return a non-nil value.
9507 If it decides that it is not responsible for this link, it must return
9508 nil to indicate that that Org-mode can continue with other options
9509 like exact and fuzzy text search.")
9511 (defun org-next-link ()
9512 "Move forward to the next link.
9513 If the link is in hidden text, expose it."
9514 (interactive)
9515 (when (and org-link-search-failed (eq this-command last-command))
9516 (goto-char (point-min))
9517 (message "Link search wrapped back to beginning of buffer"))
9518 (setq org-link-search-failed nil)
9519 (let* ((pos (point))
9520 (ct (org-context))
9521 (a (assoc :link ct)))
9522 (if a (goto-char (nth 2 a)))
9523 (if (re-search-forward org-any-link-re nil t)
9524 (progn
9525 (goto-char (match-beginning 0))
9526 (if (outline-invisible-p) (org-show-context)))
9527 (goto-char pos)
9528 (setq org-link-search-failed t)
9529 (error "No further link found"))))
9531 (defun org-previous-link ()
9532 "Move backward to the previous link.
9533 If the link is in hidden text, expose it."
9534 (interactive)
9535 (when (and org-link-search-failed (eq this-command last-command))
9536 (goto-char (point-max))
9537 (message "Link search wrapped back to end of buffer"))
9538 (setq org-link-search-failed nil)
9539 (let* ((pos (point))
9540 (ct (org-context))
9541 (a (assoc :link ct)))
9542 (if a (goto-char (nth 1 a)))
9543 (if (re-search-backward org-any-link-re nil t)
9544 (progn
9545 (goto-char (match-beginning 0))
9546 (if (outline-invisible-p) (org-show-context)))
9547 (goto-char pos)
9548 (setq org-link-search-failed t)
9549 (error "No further link found"))))
9551 (defun org-translate-link (s)
9552 "Translate a link string if a translation function has been defined."
9553 (if (and org-link-translation-function
9554 (fboundp org-link-translation-function)
9555 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9556 (progn
9557 (setq s (funcall org-link-translation-function
9558 (match-string 1 s) (match-string 2 s)))
9559 (concat (car s) ":" (cdr s)))
9562 (defun org-translate-link-from-planner (type path)
9563 "Translate a link from Emacs Planner syntax so that Org can follow it.
9564 This is still an experimental function, your mileage may vary."
9565 (cond
9566 ((member type '("http" "https" "news" "ftp"))
9567 ;; standard Internet links are the same.
9568 nil)
9569 ((and (equal type "irc") (string-match "^//" path))
9570 ;; Planner has two / at the beginning of an irc link, we have 1.
9571 ;; We should have zero, actually....
9572 (setq path (substring path 1)))
9573 ((and (equal type "lisp") (string-match "^/" path))
9574 ;; Planner has a slash, we do not.
9575 (setq type "elisp" path (substring path 1)))
9576 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9577 ;; A typical message link. Planner has the id after the final slash,
9578 ;; we separate it with a hash mark
9579 (setq path (concat (match-string 1 path) "#"
9580 (org-remove-angle-brackets (match-string 2 path)))))
9582 (cons type path))
9584 (defun org-find-file-at-mouse (ev)
9585 "Open file link or URL at mouse."
9586 (interactive "e")
9587 (mouse-set-point ev)
9588 (org-open-at-point 'in-emacs))
9590 (defun org-open-at-mouse (ev)
9591 "Open file link or URL at mouse.
9592 See the docstring of `org-open-file' for details."
9593 (interactive "e")
9594 (mouse-set-point ev)
9595 (if (eq major-mode 'org-agenda-mode)
9596 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9597 (org-open-at-point))
9599 (defvar org-window-config-before-follow-link nil
9600 "The window configuration before following a link.
9601 This is saved in case the need arises to restore it.")
9603 (defvar org-open-link-marker (make-marker)
9604 "Marker pointing to the location where `org-open-at-point; was called.")
9606 ;;;###autoload
9607 (defun org-open-at-point-global ()
9608 "Follow a link like Org-mode does.
9609 This command can be called in any mode to follow a link that has
9610 Org-mode syntax."
9611 (interactive)
9612 (org-run-like-in-org-mode 'org-open-at-point))
9614 ;;;###autoload
9615 (defun org-open-link-from-string (s &optional arg reference-buffer)
9616 "Open a link in the string S, as if it was in Org-mode."
9617 (interactive "sLink: \nP")
9618 (let ((reference-buffer (or reference-buffer (current-buffer))))
9619 (with-temp-buffer
9620 (let ((org-inhibit-startup (not reference-buffer)))
9621 (org-mode)
9622 (insert s)
9623 (goto-char (point-min))
9624 (when reference-buffer
9625 (setq org-link-abbrev-alist-local
9626 (with-current-buffer reference-buffer
9627 org-link-abbrev-alist-local)))
9628 (org-open-at-point arg reference-buffer)))))
9630 (defvar org-open-at-point-functions nil
9631 "Hook that is run when following a link at point.
9633 Functions in this hook must return t if they identify and follow
9634 a link at point. If they don't find anything interesting at point,
9635 they must return nil.")
9637 (defun org-open-at-point (&optional arg reference-buffer)
9638 "Open link at or after point.
9639 If there is no link at point, this function will search forward up to
9640 the end of the current line.
9641 Normally, files will be opened by an appropriate application. If the
9642 optional prefix argument ARG is non-nil, Emacs will visit the file.
9643 With a double prefix argument, try to open outside of Emacs, in the
9644 application the system uses for this file type."
9645 (interactive "P")
9646 ;; if in a code block, then open the block's results
9647 (unless (call-interactively #'org-babel-open-src-block-result)
9648 (org-load-modules-maybe)
9649 (move-marker org-open-link-marker (point))
9650 (setq org-window-config-before-follow-link (current-window-configuration))
9651 (org-remove-occur-highlights nil nil t)
9652 (cond
9653 ((and (org-at-heading-p)
9654 (not (org-at-timestamp-p t))
9655 (not (org-in-regexp
9656 (concat org-plain-link-re "\\|"
9657 org-bracket-link-regexp "\\|"
9658 org-angle-link-re "\\|"
9659 "[ \t]:[^ \t\n]+:[ \t]*$")))
9660 (not (get-text-property (point) 'org-linked-text)))
9661 (or (org-offer-links-in-entry arg)
9662 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9663 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9664 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9665 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9666 (not (org-in-regexp org-bracket-link-regexp)))
9667 (org-footnote-action))
9669 (let (type path link line search (pos (point)))
9670 (catch 'match
9671 (save-excursion
9672 (skip-chars-forward "^]\n\r")
9673 (when (org-in-regexp org-bracket-link-regexp 1)
9674 (setq link (org-extract-attributes
9675 (org-link-unescape (org-match-string-no-properties 1))))
9676 (while (string-match " *\n *" link)
9677 (setq link (replace-match " " t t link)))
9678 (setq link (org-link-expand-abbrev link))
9679 (cond
9680 ((or (file-name-absolute-p link)
9681 (string-match "^\\.\\.?/" link))
9682 (setq type "file" path link))
9683 ((string-match org-link-re-with-space3 link)
9684 (setq type (match-string 1 link) path (match-string 2 link)))
9685 (t (setq type "thisfile" path link)))
9686 (throw 'match t)))
9688 (when (get-text-property (point) 'org-linked-text)
9689 (setq type "thisfile"
9690 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9691 (1+ (point)) (point))
9692 path (buffer-substring
9693 (or (previous-single-property-change pos 'org-linked-text)
9694 (point-min))
9695 (or (next-single-property-change pos 'org-linked-text)
9696 (point-max))))
9697 (throw 'match t))
9699 (save-excursion
9700 (when (or (org-in-regexp org-angle-link-re)
9701 (org-in-regexp org-plain-link-re))
9702 (setq type (match-string 1)
9703 path (org-link-unescape (match-string 2)))
9704 (throw 'match t)))
9705 (save-excursion
9706 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9707 (setq type "tags"
9708 path (match-string 1))
9709 (while (string-match ":" path)
9710 (setq path (replace-match "+" t t path)))
9711 (throw 'match t)))
9712 (when (org-in-regexp "<\\([^><\n]+\\)>")
9713 (setq type "tree-match"
9714 path (match-string 1))
9715 (throw 'match t)))
9716 (unless path
9717 (error "No link found"))
9719 ;; switch back to reference buffer
9720 ;; needed when if called in a temporary buffer through
9721 ;; org-open-link-from-string
9722 (with-current-buffer (or reference-buffer (current-buffer))
9724 ;; Remove any trailing spaces in path
9725 (if (string-match " +\\'" path)
9726 (setq path (replace-match "" t t path)))
9727 (if (and org-link-translation-function
9728 (fboundp org-link-translation-function))
9729 ;; Check if we need to translate the link
9730 (let ((tmp (funcall org-link-translation-function type path)))
9731 (setq type (car tmp) path (cdr tmp))))
9733 (cond
9735 ((assoc type org-link-protocols)
9736 (funcall (nth 1 (assoc type org-link-protocols)) path))
9738 ((equal type "mailto")
9739 (let ((cmd (car org-link-mailto-program))
9740 (args (cdr org-link-mailto-program)) args1
9741 (address path) (subject "") a)
9742 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9743 (setq address (match-string 1 path)
9744 subject (org-link-escape (match-string 2 path))))
9745 (while args
9746 (cond
9747 ((not (stringp (car args))) (push (pop args) args1))
9748 (t (setq a (pop args))
9749 (if (string-match "%a" a)
9750 (setq a (replace-match address t t a)))
9751 (if (string-match "%s" a)
9752 (setq a (replace-match subject t t a)))
9753 (push a args1))))
9754 (apply cmd (nreverse args1))))
9756 ((member type '("http" "https" "ftp" "news"))
9757 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9758 (org-link-escape
9759 path org-link-escape-chars-browser)
9760 path))))
9762 ((string= type "doi")
9763 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9764 (org-link-escape
9765 path org-link-escape-chars-browser)
9766 path))))
9768 ((member type '("message"))
9769 (browse-url (concat type ":" path)))
9771 ((string= type "tags")
9772 (org-tags-view arg path))
9774 ((string= type "tree-match")
9775 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9777 ((string= type "file")
9778 (if (string-match "::\\([0-9]+\\)\\'" path)
9779 (setq line (string-to-number (match-string 1 path))
9780 path (substring path 0 (match-beginning 0)))
9781 (if (string-match "::\\(.+\\)\\'" path)
9782 (setq search (match-string 1 path)
9783 path (substring path 0 (match-beginning 0)))))
9784 (if (string-match "[*?{]" (file-name-nondirectory path))
9785 (dired path)
9786 (org-open-file path arg line search)))
9788 ((string= type "shell")
9789 (let ((cmd path))
9790 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9791 (string-match org-confirm-shell-link-not-regexp cmd))
9792 (not org-confirm-shell-link-function)
9793 (funcall org-confirm-shell-link-function
9794 (format "Execute \"%s\" in shell? "
9795 (org-add-props cmd nil
9796 'face 'org-warning))))
9797 (progn
9798 (message "Executing %s" cmd)
9799 (shell-command cmd))
9800 (error "Abort"))))
9802 ((string= type "elisp")
9803 (let ((cmd path))
9804 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9805 (string-match org-confirm-elisp-link-not-regexp cmd))
9806 (not org-confirm-elisp-link-function)
9807 (funcall org-confirm-elisp-link-function
9808 (format "Execute \"%s\" as elisp? "
9809 (org-add-props cmd nil
9810 'face 'org-warning))))
9811 (message "%s => %s" cmd
9812 (if (equal (string-to-char cmd) ?\()
9813 (eval (read cmd))
9814 (call-interactively (read cmd))))
9815 (error "Abort"))))
9817 ((and (string= type "thisfile")
9818 (run-hook-with-args-until-success
9819 'org-open-link-functions path)))
9821 ((string= type "thisfile")
9822 (if arg
9823 (switch-to-buffer-other-window
9824 (org-get-buffer-for-internal-link (current-buffer)))
9825 (org-mark-ring-push))
9826 (let ((cmd `(org-link-search
9827 ,path
9828 ,(cond ((equal arg '(4)) ''occur)
9829 ((equal arg '(16)) ''org-occur)
9830 (t nil))
9831 ,pos)))
9832 (condition-case nil (let ((org-link-search-inhibit-query t))
9833 (eval cmd))
9834 (error (progn (widen) (eval cmd))))))
9837 (browse-url-at-point)))))))
9838 (move-marker org-open-link-marker nil)
9839 (run-hook-with-args 'org-follow-link-hook)))
9841 (defun org-offer-links-in-entry (&optional nth zero)
9842 "Offer links in the current entry and follow the selected link.
9843 If there is only one link, follow it immediately as well.
9844 If NTH is an integer, immediately pick the NTH link found.
9845 If ZERO is a string, check also this string for a link, and if
9846 there is one, offer it as link number zero."
9847 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9848 "\\(" org-angle-link-re "\\)\\|"
9849 "\\(" org-plain-link-re "\\)"))
9850 (cnt ?0)
9851 (in-emacs (if (integerp nth) nil nth))
9852 have-zero end links link c)
9853 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9854 (push (match-string 0 zero) links)
9855 (setq cnt (1- cnt) have-zero t))
9856 (save-excursion
9857 (org-back-to-heading t)
9858 (setq end (save-excursion (outline-next-heading) (point)))
9859 (while (re-search-forward re end t)
9860 (push (match-string 0) links))
9861 (setq links (org-uniquify (reverse links))))
9863 (cond
9864 ((null links)
9865 (message "No links"))
9866 ((equal (length links) 1)
9867 (setq link (list (car links))))
9868 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9869 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9870 (t ; we have to select a link
9871 (save-excursion
9872 (save-window-excursion
9873 (delete-other-windows)
9874 (with-output-to-temp-buffer "*Select Link*"
9875 (mapc (lambda (l)
9876 (if (not (string-match org-bracket-link-regexp l))
9877 (princ (format "[%c] %s\n" (incf cnt)
9878 (org-remove-angle-brackets l)))
9879 (if (match-end 3)
9880 (princ (format "[%c] %s (%s)\n" (incf cnt)
9881 (match-string 3 l) (match-string 1 l)))
9882 (princ (format "[%c] %s\n" (incf cnt)
9883 (match-string 1 l))))))
9884 links))
9885 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9886 (message "Select link to open, RET to open all:")
9887 (setq c (read-char-exclusive))
9888 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9889 (when (equal c ?q) (error "Abort"))
9890 (if (equal c ?\C-m)
9891 (setq link links)
9892 (setq nth (- c ?0))
9893 (if have-zero (setq nth (1+ nth)))
9894 (unless (and (integerp nth) (>= (length links) nth))
9895 (error "Invalid link selection"))
9896 (setq link (list (nth (1- nth) links))))))
9897 (if link
9898 (let ((buf (current-buffer)))
9899 (dolist (l link)
9900 (org-open-link-from-string l in-emacs buf))
9902 nil)))
9904 ;; Add special file links that specify the way of opening
9906 (org-add-link-type "file+sys" 'org-open-file-with-system)
9907 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9908 (defun org-open-file-with-system (path)
9909 "Open file at PATH using the system way of opening it."
9910 (org-open-file path 'system))
9911 (defun org-open-file-with-emacs (path)
9912 "Open file at PATH in Emacs."
9913 (org-open-file path 'emacs))
9914 (defun org-remove-file-link-modifiers ()
9915 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9916 (goto-char (point-min))
9917 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9918 (org-if-unprotected
9919 (replace-match "file:" t t))))
9920 (eval-after-load "org-exp"
9921 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9922 'org-remove-file-link-modifiers))
9924 ;;;; Time estimates
9926 (defun org-get-effort (&optional pom)
9927 "Get the effort estimate for the current entry."
9928 (org-entry-get pom org-effort-property))
9930 ;;; File search
9932 (defvar org-create-file-search-functions nil
9933 "List of functions to construct the right search string for a file link.
9934 These functions are called in turn with point at the location to
9935 which the link should point.
9937 A function in the hook should first test if it would like to
9938 handle this file type, for example by checking the `major-mode'
9939 or the file extension. If it decides not to handle this file, it
9940 should just return nil to give other functions a chance. If it
9941 does handle the file, it must return the search string to be used
9942 when following the link. The search string will be part of the
9943 file link, given after a double colon, and `org-open-at-point'
9944 will automatically search for it. If special measures must be
9945 taken to make the search successful, another function should be
9946 added to the companion hook `org-execute-file-search-functions',
9947 which see.
9949 A function in this hook may also use `setq' to set the variable
9950 `description' to provide a suggestion for the descriptive text to
9951 be used for this link when it gets inserted into an Org-mode
9952 buffer with \\[org-insert-link].")
9954 (defvar org-execute-file-search-functions nil
9955 "List of functions to execute a file search triggered by a link.
9957 Functions added to this hook must accept a single argument, the
9958 search string that was part of the file link, the part after the
9959 double colon. The function must first check if it would like to
9960 handle this search, for example by checking the `major-mode' or
9961 the file extension. If it decides not to handle this search, it
9962 should just return nil to give other functions a chance. If it
9963 does handle the search, it must return a non-nil value to keep
9964 other functions from trying.
9966 Each function can access the current prefix argument through the
9967 variable `current-prefix-argument'. Note that a single prefix is
9968 used to force opening a link in Emacs, so it may be good to only
9969 use a numeric or double prefix to guide the search function.
9971 In case this is needed, a function in this hook can also restore
9972 the window configuration before `org-open-at-point' was called using:
9974 (set-window-configuration org-window-config-before-follow-link)")
9976 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9977 (defun org-link-search (s &optional type avoid-pos stealth)
9978 "Search for a link search option.
9979 If S is surrounded by forward slashes, it is interpreted as a
9980 regular expression. In org-mode files, this will create an `org-occur'
9981 sparse tree. In ordinary files, `occur' will be used to list matches.
9982 If the current buffer is in `dired-mode', grep will be used to search
9983 in all files. If AVOID-POS is given, ignore matches near that position.
9985 When optional argument STEALTH is non-nil, do not modify
9986 visibility around point, thus ignoring
9987 `org-show-hierarchy-above', `org-show-following-heading' and
9988 `org-show-siblings' variables."
9989 (let ((case-fold-search t)
9990 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9991 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9992 (append '(("") (" ") ("\t") ("\n"))
9993 org-emphasis-alist)
9994 "\\|") "\\)"))
9995 (pos (point))
9996 (pre nil) (post nil)
9997 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9998 (cond
9999 ;; First check if there are any special search functions
10000 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10001 ;; Now try the builtin stuff
10002 ((and (equal (string-to-char s0) ?#)
10003 (> (length s0) 1)
10004 (save-excursion
10005 (goto-char (point-min))
10006 (and
10007 (re-search-forward
10008 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10009 (setq type 'dedicated
10010 pos (match-beginning 0))))
10011 ;; There is an exact target for this
10012 (goto-char pos)
10013 (org-back-to-heading t)))
10014 ((save-excursion
10015 (goto-char (point-min))
10016 (and
10017 (re-search-forward
10018 (concat "<<" (regexp-quote s0) ">>") nil t)
10019 (setq type 'dedicated
10020 pos (match-beginning 0))))
10021 ;; There is an exact target for this
10022 (goto-char pos))
10023 ((save-excursion
10024 (goto-char (point-min))
10025 (and
10026 (re-search-forward
10027 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10028 (setq type 'dedicated pos (match-beginning 0))))
10029 ;; Found an invisible target.
10030 (goto-char pos))
10031 ((save-excursion
10032 (goto-char (point-min))
10033 (and
10034 (re-search-forward
10035 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10036 (setq type 'dedicated pos (match-beginning 0))))
10037 ;; Found an element with a matching #+name affiliated keyword.
10038 (goto-char pos))
10039 ((and (string-match "^(\\(.*\\))$" s0)
10040 (save-excursion
10041 (goto-char (point-min))
10042 (and
10043 (re-search-forward
10044 (concat "[^[]" (regexp-quote
10045 (format org-coderef-label-format
10046 (match-string 1 s0))))
10047 nil t)
10048 (setq type 'dedicated
10049 pos (1+ (match-beginning 0))))))
10050 ;; There is a coderef target for this
10051 (goto-char pos))
10052 ((string-match "^/\\(.*\\)/$" s)
10053 ;; A regular expression
10054 (cond
10055 ((derived-mode-p 'org-mode)
10056 (org-occur (match-string 1 s)))
10057 ;;((eq major-mode 'dired-mode)
10058 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10059 (t (org-do-occur (match-string 1 s)))))
10060 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10061 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10062 (goto-char (point-min))
10063 (cond
10064 ((let (case-fold-search)
10065 (re-search-forward (format org-complex-heading-regexp-format
10066 (regexp-quote s))
10067 nil t))
10068 ;; OK, found a match
10069 (setq type 'dedicated)
10070 (goto-char (match-beginning 0)))
10071 ((and (not org-link-search-inhibit-query)
10072 (eq org-link-search-must-match-exact-headline 'query-to-create)
10073 (y-or-n-p "No match - create this as a new heading? "))
10074 (goto-char (point-max))
10075 (or (bolp) (newline))
10076 (insert "* " s "\n")
10077 (beginning-of-line 0))
10079 (goto-char pos)
10080 (error "No match"))))
10082 ;; A normal search string
10083 (when (equal (string-to-char s) ?*)
10084 ;; Anchor on headlines, post may include tags.
10085 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10086 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10087 s (substring s 1)))
10088 (remove-text-properties
10089 0 (length s)
10090 '(face nil mouse-face nil keymap nil fontified nil) s)
10091 ;; Make a series of regular expressions to find a match
10092 (setq words (org-split-string s "[ \n\r\t]+")
10094 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10095 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10096 "\\)" markers)
10097 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10098 re2a (concat "[ \t\r\n]" re2a_)
10099 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10100 re4 (concat "[^a-zA-Z_]" re4_)
10102 re1 (concat pre re2 post)
10103 re3 (concat pre (if pre re4_ re4) post)
10104 re5 (concat pre ".*" re4)
10105 re2 (concat pre re2)
10106 re2a (concat pre (if pre re2a_ re2a))
10107 re4 (concat pre (if pre re4_ re4))
10108 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10109 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10110 re5 "\\)"
10112 (cond
10113 ((eq type 'org-occur) (org-occur reall))
10114 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10115 (t (goto-char (point-min))
10116 (setq type 'fuzzy)
10117 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10118 (org-search-not-self 1 re1 nil t)
10119 (org-search-not-self 1 re2 nil t)
10120 (org-search-not-self 1 re2a nil t)
10121 (org-search-not-self 1 re3 nil t)
10122 (org-search-not-self 1 re4 nil t)
10123 (org-search-not-self 1 re5 nil t)
10125 (goto-char (match-beginning 1))
10126 (goto-char pos)
10127 (error "No match"))))))
10128 (and (derived-mode-p 'org-mode)
10129 (not stealth)
10130 (org-show-context 'link-search))
10131 type))
10133 (defun org-search-not-self (group &rest args)
10134 "Execute `re-search-forward', but only accept matches that do not
10135 enclose the position of `org-open-link-marker'."
10136 (let ((m org-open-link-marker))
10137 (catch 'exit
10138 (while (apply 're-search-forward args)
10139 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10140 (goto-char (match-end group))
10141 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10142 (> (match-beginning 0) (marker-position m))
10143 (< (match-end 0) (marker-position m)))
10144 (save-match-data
10145 (or (not (org-in-regexp
10146 org-bracket-link-analytic-regexp 1))
10147 (not (match-end 4)) ; no description
10148 (and (<= (match-beginning 4) (point))
10149 (>= (match-end 4) (point))))))
10150 (throw 'exit (point))))))))
10152 (defun org-get-buffer-for-internal-link (buffer)
10153 "Return a buffer to be used for displaying the link target of internal links."
10154 (cond
10155 ((not org-display-internal-link-with-indirect-buffer)
10156 buffer)
10157 ((string-match "(Clone)$" (buffer-name buffer))
10158 (message "Buffer is already a clone, not making another one")
10159 ;; we also do not modify visibility in this case
10160 buffer)
10161 (t ; make a new indirect buffer for displaying the link
10162 (let* ((bn (buffer-name buffer))
10163 (ibn (concat bn "(Clone)"))
10164 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10165 (with-current-buffer ib (org-overview))
10166 ib))))
10168 (defun org-do-occur (regexp &optional cleanup)
10169 "Call the Emacs command `occur'.
10170 If CLEANUP is non-nil, remove the printout of the regular expression
10171 in the *Occur* buffer. This is useful if the regex is long and not useful
10172 to read."
10173 (occur regexp)
10174 (when cleanup
10175 (let ((cwin (selected-window)) win beg end)
10176 (when (setq win (get-buffer-window "*Occur*"))
10177 (select-window win))
10178 (goto-char (point-min))
10179 (when (re-search-forward "match[a-z]+" nil t)
10180 (setq beg (match-end 0))
10181 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10182 (setq end (1- (match-beginning 0)))))
10183 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10184 (goto-char (point-min))
10185 (select-window cwin))))
10187 ;;; The mark ring for links jumps
10189 (defvar org-mark-ring nil
10190 "Mark ring for positions before jumps in Org-mode.")
10191 (defvar org-mark-ring-last-goto nil
10192 "Last position in the mark ring used to go back.")
10193 ;; Fill and close the ring
10194 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10195 (loop for i from 1 to org-mark-ring-length do
10196 (push (make-marker) org-mark-ring))
10197 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10198 org-mark-ring)
10200 (defun org-mark-ring-push (&optional pos buffer)
10201 "Put the current position or POS into the mark ring and rotate it."
10202 (interactive)
10203 (setq pos (or pos (point)))
10204 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10205 (move-marker (car org-mark-ring)
10206 (or pos (point))
10207 (or buffer (current-buffer)))
10208 (message "%s"
10209 (substitute-command-keys
10210 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10212 (defun org-mark-ring-goto (&optional n)
10213 "Jump to the previous position in the mark ring.
10214 With prefix arg N, jump back that many stored positions. When
10215 called several times in succession, walk through the entire ring.
10216 Org-mode commands jumping to a different position in the current file,
10217 or to another Org-mode file, automatically push the old position
10218 onto the ring."
10219 (interactive "p")
10220 (let (p m)
10221 (if (eq last-command this-command)
10222 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10223 (setq p org-mark-ring))
10224 (setq org-mark-ring-last-goto p)
10225 (setq m (car p))
10226 (org-pop-to-buffer-same-window (marker-buffer m))
10227 (goto-char m)
10228 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10230 (defun org-remove-angle-brackets (s)
10231 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10232 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10234 (defun org-add-angle-brackets (s)
10235 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10236 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10238 (defun org-remove-double-quotes (s)
10239 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10240 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10243 ;;; Following specific links
10245 (defun org-follow-timestamp-link ()
10246 (cond
10247 ((org-at-date-range-p t)
10248 (let ((org-agenda-start-on-weekday)
10249 (t1 (match-string 1))
10250 (t2 (match-string 2)))
10251 (setq t1 (time-to-days (org-time-string-to-time t1))
10252 t2 (time-to-days (org-time-string-to-time t2)))
10253 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10254 ((org-at-timestamp-p t)
10255 (org-agenda-list nil (time-to-days (org-time-string-to-time
10256 (substring (match-string 1) 0 10)))
10258 (t (error "This should not happen"))))
10261 ;;; Following file links
10262 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10263 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10264 (declare-function mailcap-mime-info
10265 "mailcap" (string &optional request no-decode))
10266 (defvar org-wait nil)
10267 (defun org-open-file (path &optional in-emacs line search)
10268 "Open the file at PATH.
10269 First, this expands any special file name abbreviations. Then the
10270 configuration variable `org-file-apps' is checked if it contains an
10271 entry for this file type, and if yes, the corresponding command is launched.
10273 If no application is found, Emacs simply visits the file.
10275 With optional prefix argument IN-EMACS, Emacs will visit the file.
10276 With a double \\[universal-argument] \\[universal-argument] \
10277 prefix arg, Org tries to avoid opening in Emacs
10278 and to use an external application to visit the file.
10280 Optional LINE specifies a line to go to, optional SEARCH a string
10281 to search for. If LINE or SEARCH is given, the file will be
10282 opened in Emacs, unless an entry from org-file-apps that makes
10283 use of groups in a regexp matches.
10285 If you want to change the way frames are used when following a
10286 link, please customize `org-link-frame-setup'.
10288 If the file does not exist, an error is thrown."
10289 (let* ((file (if (equal path "")
10290 buffer-file-name
10291 (substitute-in-file-name (expand-file-name path))))
10292 (file-apps (append org-file-apps (org-default-apps)))
10293 (apps (org-remove-if
10294 'org-file-apps-entry-match-against-dlink-p file-apps))
10295 (apps-dlink (org-remove-if-not
10296 'org-file-apps-entry-match-against-dlink-p file-apps))
10297 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10298 (dirp (if remp nil (file-directory-p file)))
10299 (file (if (and dirp org-open-directory-means-index-dot-org)
10300 (concat (file-name-as-directory file) "index.org")
10301 file))
10302 (a-m-a-p (assq 'auto-mode apps))
10303 (dfile (downcase file))
10304 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10305 (link (cond ((and (eq line nil)
10306 (eq search nil))
10307 file)
10308 (line
10309 (concat file "::" (number-to-string line)))
10310 (search
10311 (concat file "::" search))))
10312 (dlink (downcase link))
10313 (old-buffer (current-buffer))
10314 (old-pos (point))
10315 (old-mode major-mode)
10316 ext cmd link-match-data)
10317 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10318 (setq ext (match-string 1 dfile))
10319 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10320 (setq ext (match-string 1 dfile))))
10321 (cond
10322 ((member in-emacs '((16) system))
10323 (setq cmd (cdr (assoc 'system apps))))
10324 (in-emacs (setq cmd 'emacs))
10326 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10327 (and dirp (cdr (assoc 'directory apps)))
10328 ; first, try matching against apps-dlink
10329 ; if we get a match here, store the match data for later
10330 (let ((match (assoc-default dlink apps-dlink
10331 'string-match)))
10332 (if match
10333 (progn (setq link-match-data (match-data))
10334 match)
10335 (progn (setq in-emacs (or in-emacs line search))
10336 nil))) ; if we have no match in apps-dlink,
10337 ; always open the file in emacs if line or search
10338 ; is given (for backwards compatibility)
10339 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10340 'string-match)
10341 (cdr (assoc ext apps))
10342 (cdr (assoc t apps))))))
10343 (when (eq cmd 'system)
10344 (setq cmd (cdr (assoc 'system apps))))
10345 (when (eq cmd 'default)
10346 (setq cmd (cdr (assoc t apps))))
10347 (when (eq cmd 'mailcap)
10348 (require 'mailcap)
10349 (mailcap-parse-mailcaps)
10350 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10351 (command (mailcap-mime-info mime-type)))
10352 (if (stringp command)
10353 (setq cmd command)
10354 (setq cmd 'emacs))))
10355 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10356 (not (file-exists-p file))
10357 (not org-open-non-existing-files))
10358 (error "No such file: %s" file))
10359 (cond
10360 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10361 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10362 (while (string-match "['\"]%s['\"]" cmd)
10363 (setq cmd (replace-match "%s" t t cmd)))
10364 (while (string-match "%s" cmd)
10365 (setq cmd (replace-match
10366 (save-match-data
10367 (shell-quote-argument
10368 (convert-standard-filename file)))
10369 t t cmd)))
10371 ;; Replace "%1", "%2" etc. in command with group matches from regex
10372 (save-match-data
10373 (let ((match-index 1)
10374 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10375 (set-match-data link-match-data)
10376 (while (<= match-index number-of-groups)
10377 (let ((regex (concat "%" (number-to-string match-index)))
10378 (replace-with (match-string match-index dlink)))
10379 (while (string-match regex cmd)
10380 (setq cmd (replace-match replace-with t t cmd))))
10381 (setq match-index (+ match-index 1)))))
10383 (save-window-excursion
10384 (start-process-shell-command cmd nil cmd)
10385 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10387 ((or (stringp cmd)
10388 (eq cmd 'emacs))
10389 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10390 (widen)
10391 (if line (org-goto-line line)
10392 (if search (org-link-search search))))
10393 ((consp cmd)
10394 (let ((file (convert-standard-filename file)))
10395 (save-match-data
10396 (set-match-data link-match-data)
10397 (eval cmd))))
10398 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10399 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10400 (or (not (equal old-buffer (current-buffer)))
10401 (not (equal old-pos (point))))
10402 (org-mark-ring-push old-pos old-buffer))))
10404 (defun org-file-apps-entry-match-against-dlink-p (entry)
10405 "This function returns non-nil if `entry' uses a regular
10406 expression which should be matched against the whole link by
10407 org-open-file.
10409 It assumes that is the case when the entry uses a regular
10410 expression which has at least one grouping construct and the
10411 action is either a lisp form or a command string containing
10412 '%1', i.e. using at least one subexpression match as a
10413 parameter."
10414 (let ((selector (car entry))
10415 (action (cdr entry)))
10416 (if (stringp selector)
10417 (and (> (regexp-opt-depth selector) 0)
10418 (or (and (stringp action)
10419 (string-match "%[0-9]" action))
10420 (consp action)))
10421 nil)))
10423 (defun org-default-apps ()
10424 "Return the default applications for this operating system."
10425 (cond
10426 ((eq system-type 'darwin)
10427 org-file-apps-defaults-macosx)
10428 ((eq system-type 'windows-nt)
10429 org-file-apps-defaults-windowsnt)
10430 (t org-file-apps-defaults-gnu)))
10432 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10433 "Convert extensions to regular expressions in the cars of LIST.
10434 Also, weed out any non-string entries, because the return value is used
10435 only for regexp matching.
10436 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10437 point to the symbol `emacs', indicating that the file should
10438 be opened in Emacs."
10439 (append
10440 (delq nil
10441 (mapcar (lambda (x)
10442 (if (not (stringp (car x)))
10444 (if (string-match "\\W" (car x))
10446 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10447 list))
10448 (if add-auto-mode
10449 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10451 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10452 (defun org-file-remote-p (file)
10453 "Test whether FILE specifies a location on a remote system.
10454 Return non-nil if the location is indeed remote.
10456 For example, the filename \"/user@host:/foo\" specifies a location
10457 on the system \"/user@host:\"."
10458 (cond ((fboundp 'file-remote-p)
10459 (file-remote-p file))
10460 ((fboundp 'tramp-handle-file-remote-p)
10461 (tramp-handle-file-remote-p file))
10462 ((and (boundp 'ange-ftp-name-format)
10463 (string-match (car ange-ftp-name-format) file))
10465 (t nil)))
10468 ;;;; Refiling
10470 (defun org-get-org-file ()
10471 "Read a filename, with default directory `org-directory'."
10472 (let ((default (or org-default-notes-file remember-data-file)))
10473 (read-file-name (format "File name [%s]: " default)
10474 (file-name-as-directory org-directory)
10475 default)))
10477 (defun org-notes-order-reversed-p ()
10478 "Check if the current file should receive notes in reversed order."
10479 (cond
10480 ((not org-reverse-note-order) nil)
10481 ((eq t org-reverse-note-order) t)
10482 ((not (listp org-reverse-note-order)) nil)
10483 (t (catch 'exit
10484 (let ((all org-reverse-note-order)
10485 entry)
10486 (while (setq entry (pop all))
10487 (if (string-match (car entry) buffer-file-name)
10488 (throw 'exit (cdr entry))))
10489 nil)))))
10491 (defvar org-refile-target-table nil
10492 "The list of refile targets, created by `org-refile'.")
10494 (defvar org-agenda-new-buffers nil
10495 "Buffers created to visit agenda files.")
10497 (defvar org-refile-cache nil
10498 "Cache for refile targets.")
10500 (defvar org-refile-markers nil
10501 "All the markers used for caching refile locations.")
10503 (defun org-refile-marker (pos)
10504 "Get a new refile marker, but only if caching is in use."
10505 (if (not org-refile-use-cache)
10507 (let ((m (make-marker)))
10508 (move-marker m pos)
10509 (push m org-refile-markers)
10510 m)))
10512 (defun org-refile-cache-clear ()
10513 "Clear the refile cache and disable all the markers."
10514 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10515 (setq org-refile-markers nil)
10516 (setq org-refile-cache nil)
10517 (message "Refile cache has been cleared"))
10519 (defun org-refile-cache-check-set (set)
10520 "Check if all the markers in the cache still have live buffers."
10521 (let (marker)
10522 (catch 'exit
10523 (while (and set (setq marker (nth 3 (pop set))))
10524 ;; if org-refile-use-outline-path is 'file, marker may be nil
10525 (when (and marker (null (marker-buffer marker)))
10526 (message "not found") (sit-for 3)
10527 (throw 'exit nil)))
10528 t)))
10530 (defun org-refile-cache-put (set &rest identifiers)
10531 "Push the refile targets SET into the cache, under IDENTIFIERS."
10532 (let* ((key (sha1 (prin1-to-string identifiers)))
10533 (entry (assoc key org-refile-cache)))
10534 (if entry
10535 (setcdr entry set)
10536 (push (cons key set) org-refile-cache))))
10538 (defun org-refile-cache-get (&rest identifiers)
10539 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10540 (cond
10541 ((not org-refile-cache) nil)
10542 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10544 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10545 org-refile-cache))))
10546 (and set (org-refile-cache-check-set set) set)))))
10548 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10549 "Produce a table with refile targets."
10550 (let ((case-fold-search nil)
10551 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10552 (entries (or org-refile-targets '((nil . (:level . 1)))))
10553 targets tgs txt re files f desc descre fast-path-p level pos0)
10554 (message "Getting targets...")
10555 (with-current-buffer (or default-buffer (current-buffer))
10556 (while (setq entry (pop entries))
10557 (setq files (car entry) desc (cdr entry))
10558 (setq fast-path-p nil)
10559 (cond
10560 ((null files) (setq files (list (current-buffer))))
10561 ((eq files 'org-agenda-files)
10562 (setq files (org-agenda-files 'unrestricted)))
10563 ((and (symbolp files) (fboundp files))
10564 (setq files (funcall files)))
10565 ((and (symbolp files) (boundp files))
10566 (setq files (symbol-value files))))
10567 (if (stringp files) (setq files (list files)))
10568 (cond
10569 ((eq (car desc) :tag)
10570 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10571 ((eq (car desc) :todo)
10572 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10573 ((eq (car desc) :regexp)
10574 (setq descre (cdr desc)))
10575 ((eq (car desc) :level)
10576 (setq descre (concat "^\\*\\{" (number-to-string
10577 (if org-odd-levels-only
10578 (1- (* 2 (cdr desc)))
10579 (cdr desc)))
10580 "\\}[ \t]")))
10581 ((eq (car desc) :maxlevel)
10582 (setq fast-path-p t)
10583 (setq descre (concat "^\\*\\{1," (number-to-string
10584 (if org-odd-levels-only
10585 (1- (* 2 (cdr desc)))
10586 (cdr desc)))
10587 "\\}[ \t]")))
10588 (t (error "Bad refiling target description %s" desc)))
10589 (while (setq f (pop files))
10590 (with-current-buffer
10591 (if (bufferp f) f (org-get-agenda-file-buffer f))
10593 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10594 (progn
10595 (if (bufferp f) (setq f (buffer-file-name
10596 (buffer-base-buffer f))))
10597 (setq f (and f (expand-file-name f)))
10598 (if (eq org-refile-use-outline-path 'file)
10599 (push (list (file-name-nondirectory f) f nil nil) tgs))
10600 (save-excursion
10601 (save-restriction
10602 (widen)
10603 (goto-char (point-min))
10604 (while (re-search-forward descre nil t)
10605 (goto-char (setq pos0 (point-at-bol)))
10606 (catch 'next
10607 (when org-refile-target-verify-function
10608 (save-match-data
10609 (or (funcall org-refile-target-verify-function)
10610 (throw 'next t))))
10611 (when (and (looking-at org-complex-heading-regexp)
10612 (not (member (match-string 4) excluded-entries))
10613 (match-string 4))
10614 (setq level (org-reduced-level
10615 (- (match-end 1) (match-beginning 1)))
10616 txt (org-link-display-format (match-string 4))
10617 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10618 re (format org-complex-heading-regexp-format
10619 (regexp-quote (match-string 4))))
10620 (when org-refile-use-outline-path
10621 (setq txt (mapconcat
10622 'org-protect-slash
10623 (append
10624 (if (eq org-refile-use-outline-path
10625 'file)
10626 (list (file-name-nondirectory
10627 (buffer-file-name
10628 (buffer-base-buffer))))
10629 (if (eq org-refile-use-outline-path
10630 'full-file-path)
10631 (list (buffer-file-name
10632 (buffer-base-buffer)))))
10633 (org-get-outline-path fast-path-p
10634 level txt)
10635 (list txt))
10636 "/")))
10637 (push (list txt f re (org-refile-marker (point)))
10638 tgs)))
10639 (when (= (point) pos0)
10640 ;; verification function has not moved point
10641 (goto-char (point-at-eol))))))))
10642 (when org-refile-use-cache
10643 (org-refile-cache-put tgs (buffer-file-name) descre))
10644 (setq targets (append tgs targets))
10645 ))))
10646 (message "Getting targets...done")
10647 (nreverse targets)))
10649 (defun org-protect-slash (s)
10650 (while (string-match "/" s)
10651 (setq s (replace-match "\\" t t s)))
10654 (defvar org-olpa (make-vector 20 nil))
10656 (defun org-get-outline-path (&optional fastp level heading)
10657 "Return the outline path to the current entry, as a list.
10659 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10660 routine which makes outline path derivations for an entire file,
10661 avoiding backtracing. Refile target collection makes use of that."
10662 (if fastp
10663 (progn
10664 (if (> level 19)
10665 (error "Outline path failure, more than 19 levels"))
10666 (loop for i from level upto 19 do
10667 (aset org-olpa i nil))
10668 (prog1
10669 (delq nil (append org-olpa nil))
10670 (aset org-olpa level heading)))
10671 (let (rtn case-fold-search)
10672 (save-excursion
10673 (save-restriction
10674 (widen)
10675 (while (org-up-heading-safe)
10676 (when (looking-at org-complex-heading-regexp)
10677 (push (org-match-string-no-properties 4) rtn)))
10678 rtn)))))
10680 (defun org-format-outline-path (path &optional width prefix)
10681 "Format the outline path PATH for display.
10682 Width is the maximum number of characters that is available.
10683 Prefix is a prefix to be included in the returned string,
10684 such as the file name."
10685 (setq width (or width 79))
10686 (if prefix (setq width (- width (length prefix))))
10687 (if (not path)
10688 (or prefix "")
10689 (let* ((nsteps (length path))
10690 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10691 (maxwidth (if (<= total-width width)
10692 10000 ;; everything fits
10693 ;; we need to shorten the level headings
10694 (/ (- width nsteps) nsteps)))
10695 (org-odd-levels-only nil)
10696 (n 0)
10697 (total (1+ (length prefix))))
10698 (setq maxwidth (max maxwidth 10))
10699 (concat prefix
10700 (mapconcat
10701 (lambda (h)
10702 (setq n (1+ n))
10703 (if (and (= n nsteps) (< maxwidth 10000))
10704 (setq maxwidth (- total-width total)))
10705 (if (< (length h) maxwidth)
10706 (progn (setq total (+ total (length h) 1)) h)
10707 (setq h (substring h 0 (- maxwidth 2))
10708 total (+ total maxwidth 1))
10709 (if (string-match "[ \t]+\\'" h)
10710 (setq h (substring h 0 (match-beginning 0))))
10711 (setq h (concat h "..")))
10712 (org-add-props h nil 'face
10713 (nth (% (1- n) org-n-level-faces)
10714 org-level-faces))
10716 path "/")))))
10718 (defun org-display-outline-path (&optional file current)
10719 "Display the current outline path in the echo area."
10720 (interactive "P")
10721 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10722 (case-fold-search nil)
10723 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10724 (if current (setq path (append path
10725 (save-excursion
10726 (org-back-to-heading t)
10727 (if (looking-at org-complex-heading-regexp)
10728 (list (match-string 4)))))))
10729 (message "%s"
10730 (org-format-outline-path
10731 path
10732 (1- (frame-width))
10733 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10735 (defvar org-refile-history nil
10736 "History for refiling operations.")
10738 (defvar org-after-refile-insert-hook nil
10739 "Hook run after `org-refile' has inserted its stuff at the new location.
10740 Note that this is still *before* the stuff will be removed from
10741 the *old* location.")
10743 (defvar org-capture-last-stored-marker)
10744 (defun org-refile (&optional goto default-buffer rfloc)
10745 "Move the entry or entries at point to another heading.
10746 The list of target headings is compiled using the information in
10747 `org-refile-targets', which see.
10749 At the target location, the entry is filed as a subitem of the target
10750 heading. Depending on `org-reverse-note-order', the new subitem will
10751 either be the first or the last subitem.
10753 If there is an active region, all entries in that region will be moved.
10754 However, the region must fulfill the requirement that the first heading
10755 is the first one sets the top-level of the moved text - at most siblings
10756 below it are allowed.
10758 With prefix arg GOTO, the command will only visit the target location
10759 and not actually move anything.
10761 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10762 go to the location where the last refiling operation has put the subtree.
10763 With a prefix argument of `2', refile to the running clock.
10765 RFLOC can be a refile location obtained in a different way.
10767 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10769 If you are using target caching (see `org-refile-use-cache'),
10770 you have to clear the target cache in order to find new targets.
10771 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10772 prefix argument (`C-u C-u C-u C-c C-w')."
10774 (interactive "P")
10775 (if (member goto '(0 (64)))
10776 (org-refile-cache-clear)
10777 (let* ((cbuf (current-buffer))
10778 (regionp (org-region-active-p))
10779 (region-start (and regionp (region-beginning)))
10780 (region-end (and regionp (region-end)))
10781 (region-length (and regionp (- region-end region-start)))
10782 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10783 pos it nbuf file re level reversed)
10784 (setq last-command nil)
10785 (when regionp
10786 (goto-char region-start)
10787 (or (bolp) (goto-char (point-at-bol)))
10788 (setq region-start (point))
10789 (unless (or (org-kill-is-subtree-p
10790 (buffer-substring region-start region-end))
10791 (prog1 org-refile-active-region-within-subtree
10792 (org-toggle-heading)))
10793 (error "The region is not a (sequence of) subtree(s)")))
10794 (if (equal goto '(16))
10795 (org-refile-goto-last-stored)
10796 (when (or
10797 (and (equal goto 2)
10798 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10799 (prog1
10800 (setq it (list (or org-clock-heading "running clock")
10801 (buffer-file-name
10802 (marker-buffer org-clock-hd-marker))
10804 (marker-position org-clock-hd-marker)))
10805 (setq goto nil)))
10806 (setq it (or rfloc
10807 (let (heading-text)
10808 (save-excursion
10809 (unless goto
10810 (org-back-to-heading t)
10811 (setq heading-text
10812 (nth 4 (org-heading-components))))
10813 (org-refile-get-location
10814 (cond (goto "Goto")
10815 (regionp "Refile region to")
10816 (t (concat "Refile subtree \""
10817 heading-text "\" to")))
10818 default-buffer
10819 (and (not (equal '(4) goto))
10820 org-refile-allow-creating-parent-nodes)
10821 goto))))))
10822 (setq file (nth 1 it)
10823 re (nth 2 it)
10824 pos (nth 3 it))
10825 (if (and (not goto)
10827 (equal (buffer-file-name) file)
10828 (if regionp
10829 (and (>= pos region-start)
10830 (<= pos region-end))
10831 (and (>= pos (point))
10832 (< pos (save-excursion
10833 (org-end-of-subtree t t))))))
10834 (error "Cannot refile to position inside the tree or region"))
10836 (setq nbuf (or (find-buffer-visiting file)
10837 (find-file-noselect file)))
10838 (if goto
10839 (progn
10840 (org-pop-to-buffer-same-window nbuf)
10841 (goto-char pos)
10842 (org-show-context 'org-goto))
10843 (if regionp
10844 (progn
10845 (org-kill-new (buffer-substring region-start region-end))
10846 (org-save-markers-in-region region-start region-end))
10847 (org-copy-subtree 1 nil t))
10848 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10849 (find-file-noselect file)))
10850 (setq reversed (org-notes-order-reversed-p))
10851 (save-excursion
10852 (save-restriction
10853 (widen)
10854 (if pos
10855 (progn
10856 (goto-char pos)
10857 (looking-at org-outline-regexp)
10858 (setq level (org-get-valid-level (funcall outline-level) 1))
10859 (goto-char
10860 (if reversed
10861 (or (outline-next-heading) (point-max))
10862 (or (save-excursion (org-get-next-sibling))
10863 (org-end-of-subtree t t)
10864 (point-max)))))
10865 (setq level 1)
10866 (if (not reversed)
10867 (goto-char (point-max))
10868 (goto-char (point-min))
10869 (or (outline-next-heading) (goto-char (point-max)))))
10870 (if (not (bolp)) (newline))
10871 (org-paste-subtree level)
10872 (when org-log-refile
10873 (org-add-log-setup 'refile nil nil 'findpos
10874 org-log-refile)
10875 (unless (eq org-log-refile 'note)
10876 (save-excursion (org-add-log-note))))
10877 (and org-auto-align-tags
10878 (let ((org-loop-over-headlines-in-active-region nil))
10879 (org-set-tags nil t)))
10880 (bookmark-set "org-refile-last-stored")
10881 ;; If we are refiling for capture, make sure that the
10882 ;; last-capture pointers point here
10883 (when (org-bound-and-true-p org-refile-for-capture)
10884 (bookmark-set "org-capture-last-stored-marker")
10885 (move-marker org-capture-last-stored-marker (point)))
10886 (if (fboundp 'deactivate-mark) (deactivate-mark))
10887 (run-hooks 'org-after-refile-insert-hook))))
10888 (if regionp
10889 (delete-region (point) (+ (point) region-length))
10890 (org-cut-subtree))
10891 (when (featurep 'org-inlinetask)
10892 (org-inlinetask-remove-END-maybe))
10893 (setq org-markers-to-move nil)
10894 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10896 (defun org-refile-goto-last-stored ()
10897 "Go to the location where the last refile was stored."
10898 (interactive)
10899 (bookmark-jump "org-refile-last-stored")
10900 (message "This is the location of the last refile"))
10902 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10903 no-exclude)
10904 "Prompt the user for a refile location, using PROMPT.
10905 PROMPT should not be suffixed with a colon and a space, because
10906 this function appends the default value from
10907 `org-refile-history' automatically, if that is not empty.
10908 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10909 this is used for the GOTO interface."
10910 (let ((org-refile-targets org-refile-targets)
10911 (org-refile-use-outline-path org-refile-use-outline-path)
10912 excluded-entries)
10913 (when (and (derived-mode-p 'org-mode)
10914 (not org-refile-use-cache)
10915 (not no-exclude))
10916 (org-map-tree
10917 (lambda()
10918 (setq excluded-entries
10919 (append excluded-entries (list (org-get-heading t t)))))))
10920 (setq org-refile-target-table
10921 (org-refile-get-targets default-buffer excluded-entries)))
10922 (unless org-refile-target-table
10923 (error "No refile targets"))
10924 (let* ((prompt (concat prompt
10925 (and (car org-refile-history)
10926 (concat " (default " (car org-refile-history) ")"))
10927 ": "))
10928 (cbuf (current-buffer))
10929 (partial-completion-mode nil)
10930 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10931 (cfunc (if (and org-refile-use-outline-path
10932 org-outline-path-complete-in-steps)
10933 'org-olpath-completing-read
10934 'org-icompleting-read))
10935 (extra (if org-refile-use-outline-path "/" ""))
10936 (filename (and cfn (expand-file-name cfn)))
10937 (tbl (mapcar
10938 (lambda (x)
10939 (if (and (not (member org-refile-use-outline-path
10940 '(file full-file-path)))
10941 (not (equal filename (nth 1 x))))
10942 (cons (concat (car x) extra " ("
10943 (file-name-nondirectory (nth 1 x)) ")")
10944 (cdr x))
10945 (cons (concat (car x) extra) (cdr x))))
10946 org-refile-target-table))
10947 (completion-ignore-case t)
10948 pa answ parent-target child parent old-hist)
10949 (setq old-hist org-refile-history)
10950 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10951 nil 'org-refile-history (car org-refile-history)))
10952 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10953 (org-refile-check-position pa)
10954 (if pa
10955 (progn
10956 (when (or (not org-refile-history)
10957 (not (eq old-hist org-refile-history))
10958 (not (equal (car pa) (car org-refile-history))))
10959 (setq org-refile-history
10960 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10961 org-refile-history
10962 (cdr org-refile-history))))
10963 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10964 (pop org-refile-history)))
10966 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10967 (progn
10968 (setq parent (match-string 1 answ)
10969 child (match-string 2 answ))
10970 (setq parent-target (or (assoc parent tbl)
10971 (assoc (concat parent "/") tbl)))
10972 (when (and parent-target
10973 (or (eq new-nodes t)
10974 (and (eq new-nodes 'confirm)
10975 (y-or-n-p (format "Create new node \"%s\"? "
10976 child)))))
10977 (org-refile-new-child parent-target child)))
10978 (error "Invalid target location")))))
10980 (declare-function org-string-nw-p "org-macs.el" (s))
10981 (defun org-refile-check-position (refile-pointer)
10982 "Check if the refile pointer matches the readline to which it points."
10983 (let* ((file (nth 1 refile-pointer))
10984 (re (nth 2 refile-pointer))
10985 (pos (nth 3 refile-pointer))
10986 buffer)
10987 (when (org-string-nw-p re)
10988 (setq buffer (if (markerp pos)
10989 (marker-buffer pos)
10990 (or (find-buffer-visiting file)
10991 (find-file-noselect file))))
10992 (with-current-buffer buffer
10993 (save-excursion
10994 (save-restriction
10995 (widen)
10996 (goto-char pos)
10997 (beginning-of-line 1)
10998 (unless (org-looking-at-p re)
10999 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11001 (defun org-refile-new-child (parent-target child)
11002 "Use refile target PARENT-TARGET to add new CHILD below it."
11003 (unless parent-target
11004 (error "Cannot find parent for new node"))
11005 (let ((file (nth 1 parent-target))
11006 (pos (nth 3 parent-target))
11007 level)
11008 (with-current-buffer (or (find-buffer-visiting file)
11009 (find-file-noselect file))
11010 (save-excursion
11011 (save-restriction
11012 (widen)
11013 (if pos
11014 (goto-char pos)
11015 (goto-char (point-max))
11016 (if (not (bolp)) (newline)))
11017 (when (looking-at org-outline-regexp)
11018 (setq level (funcall outline-level))
11019 (org-end-of-subtree t t))
11020 (org-back-over-empty-lines)
11021 (insert "\n" (make-string
11022 (if pos (org-get-valid-level level 1) 1) ?*)
11023 " " child "\n")
11024 (beginning-of-line 0)
11025 (list (concat (car parent-target) "/" child) file "" (point)))))))
11027 (defun org-olpath-completing-read (prompt collection &rest args)
11028 "Read an outline path like a file name."
11029 (let ((thetable collection)
11030 (org-completion-use-ido nil) ; does not work with ido.
11031 (org-completion-use-iswitchb nil)) ; or iswitchb
11032 (apply
11033 'org-icompleting-read prompt
11034 (lambda (string predicate &optional flag)
11035 (let (rtn r f (l (length string)))
11036 (cond
11037 ((eq flag nil)
11038 ;; try completion
11039 (try-completion string thetable))
11040 ((eq flag t)
11041 ;; all-completions
11042 (setq rtn (all-completions string thetable predicate))
11043 (mapcar
11044 (lambda (x)
11045 (setq r (substring x l))
11046 (if (string-match " ([^)]*)$" x)
11047 (setq f (match-string 0 x))
11048 (setq f ""))
11049 (if (string-match "/" r)
11050 (concat string (substring r 0 (match-end 0)) f)
11052 rtn))
11053 ((eq flag 'lambda)
11054 ;; exact match?
11055 (assoc string thetable)))))
11056 args)))
11058 ;;;; Dynamic blocks
11060 (defun org-find-dblock (name)
11061 "Find the first dynamic block with name NAME in the buffer.
11062 If not found, stay at current position and return nil."
11063 (let (pos)
11064 (save-excursion
11065 (goto-char (point-min))
11066 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
11067 nil t)
11068 (match-beginning 0))))
11069 (if pos (goto-char pos))
11070 pos))
11072 (defconst org-dblock-start-re
11073 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11074 "Matches the start line of a dynamic block, with parameters.")
11076 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
11077 "Matches the end of a dynamic block.")
11079 (defun org-create-dblock (plist)
11080 "Create a dynamic block section, with parameters taken from PLIST.
11081 PLIST must contain a :name entry which is used as name of the block."
11082 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11083 (end-of-line 1)
11084 (newline))
11085 (let ((col (current-column))
11086 (name (plist-get plist :name)))
11087 (insert "#+BEGIN: " name)
11088 (while plist
11089 (if (eq (car plist) :name)
11090 (setq plist (cddr plist))
11091 (insert " " (prin1-to-string (pop plist)))))
11092 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11093 (beginning-of-line -2)))
11095 (defun org-prepare-dblock ()
11096 "Prepare dynamic block for refresh.
11097 This empties the block, puts the cursor at the insert position and returns
11098 the property list including an extra property :name with the block name."
11099 (unless (looking-at org-dblock-start-re)
11100 (error "Not at a dynamic block"))
11101 (let* ((begdel (1+ (match-end 0)))
11102 (name (org-no-properties (match-string 1)))
11103 (params (append (list :name name)
11104 (read (concat "(" (match-string 3) ")")))))
11105 (save-excursion
11106 (beginning-of-line 1)
11107 (skip-chars-forward " \t")
11108 (setq params (plist-put params :indentation-column (current-column))))
11109 (unless (re-search-forward org-dblock-end-re nil t)
11110 (error "Dynamic block not terminated"))
11111 (setq params
11112 (append params
11113 (list :content (buffer-substring
11114 begdel (match-beginning 0)))))
11115 (delete-region begdel (match-beginning 0))
11116 (goto-char begdel)
11117 (open-line 1)
11118 params))
11120 (defun org-map-dblocks (&optional command)
11121 "Apply COMMAND to all dynamic blocks in the current buffer.
11122 If COMMAND is not given, use `org-update-dblock'."
11123 (let ((cmd (or command 'org-update-dblock)))
11124 (save-excursion
11125 (goto-char (point-min))
11126 (while (re-search-forward org-dblock-start-re nil t)
11127 (goto-char (match-beginning 0))
11128 (save-excursion
11129 (condition-case nil
11130 (funcall cmd)
11131 (error (message "Error during update of dynamic block"))))
11132 (unless (re-search-forward org-dblock-end-re nil t)
11133 (error "Dynamic block not terminated"))))))
11135 (defun org-dblock-update (&optional arg)
11136 "User command for updating dynamic blocks.
11137 Update the dynamic block at point. With prefix ARG, update all dynamic
11138 blocks in the buffer."
11139 (interactive "P")
11140 (if arg
11141 (org-update-all-dblocks)
11142 (or (looking-at org-dblock-start-re)
11143 (org-beginning-of-dblock))
11144 (org-update-dblock)))
11146 (defun org-update-dblock ()
11147 "Update the dynamic block at point.
11148 This means to empty the block, parse for parameters and then call
11149 the correct writing function."
11150 (interactive)
11151 (save-window-excursion
11152 (let* ((pos (point))
11153 (line (org-current-line))
11154 (params (org-prepare-dblock))
11155 (name (plist-get params :name))
11156 (indent (plist-get params :indentation-column))
11157 (cmd (intern (concat "org-dblock-write:" name))))
11158 (message "Updating dynamic block `%s' at line %d..." name line)
11159 (funcall cmd params)
11160 (message "Updating dynamic block `%s' at line %d...done" name line)
11161 (goto-char pos)
11162 (when (and indent (> indent 0))
11163 (setq indent (make-string indent ?\ ))
11164 (save-excursion
11165 (org-beginning-of-dblock)
11166 (forward-line 1)
11167 (while (not (looking-at org-dblock-end-re))
11168 (insert indent)
11169 (beginning-of-line 2))
11170 (when (looking-at org-dblock-end-re)
11171 (and (looking-at "[ \t]+")
11172 (replace-match ""))
11173 (insert indent)))))))
11175 (defun org-beginning-of-dblock ()
11176 "Find the beginning of the dynamic block at point.
11177 Error if there is no such block at point."
11178 (let ((pos (point))
11179 beg)
11180 (end-of-line 1)
11181 (if (and (re-search-backward org-dblock-start-re nil t)
11182 (setq beg (match-beginning 0))
11183 (re-search-forward org-dblock-end-re nil t)
11184 (> (match-end 0) pos))
11185 (goto-char beg)
11186 (goto-char pos)
11187 (error "Not in a dynamic block"))))
11189 ;;;###autoload
11190 (defun org-update-all-dblocks ()
11191 "Update all dynamic blocks in the buffer.
11192 This function can be used in a hook."
11193 (interactive)
11194 (when (derived-mode-p 'org-mode)
11195 (org-map-dblocks 'org-update-dblock)))
11198 ;;;; Completion
11200 (defconst org-additional-option-like-keywords
11201 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11202 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11203 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11204 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11205 "BEGIN:" "END:"
11206 "ORGTBL" "TBLFM:" "TBLNAME:"
11207 "BEGIN_EXAMPLE" "END_EXAMPLE"
11208 "BEGIN_VERBATIM" "END_VERBATIM"
11209 "BEGIN_QUOTE" "END_QUOTE"
11210 "BEGIN_VERSE" "END_VERSE"
11211 "BEGIN_CENTER" "END_CENTER"
11212 "BEGIN_SRC" "END_SRC"
11213 "BEGIN_RESULT" "END_RESULT"
11214 "BEGIN_lstlisting" "END_lstlisting"
11215 "NAME:" "RESULTS:"
11216 "HEADER:" "HEADERS:"
11217 "COLUMNS:" "PROPERTY:"
11218 "CAPTION:" "LABEL:"
11219 "SETUPFILE:"
11220 "INCLUDE:"
11221 "BIND:"
11222 "MACRO:"))
11224 (defconst org-options-keywords
11225 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11226 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11227 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11228 "LINK_UP:" "LINK_HOME:" "LINK:"
11229 "XSLT:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11230 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:"
11231 "FILETAGS:" "ARCHIVE:"))
11233 (defconst org-additional-option-like-keywords-for-flyspell
11234 (delete-dups
11235 (split-string
11236 (mapconcat (lambda(k)
11237 (replace-regexp-in-string
11238 "_\\|:" " "
11239 (concat k " " (downcase k) " " (upcase k))))
11240 (append org-options-keywords org-additional-option-like-keywords)
11241 " ")
11242 " +" t)))
11244 (defcustom org-structure-template-alist
11246 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11247 "<src lang=\"?\">\n\n</src>")
11248 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11249 "<example>\n?\n</example>")
11250 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11251 "<quote>\n?\n</quote>")
11252 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11253 "<verse>\n?\n</verse>")
11254 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11255 "<center>\n?\n</center>")
11256 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11257 "<literal style=\"latex\">\n?\n</literal>")
11258 ("L" "#+LaTeX: "
11259 "<literal style=\"latex\">?</literal>")
11260 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11261 "<literal style=\"html\">\n?\n</literal>")
11262 ("H" "#+HTML: "
11263 "<literal style=\"html\">?</literal>")
11264 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11265 ("A" "#+ASCII: ")
11266 ("i" "#+INDEX: ?"
11267 "#+INDEX: ?")
11268 ("I" "#+INCLUDE %file ?"
11269 "<include file=%file markup=\"?\">")
11271 "Structure completion elements.
11272 This is a list of abbreviation keys and values. The value gets inserted
11273 if you type `<' followed by the key and then press the completion key,
11274 usually `M-TAB'. %file will be replaced by a file name after prompting
11275 for the file using completion. The cursor will be placed at the position
11276 of the `?` in the template.
11277 There are two templates for each key, the first uses the original Org syntax,
11278 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11279 the default when the /org-mtags.el/ module has been loaded. See also the
11280 variable `org-mtags-prefer-muse-templates'."
11281 :group 'org-completion
11282 :type '(repeat
11283 (string :tag "Key")
11284 (string :tag "Template")
11285 (string :tag "Muse Template")))
11287 (defun org-try-structure-completion ()
11288 "Try to complete a structure template before point.
11289 This looks for strings like \"<e\" on an otherwise empty line and
11290 expands them."
11291 (let ((l (buffer-substring (point-at-bol) (point)))
11293 (when (and (looking-at "[ \t]*$")
11294 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11295 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11296 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11297 (match-beginning 1)) a)
11298 t)))
11300 (defun org-complete-expand-structure-template (start cell)
11301 "Expand a structure template."
11302 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11303 (rpl (nth (if musep 2 1) cell))
11304 (ind ""))
11305 (delete-region start (point))
11306 (when (string-match "\\`#\\+" rpl)
11307 (cond
11308 ((bolp))
11309 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11310 (setq ind (buffer-substring (point-at-bol) (point))))
11311 (t (newline))))
11312 (setq start (point))
11313 (if (string-match "%file" rpl)
11314 (setq rpl (replace-match
11315 (concat
11316 "\""
11317 (save-match-data
11318 (abbreviate-file-name (read-file-name "Include file: ")))
11319 "\"")
11320 t t rpl)))
11321 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11322 (concat "\n" ind)))
11323 (insert rpl)
11324 (if (re-search-backward "\\?" start t) (delete-char 1))))
11326 ;;;; TODO, DEADLINE, Comments
11328 (defun org-toggle-comment ()
11329 "Change the COMMENT state of an entry."
11330 (interactive)
11331 (save-excursion
11332 (org-back-to-heading)
11333 (let (case-fold-search)
11334 (cond
11335 ((looking-at (format org-heading-keyword-regexp-format
11336 org-comment-string))
11337 (goto-char (match-end 1))
11338 (looking-at (concat " +" org-comment-string))
11339 (replace-match "" t t)
11340 (when (eolp) (insert " ")))
11341 ((looking-at org-outline-regexp)
11342 (goto-char (match-end 0))
11343 (insert org-comment-string " "))))))
11345 (defvar org-last-todo-state-is-todo nil
11346 "This is non-nil when the last TODO state change led to a TODO state.
11347 If the last change removed the TODO tag or switched to DONE, then
11348 this is nil.")
11350 (defvar org-setting-tags nil) ; dynamically skipped
11352 (defvar org-todo-setup-filter-hook nil
11353 "Hook for functions that pre-filter todo specs.
11354 Each function takes a todo spec and returns either nil or the spec
11355 transformed into canonical form." )
11357 (defvar org-todo-get-default-hook nil
11358 "Hook for functions that get a default item for todo.
11359 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11360 nil or a string to be used for the todo mark." )
11362 (defvar org-agenda-headline-snapshot-before-repeat)
11364 (defun org-current-effective-time ()
11365 "Return current time adjusted for `org-extend-today-until' variable."
11366 (let* ((ct (org-current-time))
11367 (dct (decode-time ct))
11368 (ct1
11369 (if (and org-use-effective-time
11370 (< (nth 2 dct) org-extend-today-until))
11371 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11372 ct)))
11373 ct1))
11375 (defun org-todo-yesterday (&optional arg)
11376 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11377 (interactive "P")
11378 (if (eq major-mode 'org-agenda-mode)
11379 (apply 'org-agenda-todo-yesterday arg)
11380 (let* ((hour (third (decode-time
11381 (org-current-time))))
11382 (org-extend-today-until (1+ hour)))
11383 (org-todo arg))))
11385 (defun org-todo (&optional arg)
11386 "Change the TODO state of an item.
11387 The state of an item is given by a keyword at the start of the heading,
11388 like
11389 *** TODO Write paper
11390 *** DONE Call mom
11392 The different keywords are specified in the variable `org-todo-keywords'.
11393 By default the available states are \"TODO\" and \"DONE\".
11394 So for this example: when the item starts with TODO, it is changed to DONE.
11395 When it starts with DONE, the DONE is removed. And when neither TODO nor
11396 DONE are present, add TODO at the beginning of the heading.
11398 With \\[universal-argument] prefix arg, use completion to determine the new \
11399 state.
11400 With numeric prefix arg, switch to that state.
11401 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11402 keywords (nextset).
11403 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11404 With a numeric prefix arg of 0, inhibit note taking for the change.
11406 For calling through lisp, arg is also interpreted in the following way:
11407 'none -> empty state
11408 \"\"(empty string) -> switch to empty state
11409 'done -> switch to DONE
11410 'nextset -> switch to the next set of keywords
11411 'previousset -> switch to the previous set of keywords
11412 \"WAITING\" -> switch to the specified keyword, but only if it
11413 really is a member of `org-todo-keywords'."
11414 (interactive "P")
11415 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11416 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11417 'region-start-level 'region))
11418 org-loop-over-headlines-in-active-region)
11419 (org-map-entries
11420 `(org-todo ,arg)
11421 org-loop-over-headlines-in-active-region
11422 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11423 (if (equal arg '(16)) (setq arg 'nextset))
11424 (let ((org-blocker-hook org-blocker-hook)
11425 (case-fold-search nil))
11426 (when (equal arg '(64))
11427 (setq arg nil org-blocker-hook nil))
11428 (when (and org-blocker-hook
11429 (or org-inhibit-blocking
11430 (org-entry-get nil "NOBLOCKING")))
11431 (setq org-blocker-hook nil))
11432 (save-excursion
11433 (catch 'exit
11434 (org-back-to-heading t)
11435 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11436 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11437 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11438 (let* ((match-data (match-data))
11439 (startpos (point-at-bol))
11440 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11441 (org-log-done org-log-done)
11442 (org-log-repeat org-log-repeat)
11443 (org-todo-log-states org-todo-log-states)
11444 (org-inhibit-logging
11445 (if (equal arg 0)
11446 (progn (setq arg nil) 'note) org-inhibit-logging))
11447 (this (match-string 1))
11448 (hl-pos (match-beginning 0))
11449 (head (org-get-todo-sequence-head this))
11450 (ass (assoc head org-todo-kwd-alist))
11451 (interpret (nth 1 ass))
11452 (done-word (nth 3 ass))
11453 (final-done-word (nth 4 ass))
11454 (org-last-state (or this ""))
11455 (completion-ignore-case t)
11456 (member (member this org-todo-keywords-1))
11457 (tail (cdr member))
11458 (org-state (cond
11459 ((and org-todo-key-trigger
11460 (or (and (equal arg '(4))
11461 (eq org-use-fast-todo-selection 'prefix))
11462 (and (not arg) org-use-fast-todo-selection
11463 (not (eq org-use-fast-todo-selection
11464 'prefix)))))
11465 ;; Use fast selection
11466 (org-fast-todo-selection))
11467 ((and (equal arg '(4))
11468 (or (not org-use-fast-todo-selection)
11469 (not org-todo-key-trigger)))
11470 ;; Read a state with completion
11471 (org-icompleting-read
11472 "State: " (mapcar (lambda(x) (list x))
11473 org-todo-keywords-1)
11474 nil t))
11475 ((eq arg 'right)
11476 (if this
11477 (if tail (car tail) nil)
11478 (car org-todo-keywords-1)))
11479 ((eq arg 'left)
11480 (if (equal member org-todo-keywords-1)
11482 (if this
11483 (nth (- (length org-todo-keywords-1)
11484 (length tail) 2)
11485 org-todo-keywords-1)
11486 (org-last org-todo-keywords-1))))
11487 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11488 (setq arg nil))) ; hack to fall back to cycling
11489 (arg
11490 ;; user or caller requests a specific state
11491 (cond
11492 ((equal arg "") nil)
11493 ((eq arg 'none) nil)
11494 ((eq arg 'done) (or done-word (car org-done-keywords)))
11495 ((eq arg 'nextset)
11496 (or (car (cdr (member head org-todo-heads)))
11497 (car org-todo-heads)))
11498 ((eq arg 'previousset)
11499 (let ((org-todo-heads (reverse org-todo-heads)))
11500 (or (car (cdr (member head org-todo-heads)))
11501 (car org-todo-heads))))
11502 ((car (member arg org-todo-keywords-1)))
11503 ((stringp arg)
11504 (error "State `%s' not valid in this file" arg))
11505 ((nth (1- (prefix-numeric-value arg))
11506 org-todo-keywords-1))))
11507 ((null member) (or head (car org-todo-keywords-1)))
11508 ((equal this final-done-word) nil) ;; -> make empty
11509 ((null tail) nil) ;; -> first entry
11510 ((memq interpret '(type priority))
11511 (if (eq this-command last-command)
11512 (car tail)
11513 (if (> (length tail) 0)
11514 (or done-word (car org-done-keywords))
11515 nil)))
11517 (car tail))))
11518 (org-state (or
11519 (run-hook-with-args-until-success
11520 'org-todo-get-default-hook org-state org-last-state)
11521 org-state))
11522 (next (if org-state (concat " " org-state " ") " "))
11523 (change-plist (list :type 'todo-state-change :from this :to org-state
11524 :position startpos))
11525 dolog now-done-p)
11526 (when org-blocker-hook
11527 (setq org-last-todo-state-is-todo
11528 (not (member this org-done-keywords)))
11529 (unless (save-excursion
11530 (save-match-data
11531 (org-with-wide-buffer
11532 (run-hook-with-args-until-failure
11533 'org-blocker-hook change-plist))))
11534 (if (org-called-interactively-p 'interactive)
11535 (error "TODO state change from %s to %s blocked" this org-state)
11536 ;; fail silently
11537 (message "TODO state change from %s to %s blocked" this org-state)
11538 (throw 'exit nil))))
11539 (store-match-data match-data)
11540 (replace-match next t t)
11541 (unless (pos-visible-in-window-p hl-pos)
11542 (message "TODO state changed to %s" (org-trim next)))
11543 (unless head
11544 (setq head (org-get-todo-sequence-head org-state)
11545 ass (assoc head org-todo-kwd-alist)
11546 interpret (nth 1 ass)
11547 done-word (nth 3 ass)
11548 final-done-word (nth 4 ass)))
11549 (when (memq arg '(nextset previousset))
11550 (message "Keyword-Set %d/%d: %s"
11551 (- (length org-todo-sets) -1
11552 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11553 (length org-todo-sets)
11554 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11555 (setq org-last-todo-state-is-todo
11556 (not (member org-state org-done-keywords)))
11557 (setq now-done-p (and (member org-state org-done-keywords)
11558 (not (member this org-done-keywords))))
11559 (and logging (org-local-logging logging))
11560 (when (and (or org-todo-log-states org-log-done)
11561 (not (eq org-inhibit-logging t))
11562 (not (memq arg '(nextset previousset))))
11563 ;; we need to look at recording a time and note
11564 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11565 (nth 2 (assoc this org-todo-log-states))))
11566 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11567 (setq dolog 'time))
11568 (when (and org-state
11569 (member org-state org-not-done-keywords)
11570 (not (member this org-not-done-keywords)))
11571 ;; This is now a todo state and was not one before
11572 ;; If there was a CLOSED time stamp, get rid of it.
11573 (org-add-planning-info nil nil 'closed))
11574 (when (and now-done-p org-log-done)
11575 ;; It is now done, and it was not done before
11576 (org-add-planning-info 'closed (org-current-effective-time))
11577 (if (and (not dolog) (eq 'note org-log-done))
11578 (org-add-log-setup 'done org-state this 'findpos 'note)))
11579 (when (and org-state dolog)
11580 ;; This is a non-nil state, and we need to log it
11581 (org-add-log-setup 'state org-state this 'findpos dolog)))
11582 ;; Fixup tag positioning
11583 (org-todo-trigger-tag-changes org-state)
11584 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11585 (when org-provide-todo-statistics
11586 (org-update-parent-todo-statistics))
11587 (run-hooks 'org-after-todo-state-change-hook)
11588 (if (and arg (not (member org-state org-done-keywords)))
11589 (setq head (org-get-todo-sequence-head org-state)))
11590 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11591 ;; Do we need to trigger a repeat?
11592 (when now-done-p
11593 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11594 ;; This is for the agenda, take a snapshot of the headline.
11595 (save-match-data
11596 (setq org-agenda-headline-snapshot-before-repeat
11597 (org-get-heading))))
11598 (org-auto-repeat-maybe org-state))
11599 ;; Fixup cursor location if close to the keyword
11600 (if (and (outline-on-heading-p)
11601 (not (bolp))
11602 (save-excursion (beginning-of-line 1)
11603 (looking-at org-todo-line-regexp))
11604 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11605 (progn
11606 (goto-char (or (match-end 2) (match-end 1)))
11607 (and (looking-at " ") (just-one-space))))
11608 (when org-trigger-hook
11609 (save-excursion
11610 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11612 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11613 "Block turning an entry into a TODO, using the hierarchy.
11614 This checks whether the current task should be blocked from state
11615 changes. Such blocking occurs when:
11617 1. The task has children which are not all in a completed state.
11619 2. A task has a parent with the property :ORDERED:, and there
11620 are siblings prior to the current task with incomplete
11621 status.
11623 3. The parent of the task is blocked because it has siblings that should
11624 be done first, or is child of a block grandparent TODO entry."
11626 (if (not org-enforce-todo-dependencies)
11627 t ; if locally turned off don't block
11628 (catch 'dont-block
11629 ;; If this is not a todo state change, or if this entry is already DONE,
11630 ;; do not block
11631 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11632 (member (plist-get change-plist :from)
11633 (cons 'done org-done-keywords))
11634 (member (plist-get change-plist :to)
11635 (cons 'todo org-not-done-keywords))
11636 (not (plist-get change-plist :to)))
11637 (throw 'dont-block t))
11638 ;; If this task has children, and any are undone, it's blocked
11639 (save-excursion
11640 (org-back-to-heading t)
11641 (let ((this-level (funcall outline-level)))
11642 (outline-next-heading)
11643 (let ((child-level (funcall outline-level)))
11644 (while (and (not (eobp))
11645 (> child-level this-level))
11646 ;; this todo has children, check whether they are all
11647 ;; completed
11648 (if (and (not (org-entry-is-done-p))
11649 (org-entry-is-todo-p))
11650 (throw 'dont-block nil))
11651 (outline-next-heading)
11652 (setq child-level (funcall outline-level))))))
11653 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11654 ;; any previous siblings are undone, it's blocked
11655 (save-excursion
11656 (org-back-to-heading t)
11657 (let* ((pos (point))
11658 (parent-pos (and (org-up-heading-safe) (point))))
11659 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11660 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11661 (forward-line 1)
11662 (re-search-forward org-not-done-heading-regexp pos t))
11663 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11664 ;; Search further up the hierarchy, to see if an ancestor is blocked
11665 (while t
11666 (goto-char parent-pos)
11667 (if (not (looking-at org-not-done-heading-regexp))
11668 (throw 'dont-block t)) ; do not block, parent is not a TODO
11669 (setq pos (point))
11670 (setq parent-pos (and (org-up-heading-safe) (point)))
11671 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11672 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11673 (forward-line 1)
11674 (re-search-forward org-not-done-heading-regexp pos t))
11675 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11677 (defcustom org-track-ordered-property-with-tag nil
11678 "Should the ORDERED property also be shown as a tag?
11679 The ORDERED property decides if an entry should require subtasks to be
11680 completed in sequence. Since a property is not very visible, setting
11681 this option means that toggling the ORDERED property with the command
11682 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11683 not relevant for the behavior, but it makes things more visible.
11685 Note that toggling the tag with tags commands will not change the property
11686 and therefore not influence behavior!
11688 This can be t, meaning the tag ORDERED should be used, It can also be a
11689 string to select a different tag for this task."
11690 :group 'org-todo
11691 :type '(choice
11692 (const :tag "No tracking" nil)
11693 (const :tag "Track with ORDERED tag" t)
11694 (string :tag "Use other tag")))
11696 (defun org-toggle-ordered-property ()
11697 "Toggle the ORDERED property of the current entry.
11698 For better visibility, you can track the value of this property with a tag.
11699 See variable `org-track-ordered-property-with-tag'."
11700 (interactive)
11701 (let* ((t1 org-track-ordered-property-with-tag)
11702 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11703 (save-excursion
11704 (org-back-to-heading)
11705 (if (org-entry-get nil "ORDERED")
11706 (progn
11707 (org-delete-property "ORDERED")
11708 (and tag (org-toggle-tag tag 'off))
11709 (message "Subtasks can be completed in arbitrary order"))
11710 (org-entry-put nil "ORDERED" "t")
11711 (and tag (org-toggle-tag tag 'on))
11712 (message "Subtasks must be completed in sequence")))))
11714 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11715 (defun org-block-todo-from-checkboxes (change-plist)
11716 "Block turning an entry into a TODO, using checkboxes.
11717 This checks whether the current task should be blocked from state
11718 changes because there are unchecked boxes in this entry."
11719 (if (not org-enforce-todo-checkbox-dependencies)
11720 t ; if locally turned off don't block
11721 (catch 'dont-block
11722 ;; If this is not a todo state change, or if this entry is already DONE,
11723 ;; do not block
11724 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11725 (member (plist-get change-plist :from)
11726 (cons 'done org-done-keywords))
11727 (member (plist-get change-plist :to)
11728 (cons 'todo org-not-done-keywords))
11729 (not (plist-get change-plist :to)))
11730 (throw 'dont-block t))
11731 ;; If this task has checkboxes that are not checked, it's blocked
11732 (save-excursion
11733 (org-back-to-heading t)
11734 (let ((beg (point)) end)
11735 (outline-next-heading)
11736 (setq end (point))
11737 (goto-char beg)
11738 (if (org-list-search-forward
11739 (concat (org-item-beginning-re)
11740 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11741 "\\[[- ]\\]")
11742 end t)
11743 (progn
11744 (if (boundp 'org-blocked-by-checkboxes)
11745 (setq org-blocked-by-checkboxes t))
11746 (throw 'dont-block nil)))))
11747 t))) ; do not block
11749 (defun org-entry-blocked-p ()
11750 "Is the current entry blocked?"
11751 (if (org-entry-get nil "NOBLOCKING")
11752 nil ;; Never block this entry
11753 (not
11754 (run-hook-with-args-until-failure
11755 'org-blocker-hook
11756 (list :type 'todo-state-change
11757 :position (point)
11758 :from 'todo
11759 :to 'done)))))
11761 (defun org-update-statistics-cookies (all)
11762 "Update the statistics cookie, either from TODO or from checkboxes.
11763 This should be called with the cursor in a line with a statistics cookie."
11764 (interactive "P")
11765 (if all
11766 (progn
11767 (org-update-checkbox-count 'all)
11768 (org-map-entries 'org-update-parent-todo-statistics))
11769 (if (not (org-at-heading-p))
11770 (org-update-checkbox-count)
11771 (let ((pos (move-marker (make-marker) (point)))
11772 end l1 l2)
11773 (ignore-errors (org-back-to-heading t))
11774 (if (not (org-at-heading-p))
11775 (org-update-checkbox-count)
11776 (setq l1 (org-outline-level))
11777 (setq end (save-excursion
11778 (outline-next-heading)
11779 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11780 (point)))
11781 (if (and (save-excursion
11782 (re-search-forward
11783 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11784 (not (save-excursion (re-search-forward
11785 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11786 (org-update-checkbox-count)
11787 (if (and l2 (> l2 l1))
11788 (progn
11789 (goto-char end)
11790 (org-update-parent-todo-statistics))
11791 (goto-char pos)
11792 (beginning-of-line 1)
11793 (while (re-search-forward
11794 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11795 (point-at-eol) t)
11796 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11797 (goto-char pos)
11798 (move-marker pos nil)))))
11800 (defvar org-entry-property-inherited-from) ;; defined below
11801 (defun org-update-parent-todo-statistics ()
11802 "Update any statistics cookie in the parent of the current headline.
11803 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11804 the entire subtree and this will travel up the hierarchy and update
11805 statistics everywhere."
11806 (let* ((prop (save-excursion (org-up-heading-safe)
11807 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11808 (recursive (or (not org-hierarchical-todo-statistics)
11809 (and prop (string-match "\\<recursive\\>" prop))))
11810 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11812 (first t)
11813 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11814 level ltoggle l1 new ndel
11815 (cnt-all 0) (cnt-done 0) is-percent kwd
11816 checkbox-beg ov ovs ove cookie-present)
11817 (catch 'exit
11818 (save-excursion
11819 (beginning-of-line 1)
11820 (setq ltoggle (funcall outline-level))
11821 ;; Three situations are to consider:
11823 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11824 ;; to the top-level ancestor on the headline;
11826 ;; 2. If parent has "recursive" property, repeat up to the
11827 ;; headline setting that property, taking inheritance into
11828 ;; account;
11830 ;; 3. Else, move up to direct parent and proceed only once.
11831 (while (and (setq level (org-up-heading-safe))
11832 (or recursive first)
11833 (>= (point) lim))
11834 (setq first nil cookie-present nil)
11835 (unless (and level
11836 (not (string-match
11837 "\\<checkbox\\>"
11838 (downcase (or (org-entry-get nil "COOKIE_DATA")
11839 "")))))
11840 (throw 'exit nil))
11841 (while (re-search-forward box-re (point-at-eol) t)
11842 (setq cnt-all 0 cnt-done 0 cookie-present t)
11843 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11844 (save-match-data
11845 (unless (outline-next-heading) (throw 'exit nil))
11846 (while (and (looking-at org-complex-heading-regexp)
11847 (> (setq l1 (length (match-string 1))) level))
11848 (setq kwd (and (or recursive (= l1 ltoggle))
11849 (match-string 2)))
11850 (if (or (eq org-provide-todo-statistics 'all-headlines)
11851 (and (listp org-provide-todo-statistics)
11852 (or (member kwd org-provide-todo-statistics)
11853 (member kwd org-done-keywords))))
11854 (setq cnt-all (1+ cnt-all))
11855 (if (eq org-provide-todo-statistics t)
11856 (and kwd (setq cnt-all (1+ cnt-all)))))
11857 (and (member kwd org-done-keywords)
11858 (setq cnt-done (1+ cnt-done)))
11859 (outline-next-heading)))
11860 (setq new
11861 (if is-percent
11862 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11863 (format "[%d/%d]" cnt-done cnt-all))
11864 ndel (- (match-end 0) checkbox-beg))
11865 ;; handle overlays when updating cookie from column view
11866 (when (setq ov (car (overlays-at checkbox-beg)))
11867 (setq ovs (overlay-start ov) ove (overlay-end ov))
11868 (delete-overlay ov))
11869 (goto-char checkbox-beg)
11870 (insert new)
11871 (delete-region (point) (+ (point) ndel))
11872 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11873 (when ov (move-overlay ov ovs ove)))
11874 (when cookie-present
11875 (run-hook-with-args 'org-after-todo-statistics-hook
11876 cnt-done (- cnt-all cnt-done))))))
11877 (run-hooks 'org-todo-statistics-hook)))
11879 (defvar org-after-todo-statistics-hook nil
11880 "Hook that is called after a TODO statistics cookie has been updated.
11881 Each function is called with two arguments: the number of not-done entries
11882 and the number of done entries.
11884 For example, the following function, when added to this hook, will switch
11885 an entry to DONE when all children are done, and back to TODO when new
11886 entries are set to a TODO status. Note that this hook is only called
11887 when there is a statistics cookie in the headline!
11889 (defun org-summary-todo (n-done n-not-done)
11890 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11891 (let (org-log-done org-log-states) ; turn off logging
11892 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11895 (defvar org-todo-statistics-hook nil
11896 "Hook that is run whenever Org thinks TODO statistics should be updated.
11897 This hook runs even if there is no statistics cookie present, in which case
11898 `org-after-todo-statistics-hook' would not run.")
11900 (defun org-todo-trigger-tag-changes (state)
11901 "Apply the changes defined in `org-todo-state-tags-triggers'."
11902 (let ((l org-todo-state-tags-triggers)
11903 changes)
11904 (when (or (not state) (equal state ""))
11905 (setq changes (append changes (cdr (assoc "" l)))))
11906 (when (and (stringp state) (> (length state) 0))
11907 (setq changes (append changes (cdr (assoc state l)))))
11908 (when (member state org-not-done-keywords)
11909 (setq changes (append changes (cdr (assoc 'todo l)))))
11910 (when (member state org-done-keywords)
11911 (setq changes (append changes (cdr (assoc 'done l)))))
11912 (dolist (c changes)
11913 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11915 (defun org-local-logging (value)
11916 "Get logging settings from a property VALUE."
11917 (let* (words w a)
11918 ;; directly set the variables, they are already local.
11919 (setq org-log-done nil
11920 org-log-repeat nil
11921 org-todo-log-states nil)
11922 (setq words (org-split-string value))
11923 (while (setq w (pop words))
11924 (cond
11925 ((setq a (assoc w org-startup-options))
11926 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11927 (set (nth 1 a) (nth 2 a))))
11928 ((setq a (org-extract-log-state-settings w))
11929 (and (member (car a) org-todo-keywords-1)
11930 (push a org-todo-log-states)))))))
11932 (defun org-get-todo-sequence-head (kwd)
11933 "Return the head of the TODO sequence to which KWD belongs.
11934 If KWD is not set, check if there is a text property remembering the
11935 right sequence."
11936 (let (p)
11937 (cond
11938 ((not kwd)
11939 (or (get-text-property (point-at-bol) 'org-todo-head)
11940 (progn
11941 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11942 nil (point-at-eol)))
11943 (get-text-property p 'org-todo-head))))
11944 ((not (member kwd org-todo-keywords-1))
11945 (car org-todo-keywords-1))
11946 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11948 (defun org-fast-todo-selection ()
11949 "Fast TODO keyword selection with single keys.
11950 Returns the new TODO keyword, or nil if no state change should occur."
11951 (let* ((fulltable org-todo-key-alist)
11952 (done-keywords org-done-keywords) ;; needed for the faces.
11953 (maxlen (apply 'max (mapcar
11954 (lambda (x)
11955 (if (stringp (car x)) (string-width (car x)) 0))
11956 fulltable)))
11957 (expert nil)
11958 (fwidth (+ maxlen 3 1 3))
11959 (ncol (/ (- (window-width) 4) fwidth))
11960 tg cnt e c tbl
11961 groups ingroup)
11962 (save-excursion
11963 (save-window-excursion
11964 (if expert
11965 (set-buffer (get-buffer-create " *Org todo*"))
11966 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11967 (erase-buffer)
11968 (org-set-local 'org-done-keywords done-keywords)
11969 (setq tbl fulltable cnt 0)
11970 (while (setq e (pop tbl))
11971 (cond
11972 ((equal e '(:startgroup))
11973 (push '() groups) (setq ingroup t)
11974 (when (not (= cnt 0))
11975 (setq cnt 0)
11976 (insert "\n"))
11977 (insert "{ "))
11978 ((equal e '(:endgroup))
11979 (setq ingroup nil cnt 0)
11980 (insert "}\n"))
11981 ((equal e '(:newline))
11982 (when (not (= cnt 0))
11983 (setq cnt 0)
11984 (insert "\n")
11985 (setq e (car tbl))
11986 (while (equal (car tbl) '(:newline))
11987 (insert "\n")
11988 (setq tbl (cdr tbl)))))
11990 (setq tg (car e) c (cdr e))
11991 (if ingroup (push tg (car groups)))
11992 (setq tg (org-add-props tg nil 'face
11993 (org-get-todo-face tg)))
11994 (if (and (= cnt 0) (not ingroup)) (insert " "))
11995 (insert "[" c "] " tg (make-string
11996 (- fwidth 4 (length tg)) ?\ ))
11997 (when (= (setq cnt (1+ cnt)) ncol)
11998 (insert "\n")
11999 (if ingroup (insert " "))
12000 (setq cnt 0)))))
12001 (insert "\n")
12002 (goto-char (point-min))
12003 (if (not expert) (org-fit-window-to-buffer))
12004 (message "[a-z..]:Set [SPC]:clear")
12005 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12006 (cond
12007 ((or (= c ?\C-g)
12008 (and (= c ?q) (not (rassoc c fulltable))))
12009 (setq quit-flag t))
12010 ((= c ?\ ) nil)
12011 ((setq e (rassoc c fulltable) tg (car e))
12013 (t (setq quit-flag t)))))))
12015 (defun org-entry-is-todo-p ()
12016 (member (org-get-todo-state) org-not-done-keywords))
12018 (defun org-entry-is-done-p ()
12019 (member (org-get-todo-state) org-done-keywords))
12021 (defun org-get-todo-state ()
12022 (save-excursion
12023 (org-back-to-heading t)
12024 (and (looking-at org-todo-line-regexp)
12025 (match-end 2)
12026 (match-string 2))))
12028 (defun org-at-date-range-p (&optional inactive-ok)
12029 "Is the cursor inside a date range?"
12030 (interactive)
12031 (save-excursion
12032 (catch 'exit
12033 (let ((pos (point)))
12034 (skip-chars-backward "^[<\r\n")
12035 (skip-chars-backward "<[")
12036 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12037 (>= (match-end 0) pos)
12038 (throw 'exit t))
12039 (skip-chars-backward "^<[\r\n")
12040 (skip-chars-backward "<[")
12041 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12042 (>= (match-end 0) pos)
12043 (throw 'exit t)))
12044 nil)))
12046 (defun org-get-repeat (&optional tagline)
12047 "Check if there is a deadline/schedule with repeater in this entry."
12048 (save-match-data
12049 (save-excursion
12050 (org-back-to-heading t)
12051 (and (re-search-forward (if tagline
12052 (concat tagline "\\s-*" org-repeat-re)
12053 org-repeat-re)
12054 (org-entry-end-position) t)
12055 (match-string-no-properties 1)))))
12057 (defvar org-last-changed-timestamp)
12058 (defvar org-last-inserted-timestamp)
12059 (defvar org-log-post-message)
12060 (defvar org-log-note-purpose)
12061 (defvar org-log-note-how)
12062 (defvar org-log-note-extra)
12063 (defun org-auto-repeat-maybe (done-word)
12064 "Check if the current headline contains a repeated deadline/schedule.
12065 If yes, set TODO state back to what it was and change the base date
12066 of repeating deadline/scheduled time stamps to new date.
12067 This function is run automatically after each state change to a DONE state."
12068 ;; last-state is dynamically scoped into this function
12069 (let* ((repeat (org-get-repeat))
12070 (aa (assoc org-last-state org-todo-kwd-alist))
12071 (interpret (nth 1 aa))
12072 (head (nth 2 aa))
12073 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12074 (msg "Entry repeats: ")
12075 (org-log-done nil)
12076 (org-todo-log-states nil)
12077 re type n what ts time to-state)
12078 (when repeat
12079 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12080 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12081 org-todo-repeat-to-state))
12082 (unless (and to-state (member to-state org-todo-keywords-1))
12083 (setq to-state (if (eq interpret 'type) org-last-state head)))
12084 (org-todo to-state)
12085 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12086 (org-entry-put nil "LAST_REPEAT" (format-time-string
12087 (org-time-stamp-format t t))))
12088 (when org-log-repeat
12089 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12090 (memq 'org-add-log-note post-command-hook))
12091 ;; OK, we are already setup for some record
12092 (if (eq org-log-repeat 'note)
12093 ;; make sure we take a note, not only a time stamp
12094 (setq org-log-note-how 'note))
12095 ;; Set up for taking a record
12096 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12097 org-last-state
12098 'findpos org-log-repeat)))
12099 (org-back-to-heading t)
12100 (org-add-planning-info nil nil 'closed)
12101 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12102 org-deadline-time-regexp "\\)\\|\\("
12103 org-ts-regexp "\\)"))
12104 (while (re-search-forward
12105 re (save-excursion (outline-next-heading) (point)) t)
12106 (setq type (if (match-end 1) org-scheduled-string
12107 (if (match-end 3) org-deadline-string "Plain:"))
12108 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12109 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12110 (setq n (string-to-number (match-string 2 ts))
12111 what (match-string 3 ts))
12112 (if (equal what "w") (setq n (* n 7) what "d"))
12113 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12114 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12115 ;; Preparation, see if we need to modify the start date for the change
12116 (when (match-end 1)
12117 (setq time (save-match-data (org-time-string-to-time ts)))
12118 (cond
12119 ((equal (match-string 1 ts) ".")
12120 ;; Shift starting date to today
12121 (org-timestamp-change
12122 (- (org-today) (time-to-days time))
12123 'day))
12124 ((equal (match-string 1 ts) "+")
12125 (let ((nshiftmax 10) (nshift 0))
12126 (while (or (= nshift 0)
12127 (<= (time-to-days time)
12128 (time-to-days (current-time))))
12129 (when (= (incf nshift) nshiftmax)
12130 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12131 (error "Abort")))
12132 (org-timestamp-change n (cdr (assoc what whata)))
12133 (org-at-timestamp-p t)
12134 (setq ts (match-string 1))
12135 (setq time (save-match-data (org-time-string-to-time ts)))))
12136 (org-timestamp-change (- n) (cdr (assoc what whata)))
12137 ;; rematch, so that we have everything in place for the real shift
12138 (org-at-timestamp-p t)
12139 (setq ts (match-string 1))
12140 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12141 (org-timestamp-change n (cdr (assoc what whata)))
12142 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12143 (setq org-log-post-message msg)
12144 (message "%s" msg))))
12146 (defun org-show-todo-tree (arg)
12147 "Make a compact tree which shows all headlines marked with TODO.
12148 The tree will show the lines where the regexp matches, and all higher
12149 headlines above the match.
12150 With a \\[universal-argument] prefix, prompt for a regexp to match.
12151 With a numeric prefix N, construct a sparse tree for the Nth element
12152 of `org-todo-keywords-1'."
12153 (interactive "P")
12154 (let ((case-fold-search nil)
12155 (kwd-re
12156 (cond ((null arg) org-not-done-regexp)
12157 ((equal arg '(4))
12158 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12159 (mapcar 'list org-todo-keywords-1))))
12160 (concat "\\("
12161 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12162 "\\)\\>")))
12163 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12164 (regexp-quote (nth (1- (prefix-numeric-value arg))
12165 org-todo-keywords-1)))
12166 (t (error "Invalid prefix argument: %s" arg)))))
12167 (message "%d TODO entries found"
12168 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12170 (defun org-deadline (&optional remove time)
12171 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12172 With argument REMOVE, remove any deadline from the item.
12173 With argument TIME, set the deadline at the corresponding date. TIME
12174 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12175 (interactive "P")
12176 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12177 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12178 'region-start-level 'region))
12179 org-loop-over-headlines-in-active-region)
12180 (org-map-entries
12181 `(org-deadline ',remove ,time)
12182 org-loop-over-headlines-in-active-region
12183 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12184 (let* ((old-date (org-entry-get nil "DEADLINE"))
12185 (repeater (and old-date
12186 (string-match
12187 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12188 old-date)
12189 (match-string 1 old-date))))
12190 (if remove
12191 (progn
12192 (when (and old-date org-log-redeadline)
12193 (org-add-log-setup 'deldeadline nil old-date 'findpos
12194 org-log-redeadline))
12195 (org-remove-timestamp-with-keyword org-deadline-string)
12196 (message "Item no longer has a deadline."))
12197 (org-add-planning-info 'deadline time 'closed)
12198 (when (and old-date org-log-redeadline
12199 (not (equal old-date
12200 (substring org-last-inserted-timestamp 1 -1))))
12201 (org-add-log-setup 'redeadline nil old-date 'findpos
12202 org-log-redeadline))
12203 (when repeater
12204 (save-excursion
12205 (org-back-to-heading t)
12206 (when (re-search-forward (concat org-deadline-string " "
12207 org-last-inserted-timestamp)
12208 (save-excursion
12209 (outline-next-heading) (point)) t)
12210 (goto-char (1- (match-end 0)))
12211 (insert " " repeater)
12212 (setq org-last-inserted-timestamp
12213 (concat (substring org-last-inserted-timestamp 0 -1)
12214 " " repeater
12215 (substring org-last-inserted-timestamp -1))))))
12216 (message "Deadline on %s" org-last-inserted-timestamp)))))
12218 (defun org-schedule (&optional remove time)
12219 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12220 With argument REMOVE, remove any scheduling date from the item.
12221 With argument TIME, scheduled at the corresponding date. TIME can
12222 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12223 (interactive "P")
12224 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12225 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12226 'region-start-level 'region))
12227 org-loop-over-headlines-in-active-region)
12228 (org-map-entries
12229 `(org-schedule ',remove ,time)
12230 org-loop-over-headlines-in-active-region
12231 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12232 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12233 (repeater (and old-date
12234 (string-match
12235 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12236 old-date)
12237 (match-string 1 old-date))))
12238 (if remove
12239 (progn
12240 (when (and old-date org-log-reschedule)
12241 (org-add-log-setup 'delschedule nil old-date 'findpos
12242 org-log-reschedule))
12243 (org-remove-timestamp-with-keyword org-scheduled-string)
12244 (message "Item is no longer scheduled."))
12245 (org-add-planning-info 'scheduled time 'closed)
12246 (when (and old-date org-log-reschedule
12247 (not (equal old-date
12248 (substring org-last-inserted-timestamp 1 -1))))
12249 (org-add-log-setup 'reschedule nil old-date 'findpos
12250 org-log-reschedule))
12251 (when repeater
12252 (save-excursion
12253 (org-back-to-heading t)
12254 (when (re-search-forward (concat org-scheduled-string " "
12255 org-last-inserted-timestamp)
12256 (save-excursion
12257 (outline-next-heading) (point)) t)
12258 (goto-char (1- (match-end 0)))
12259 (insert " " repeater)
12260 (setq org-last-inserted-timestamp
12261 (concat (substring org-last-inserted-timestamp 0 -1)
12262 " " repeater
12263 (substring org-last-inserted-timestamp -1))))))
12264 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12266 (defun org-get-scheduled-time (pom &optional inherit)
12267 "Get the scheduled time as a time tuple, of a format suitable
12268 for calling org-schedule with, or if there is no scheduling,
12269 returns nil."
12270 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12271 (when time
12272 (apply 'encode-time (org-parse-time-string time)))))
12274 (defun org-get-deadline-time (pom &optional inherit)
12275 "Get the deadline as a time tuple, of a format suitable for
12276 calling org-deadline with, or if there is no scheduling, returns
12277 nil."
12278 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12279 (when time
12280 (apply 'encode-time (org-parse-time-string time)))))
12282 (defun org-remove-timestamp-with-keyword (keyword)
12283 "Remove all time stamps with KEYWORD in the current entry."
12284 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12285 beg)
12286 (save-excursion
12287 (org-back-to-heading t)
12288 (setq beg (point))
12289 (outline-next-heading)
12290 (while (re-search-backward re beg t)
12291 (replace-match "")
12292 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12293 (equal (char-before) ?\ ))
12294 (backward-delete-char 1)
12295 (if (string-match "^[ \t]*$" (buffer-substring
12296 (point-at-bol) (point-at-eol)))
12297 (delete-region (point-at-bol)
12298 (min (point-max) (1+ (point-at-eol))))))))))
12300 (defun org-add-planning-info (what &optional time &rest remove)
12301 "Insert new timestamp with keyword in the line directly after the headline.
12302 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12303 If non is given, the user is prompted for a date.
12304 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12305 be removed."
12306 (interactive)
12307 (let (org-time-was-given org-end-time-was-given ts
12308 end default-time default-input)
12310 (catch 'exit
12311 (when (and (memq what '(scheduled deadline))
12312 (or (not time)
12313 (and (stringp time)
12314 (string-match "^[-+]+[0-9]" time))))
12315 ;; Try to get a default date/time from existing timestamp
12316 (save-excursion
12317 (org-back-to-heading t)
12318 (setq end (save-excursion (outline-next-heading) (point)))
12319 (when (re-search-forward (if (eq what 'scheduled)
12320 org-scheduled-time-regexp
12321 org-deadline-time-regexp)
12322 end t)
12323 (setq ts (match-string 1)
12324 default-time
12325 (apply 'encode-time (org-parse-time-string ts))
12326 default-input (and ts (org-get-compact-tod ts))))))
12327 (when what
12328 (setq time
12329 (if (stringp time)
12330 ;; This is a string (relative or absolute), set proper date
12331 (apply 'encode-time
12332 (org-read-date-analyze
12333 time default-time (decode-time default-time)))
12334 ;; If necessary, get the time from the user
12335 (or time (org-read-date nil 'to-time nil nil
12336 default-time default-input)))))
12338 (when (and org-insert-labeled-timestamps-at-point
12339 (member what '(scheduled deadline)))
12340 (insert
12341 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12342 (org-insert-time-stamp time org-time-was-given
12343 nil nil nil (list org-end-time-was-given))
12344 (setq what nil))
12345 (save-excursion
12346 (save-restriction
12347 (let (col list elt ts buffer-invisibility-spec)
12348 (org-back-to-heading t)
12349 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12350 (goto-char (match-end 1))
12351 (setq col (current-column))
12352 (goto-char (match-end 0))
12353 (if (eobp) (insert "\n") (forward-char 1))
12354 (when (and (not what)
12355 (not (looking-at
12356 (concat "[ \t]*"
12357 org-keyword-time-not-clock-regexp))))
12358 ;; Nothing to add, nothing to remove...... :-)
12359 (throw 'exit nil))
12360 (if (and (not (looking-at org-outline-regexp))
12361 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12362 "[^\r\n]*"))
12363 (not (equal (match-string 1) org-clock-string)))
12364 (narrow-to-region (match-beginning 0) (match-end 0))
12365 (insert-before-markers "\n")
12366 (backward-char 1)
12367 (narrow-to-region (point) (point))
12368 (and org-adapt-indentation (org-indent-to-column col)))
12369 ;; Check if we have to remove something.
12370 (setq list (cons what remove))
12371 (while list
12372 (setq elt (pop list))
12373 (when (or (and (eq elt 'scheduled)
12374 (re-search-forward org-scheduled-time-regexp nil t))
12375 (and (eq elt 'deadline)
12376 (re-search-forward org-deadline-time-regexp nil t))
12377 (and (eq elt 'closed)
12378 (re-search-forward org-closed-time-regexp nil t)))
12379 (replace-match "")
12380 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12381 (and (looking-at "[ \t]+") (replace-match ""))
12382 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12383 (when what
12384 (insert
12385 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12386 (cond ((eq what 'scheduled) org-scheduled-string)
12387 ((eq what 'deadline) org-deadline-string)
12388 ((eq what 'closed) org-closed-string))
12389 " ")
12390 (setq ts (org-insert-time-stamp
12391 time
12392 (or org-time-was-given
12393 (and (eq what 'closed) org-log-done-with-time))
12394 (eq what 'closed)
12395 nil nil (list org-end-time-was-given)))
12396 (insert
12397 (if (not (or (bolp) (eq (char-before) ?\ )
12398 (memq (char-after) '(32 10))
12399 (eobp))) " " ""))
12400 (end-of-line 1))
12401 (goto-char (point-min))
12402 (widen)
12403 (if (and (looking-at "[ \t]*\n")
12404 (equal (char-before) ?\n))
12405 (delete-region (1- (point)) (point-at-eol)))
12406 ts))))))
12408 (defvar org-log-note-marker (make-marker))
12409 (defvar org-log-note-purpose nil)
12410 (defvar org-log-note-state nil)
12411 (defvar org-log-note-previous-state nil)
12412 (defvar org-log-note-how nil)
12413 (defvar org-log-note-extra nil)
12414 (defvar org-log-note-window-configuration nil)
12415 (defvar org-log-note-return-to (make-marker))
12416 (defvar org-log-note-effective-time nil
12417 "Remembered current time so that dynamically scoped
12418 `org-extend-today-until' affects tha timestamps in state change
12419 log")
12421 (defvar org-log-post-message nil
12422 "Message to be displayed after a log note has been stored.
12423 The auto-repeater uses this.")
12425 (defun org-add-note ()
12426 "Add a note to the current entry.
12427 This is done in the same way as adding a state change note."
12428 (interactive)
12429 (org-add-log-setup 'note nil nil 'findpos nil))
12431 (defvar org-property-end-re)
12432 (defun org-add-log-setup (&optional purpose state prev-state
12433 findpos how extra)
12434 "Set up the post command hook to take a note.
12435 If this is about to TODO state change, the new state is expected in STATE.
12436 When FINDPOS is non-nil, find the correct position for the note in
12437 the current entry. If not, assume that it can be inserted at point.
12438 HOW is an indicator what kind of note should be created.
12439 EXTRA is additional text that will be inserted into the notes buffer."
12440 (let* ((org-log-into-drawer (org-log-into-drawer))
12441 (drawer (cond ((stringp org-log-into-drawer)
12442 org-log-into-drawer)
12443 (org-log-into-drawer "LOGBOOK")
12444 (t nil))))
12445 (save-restriction
12446 (save-excursion
12447 (when findpos
12448 (org-back-to-heading t)
12449 (narrow-to-region (point) (save-excursion
12450 (outline-next-heading) (point)))
12451 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12452 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12453 "[^\r\n]*\\)?"))
12454 (goto-char (match-end 0))
12455 (cond
12456 (drawer
12457 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12458 nil t)
12459 (progn
12460 (goto-char (match-end 0))
12461 (or org-log-states-order-reversed
12462 (and (re-search-forward org-property-end-re nil t)
12463 (goto-char (1- (match-beginning 0))))))
12464 (insert "\n:" drawer ":\n:END:")
12465 (beginning-of-line 0)
12466 (org-indent-line)
12467 (beginning-of-line 2)
12468 (org-indent-line)
12469 (end-of-line 0)))
12470 ((and org-log-state-notes-insert-after-drawers
12471 (save-excursion
12472 (forward-line) (looking-at org-drawer-regexp)))
12473 (forward-line)
12474 (while (looking-at org-drawer-regexp)
12475 (goto-char (match-end 0))
12476 (re-search-forward org-property-end-re (point-max) t)
12477 (forward-line))
12478 (forward-line -1)))
12479 (unless org-log-states-order-reversed
12480 (and (= (char-after) ?\n) (forward-char 1))
12481 (org-skip-over-state-notes)
12482 (skip-chars-backward " \t\n\r")))
12483 (move-marker org-log-note-marker (point))
12484 (setq org-log-note-purpose purpose
12485 org-log-note-state state
12486 org-log-note-previous-state prev-state
12487 org-log-note-how how
12488 org-log-note-extra extra
12489 org-log-note-effective-time (org-current-effective-time))
12490 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12492 (defun org-skip-over-state-notes ()
12493 "Skip past the list of State notes in an entry."
12494 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12495 (when (ignore-errors (goto-char (org-in-item-p)))
12496 (let* ((struct (org-list-struct))
12497 (prevs (org-list-prevs-alist struct)))
12498 (while (looking-at "[ \t]*- State")
12499 (goto-char (or (org-list-get-next-item (point) struct prevs)
12500 (org-list-get-item-end (point) struct)))))))
12502 (defun org-add-log-note (&optional purpose)
12503 "Pop up a window for taking a note, and add this note later at point."
12504 (remove-hook 'post-command-hook 'org-add-log-note)
12505 (setq org-log-note-window-configuration (current-window-configuration))
12506 (delete-other-windows)
12507 (move-marker org-log-note-return-to (point))
12508 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12509 (goto-char org-log-note-marker)
12510 (org-switch-to-buffer-other-window "*Org Note*")
12511 (erase-buffer)
12512 (if (memq org-log-note-how '(time state))
12513 (let (current-prefix-arg) (org-store-log-note))
12514 (let ((org-inhibit-startup t)) (org-mode))
12515 (insert (format "# Insert note for %s.
12516 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12517 (cond
12518 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12519 ((eq org-log-note-purpose 'done) "closed todo item")
12520 ((eq org-log-note-purpose 'state)
12521 (format "state change from \"%s\" to \"%s\""
12522 (or org-log-note-previous-state "")
12523 (or org-log-note-state "")))
12524 ((eq org-log-note-purpose 'reschedule)
12525 "rescheduling")
12526 ((eq org-log-note-purpose 'delschedule)
12527 "no longer scheduled")
12528 ((eq org-log-note-purpose 'redeadline)
12529 "changing deadline")
12530 ((eq org-log-note-purpose 'deldeadline)
12531 "removing deadline")
12532 ((eq org-log-note-purpose 'refile)
12533 "refiling")
12534 ((eq org-log-note-purpose 'note)
12535 "this entry")
12536 (t (error "This should not happen")))))
12537 (if org-log-note-extra (insert org-log-note-extra))
12538 (org-set-local 'org-finish-function 'org-store-log-note)
12539 (run-hooks 'org-log-buffer-setup-hook)))
12541 (defvar org-note-abort nil) ; dynamically scoped
12542 (defun org-store-log-note ()
12543 "Finish taking a log note, and insert it to where it belongs."
12544 (let ((txt (buffer-string))
12545 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12546 lines ind bul)
12547 (kill-buffer (current-buffer))
12548 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12549 (setq txt (replace-match "" t t txt)))
12550 (if (string-match "\\s-+\\'" txt)
12551 (setq txt (replace-match "" t t txt)))
12552 (setq lines (org-split-string txt "\n"))
12553 (when (and note (string-match "\\S-" note))
12554 (setq note
12555 (org-replace-escapes
12556 note
12557 (list (cons "%u" (user-login-name))
12558 (cons "%U" user-full-name)
12559 (cons "%t" (format-time-string
12560 (org-time-stamp-format 'long 'inactive)
12561 org-log-note-effective-time))
12562 (cons "%T" (format-time-string
12563 (org-time-stamp-format 'long nil)
12564 org-log-note-effective-time))
12565 (cons "%d" (format-time-string
12566 (org-time-stamp-format nil 'inactive)
12567 org-log-note-effective-time))
12568 (cons "%D" (format-time-string
12569 (org-time-stamp-format nil nil)
12570 org-log-note-effective-time))
12571 (cons "%s" (if org-log-note-state
12572 (concat "\"" org-log-note-state "\"")
12573 ""))
12574 (cons "%S" (if org-log-note-previous-state
12575 (concat "\"" org-log-note-previous-state "\"")
12576 "\"\"")))))
12577 (if lines (setq note (concat note " \\\\")))
12578 (push note lines))
12579 (when (or current-prefix-arg org-note-abort)
12580 (when org-log-into-drawer
12581 (org-remove-empty-drawer-at
12582 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12583 org-log-note-marker))
12584 (setq lines nil))
12585 (when lines
12586 (with-current-buffer (marker-buffer org-log-note-marker)
12587 (save-excursion
12588 (goto-char org-log-note-marker)
12589 (move-marker org-log-note-marker nil)
12590 (end-of-line 1)
12591 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12592 (setq ind (save-excursion
12593 (if (ignore-errors (goto-char (org-in-item-p)))
12594 (let ((struct (org-list-struct)))
12595 (org-list-get-ind
12596 (org-list-get-top-point struct) struct))
12597 (skip-chars-backward " \r\t\n")
12598 (cond
12599 ((and (org-at-heading-p)
12600 org-adapt-indentation)
12601 (1+ (org-current-level)))
12602 ((org-at-heading-p) 0)
12603 (t (org-get-indentation))))))
12604 (setq bul (org-list-bullet-string "-"))
12605 (org-indent-line-to ind)
12606 (insert bul (pop lines))
12607 (let ((ind-body (+ (length bul) ind)))
12608 (while lines
12609 (insert "\n")
12610 (org-indent-line-to ind-body)
12611 (insert (pop lines))))
12612 (message "Note stored")
12613 (org-back-to-heading t)
12614 (org-cycle-hide-drawers 'children)))))
12615 (set-window-configuration org-log-note-window-configuration)
12616 (with-current-buffer (marker-buffer org-log-note-return-to)
12617 (goto-char org-log-note-return-to))
12618 (move-marker org-log-note-return-to nil)
12619 (and org-log-post-message (message "%s" org-log-post-message)))
12621 (defun org-remove-empty-drawer-at (drawer pos)
12622 "Remove an empty drawer DRAWER at position POS.
12623 POS may also be a marker."
12624 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12625 (save-excursion
12626 (save-restriction
12627 (widen)
12628 (goto-char pos)
12629 (if (org-in-regexp
12630 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12631 (replace-match ""))))))
12633 (defvar org-ts-type nil)
12634 (defun org-sparse-tree (&optional arg type)
12635 "Create a sparse tree, prompt for the details.
12636 This command can create sparse trees. You first need to select the type
12637 of match used to create the tree:
12639 t Show all TODO entries.
12640 T Show entries with a specific TODO keyword.
12641 m Show entries selected by a tags/property match.
12642 p Enter a property name and its value (both with completion on existing
12643 names/values) and show entries with that property.
12644 r Show entries matching a regular expression (`/' can be used as well).
12645 b Show deadlines and scheduled items before a date.
12646 a Show deadlines and scheduled items after a date.
12647 d Show deadlines due within `org-deadline-warning-days'.
12648 D Show deadlines and scheduled items between a date range."
12649 (interactive "P")
12650 (let (ans kwd value ts-type)
12651 (setq type (or type org-sparse-tree-default-date-type))
12652 (setq org-ts-type type)
12653 (message "Sparse tree: [r]egexp [/]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"
12654 (cond ((eq type 'all) "all timestamps")
12655 ((eq type 'scheduled) "only scheduled")
12656 ((eq type 'deadline) "only deadline")
12657 ((eq type 'active) "only active timestamps")
12658 ((eq type 'inactive) "only inactive timestamps")
12659 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12660 (t "scheduled/deadline")))
12661 (setq ans (read-char-exclusive))
12662 (cond
12663 ((equal ans ?c)
12664 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12665 ((equal ans ?d)
12666 (call-interactively 'org-check-deadlines))
12667 ((equal ans ?b)
12668 (call-interactively 'org-check-before-date))
12669 ((equal ans ?a)
12670 (call-interactively 'org-check-after-date))
12671 ((equal ans ?D)
12672 (call-interactively 'org-check-dates-range))
12673 ((equal ans ?t)
12674 (org-show-todo-tree nil))
12675 ((equal ans ?T)
12676 (org-show-todo-tree '(4)))
12677 ((member ans '(?T ?m))
12678 (call-interactively 'org-match-sparse-tree))
12679 ((member ans '(?p ?P))
12680 (setq kwd (org-icompleting-read "Property: "
12681 (mapcar 'list (org-buffer-property-keys))))
12682 (setq value (org-icompleting-read "Value: "
12683 (mapcar 'list (org-property-values kwd))))
12684 (unless (string-match "\\`{.*}\\'" value)
12685 (setq value (concat "\"" value "\"")))
12686 (org-match-sparse-tree arg (concat kwd "=" value)))
12687 ((member ans '(?r ?R ?/))
12688 (call-interactively 'org-occur))
12689 (t (error "No such sparse tree command \"%c\"" ans)))))
12691 (defvar org-occur-highlights nil
12692 "List of overlays used for occur matches.")
12693 (make-variable-buffer-local 'org-occur-highlights)
12694 (defvar org-occur-parameters nil
12695 "Parameters of the active org-occur calls.
12696 This is a list, each call to org-occur pushes as cons cell,
12697 containing the regular expression and the callback, onto the list.
12698 The list can contain several entries if `org-occur' has been called
12699 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12700 will only contain one set of parameters. When the highlights are
12701 removed (for example with `C-c C-c', or with the next edit (depending
12702 on `org-remove-highlights-with-change'), this variable is emptied
12703 as well.")
12704 (make-variable-buffer-local 'org-occur-parameters)
12706 (defun org-occur (regexp &optional keep-previous callback)
12707 "Make a compact tree which shows all matches of REGEXP.
12708 The tree will show the lines where the regexp matches, and all higher
12709 headlines above the match. It will also show the heading after the match,
12710 to make sure editing the matching entry is easy.
12711 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12712 call to `org-occur' will be kept, to allow stacking of calls to this
12713 command.
12714 If CALLBACK is non-nil, it is a function which is called to confirm
12715 that the match should indeed be shown."
12716 (interactive "sRegexp: \nP")
12717 (when (equal regexp "")
12718 (error "Regexp cannot be empty"))
12719 (unless keep-previous
12720 (org-remove-occur-highlights nil nil t))
12721 (push (cons regexp callback) org-occur-parameters)
12722 (let ((cnt 0))
12723 (save-excursion
12724 (goto-char (point-min))
12725 (if (or (not keep-previous) ; do not want to keep
12726 (not org-occur-highlights)) ; no previous matches
12727 ;; hide everything
12728 (org-overview))
12729 (while (re-search-forward regexp nil t)
12730 (when (or (not callback)
12731 (save-match-data (funcall callback)))
12732 (setq cnt (1+ cnt))
12733 (when org-highlight-sparse-tree-matches
12734 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12735 (org-show-context 'occur-tree))))
12736 (when org-remove-highlights-with-change
12737 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12738 nil 'local))
12739 (unless org-sparse-tree-open-archived-trees
12740 (org-hide-archived-subtrees (point-min) (point-max)))
12741 (run-hooks 'org-occur-hook)
12742 (if (org-called-interactively-p 'interactive)
12743 (message "%d match(es) for regexp %s" cnt regexp))
12744 cnt))
12746 (defun org-occur-next-match (&optional n reset)
12747 "Function for `next-error-function' to find sparse tree matches.
12748 N is the number of matches to move, when negative move backwards.
12749 RESET is entirely ignored - this function always goes back to the
12750 starting point when no match is found."
12751 (let* ((limit (if (< n 0) (point-min) (point-max)))
12752 (search-func (if (< n 0)
12753 'previous-single-char-property-change
12754 'next-single-char-property-change))
12755 (n (abs n))
12756 (pos (point))
12758 (catch 'exit
12759 (while (setq p1 (funcall search-func (point) 'org-type))
12760 (when (equal p1 limit)
12761 (goto-char pos)
12762 (error "No more matches"))
12763 (when (equal (get-char-property p1 'org-type) 'org-occur)
12764 (setq n (1- n))
12765 (when (= n 0)
12766 (goto-char p1)
12767 (throw 'exit (point))))
12768 (goto-char p1))
12769 (goto-char p1)
12770 (error "No more matches"))))
12772 (defun org-show-context (&optional key)
12773 "Make sure point and context are visible.
12774 How much context is shown depends upon the variables
12775 `org-show-hierarchy-above', `org-show-following-heading',
12776 `org-show-entry-below' and `org-show-siblings'."
12777 (let ((heading-p (org-at-heading-p t))
12778 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12779 (following-p (org-get-alist-option org-show-following-heading key))
12780 (entry-p (org-get-alist-option org-show-entry-below key))
12781 (siblings-p (org-get-alist-option org-show-siblings key)))
12782 (catch 'exit
12783 ;; Show heading or entry text
12784 (if (and heading-p (not entry-p))
12785 (org-flag-heading nil) ; only show the heading
12786 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12787 (org-show-hidden-entry))) ; show entire entry
12788 (when following-p
12789 ;; Show next sibling, or heading below text
12790 (save-excursion
12791 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12792 (org-flag-heading nil))))
12793 (when siblings-p (org-show-siblings))
12794 (when hierarchy-p
12795 ;; show all higher headings, possibly with siblings
12796 (save-excursion
12797 (while (and (condition-case nil
12798 (progn (org-up-heading-all 1) t)
12799 (error nil))
12800 (not (bobp)))
12801 (org-flag-heading nil)
12802 (when siblings-p (org-show-siblings))))))))
12804 (defvar org-reveal-start-hook nil
12805 "Hook run before revealing a location.")
12807 (defun org-reveal (&optional siblings)
12808 "Show current entry, hierarchy above it, and the following headline.
12809 This can be used to show a consistent set of context around locations
12810 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12811 not t for the search context.
12813 With optional argument SIBLINGS, on each level of the hierarchy all
12814 siblings are shown. This repairs the tree structure to what it would
12815 look like when opened with hierarchical calls to `org-cycle'.
12816 With double optional argument \\[universal-argument] \\[universal-argument], \
12817 go to the parent and show the
12818 entire tree."
12819 (interactive "P")
12820 (run-hooks 'org-reveal-start-hook)
12821 (let ((org-show-hierarchy-above t)
12822 (org-show-following-heading t)
12823 (org-show-siblings (if siblings t org-show-siblings)))
12824 (org-show-context nil))
12825 (when (equal siblings '(16))
12826 (save-excursion
12827 (when (org-up-heading-safe)
12828 (org-show-subtree)
12829 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12831 (defun org-highlight-new-match (beg end)
12832 "Highlight from BEG to END and mark the highlight is an occur headline."
12833 (let ((ov (make-overlay beg end)))
12834 (overlay-put ov 'face 'secondary-selection)
12835 (overlay-put ov 'org-type 'org-occur)
12836 (push ov org-occur-highlights)))
12838 (defun org-remove-occur-highlights (&optional beg end noremove)
12839 "Remove the occur highlights from the buffer.
12840 BEG and END are ignored. If NOREMOVE is nil, remove this function
12841 from the `before-change-functions' in the current buffer."
12842 (interactive)
12843 (unless org-inhibit-highlight-removal
12844 (mapc 'delete-overlay org-occur-highlights)
12845 (setq org-occur-highlights nil)
12846 (setq org-occur-parameters nil)
12847 (unless noremove
12848 (remove-hook 'before-change-functions
12849 'org-remove-occur-highlights 'local))))
12851 ;;;; Priorities
12853 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12854 "Regular expression matching the priority indicator.")
12856 (defvar org-remove-priority-next-time nil)
12858 (defun org-priority-up ()
12859 "Increase the priority of the current item."
12860 (interactive)
12861 (org-priority 'up))
12863 (defun org-priority-down ()
12864 "Decrease the priority of the current item."
12865 (interactive)
12866 (org-priority 'down))
12868 (defun org-priority (&optional action)
12869 "Change the priority of an item by ARG.
12870 ACTION can be `set', `up', `down', or a character."
12871 (interactive)
12872 (unless org-enable-priority-commands
12873 (error "Priority commands are disabled"))
12874 (setq action (or action 'set))
12875 (let (current new news have remove)
12876 (save-excursion
12877 (org-back-to-heading t)
12878 (if (looking-at org-priority-regexp)
12879 (setq current (string-to-char (match-string 2))
12880 have t))
12881 (cond
12882 ((eq action 'remove)
12883 (setq remove t new ?\ ))
12884 ((or (eq action 'set)
12885 (if (featurep 'xemacs) (characterp action) (integerp action)))
12886 (if (not (eq action 'set))
12887 (setq new action)
12888 (message "Priority %c-%c, SPC to remove: "
12889 org-highest-priority org-lowest-priority)
12890 (save-match-data
12891 (setq new (read-char-exclusive))))
12892 (if (and (= (upcase org-highest-priority) org-highest-priority)
12893 (= (upcase org-lowest-priority) org-lowest-priority))
12894 (setq new (upcase new)))
12895 (cond ((equal new ?\ ) (setq remove t))
12896 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12897 (error "Priority must be between `%c' and `%c'"
12898 org-highest-priority org-lowest-priority))))
12899 ((eq action 'up)
12900 (setq new (if have
12901 (1- current) ; normal cycling
12902 ;; last priority was empty
12903 (if (eq last-command this-command)
12904 org-lowest-priority ; wrap around empty to lowest
12905 ;; default
12906 (if org-priority-start-cycle-with-default
12907 org-default-priority
12908 (1- org-default-priority))))))
12909 ((eq action 'down)
12910 (setq new (if have
12911 (1+ current) ; normal cycling
12912 ;; last priority was empty
12913 (if (eq last-command this-command)
12914 org-highest-priority ; wrap around empty to highest
12915 ;; default
12916 (if org-priority-start-cycle-with-default
12917 org-default-priority
12918 (1+ org-default-priority))))))
12919 (t (error "Invalid action")))
12920 (if (or (< (upcase new) org-highest-priority)
12921 (> (upcase new) org-lowest-priority))
12922 (if (and (memq action '(up down))
12923 (not have) (not (eq last-command this-command)))
12924 ;; `new' is from default priority
12925 (error
12926 "The default can not be set, see `org-default-priority' why")
12927 ;; normal cycling: `new' is beyond highest/lowest priority
12928 ;; and is wrapped around to the empty priority
12929 (setq remove t)))
12930 (setq news (format "%c" new))
12931 (if have
12932 (if remove
12933 (replace-match "" t t nil 1)
12934 (replace-match news t t nil 2))
12935 (if remove
12936 (error "No priority cookie found in line")
12937 (let ((case-fold-search nil))
12938 (looking-at org-todo-line-regexp))
12939 (if (match-end 2)
12940 (progn
12941 (goto-char (match-end 2))
12942 (insert " [#" news "]"))
12943 (goto-char (match-beginning 3))
12944 (insert "[#" news "] "))))
12945 (org-preserve-lc (org-set-tags nil 'align)))
12946 (if remove
12947 (message "Priority removed")
12948 (message "Priority of current item set to %s" news))))
12950 (defun org-get-priority (s)
12951 "Find priority cookie and return priority."
12952 (if (functionp org-get-priority-function)
12953 (funcall org-get-priority-function)
12954 (save-match-data
12955 (if (not (string-match org-priority-regexp s))
12956 (* 1000 (- org-lowest-priority org-default-priority))
12957 (* 1000 (- org-lowest-priority
12958 (string-to-char (match-string 2 s))))))))
12960 ;;;; Tags
12962 (defvar org-agenda-archives-mode)
12963 (defvar org-map-continue-from nil
12964 "Position from where mapping should continue.
12965 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12967 (defvar org-scanner-tags nil
12968 "The current tag list while the tags scanner is running.")
12969 (defvar org-trust-scanner-tags nil
12970 "Should `org-get-tags-at' use the tags for the scanner.
12971 This is for internal dynamical scoping only.
12972 When this is non-nil, the function `org-get-tags-at' will return the value
12973 of `org-scanner-tags' instead of building the list by itself. This
12974 can lead to large speed-ups when the tags scanner is used in a file with
12975 many entries, and when the list of tags is retrieved, for example to
12976 obtain a list of properties. Building the tags list for each entry in such
12977 a file becomes an N^2 operation - but with this variable set, it scales
12978 as N.")
12980 (defun org-scan-tags (action matcher todo-only &optional start-level)
12981 "Scan headline tags with inheritance and produce output ACTION.
12983 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12984 or `agenda' to produce an entry list for an agenda view. It can also be
12985 a Lisp form or a function that should be called at each matched headline, in
12986 this case the return value is a list of all return values from these calls.
12988 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12989 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12990 only lines with a not-done TODO keyword are included in the output.
12991 This should be the same variable that was scoped into
12992 and set by `org-make-tags-matcher' when it constructed MATCHER.
12994 START-LEVEL can be a string with asterisks, reducing the scope to
12995 headlines matching this string."
12996 (require 'org-agenda)
12997 (let* ((re (concat "^"
12998 (if start-level
12999 ;; Get the correct level to match
13000 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13001 org-outline-regexp)
13002 " *\\(\\<\\("
13003 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13004 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13005 (props (list 'face 'default
13006 'done-face 'org-agenda-done
13007 'undone-face 'default
13008 'mouse-face 'highlight
13009 'org-not-done-regexp org-not-done-regexp
13010 'org-todo-regexp org-todo-regexp
13011 'org-complex-heading-regexp org-complex-heading-regexp
13012 'help-echo
13013 (format "mouse-2 or RET jump to org file %s"
13014 (abbreviate-file-name
13015 (or (buffer-file-name (buffer-base-buffer))
13016 (buffer-name (buffer-base-buffer)))))))
13017 (case-fold-search nil)
13018 (org-map-continue-from nil)
13019 lspos tags tags-list
13020 (tags-alist (list (cons 0 org-file-tags)))
13021 (llast 0) rtn rtn1 level category i txt
13022 todo marker entry priority)
13023 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13024 (setq action (list 'lambda nil action)))
13025 (save-excursion
13026 (goto-char (point-min))
13027 (when (eq action 'sparse-tree)
13028 (org-overview)
13029 (org-remove-occur-highlights))
13030 (while (re-search-forward re nil t)
13031 (setq org-map-continue-from nil)
13032 (catch :skip
13033 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13034 tags (if (match-end 4) (org-match-string-no-properties 4)))
13035 (goto-char (setq lspos (match-beginning 0)))
13036 (setq level (org-reduced-level (funcall outline-level))
13037 category (org-get-category))
13038 (setq i llast llast level)
13039 ;; remove tag lists from same and sublevels
13040 (while (>= i level)
13041 (when (setq entry (assoc i tags-alist))
13042 (setq tags-alist (delete entry tags-alist)))
13043 (setq i (1- i)))
13044 ;; add the next tags
13045 (when tags
13046 (setq tags (org-split-string tags ":")
13047 tags-alist
13048 (cons (cons level tags) tags-alist)))
13049 ;; compile tags for current headline
13050 (setq tags-list
13051 (if org-use-tag-inheritance
13052 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13053 tags)
13054 org-scanner-tags tags-list)
13055 (when org-use-tag-inheritance
13056 (setcdr (car tags-alist)
13057 (mapcar (lambda (x)
13058 (setq x (copy-sequence x))
13059 (org-add-prop-inherited x))
13060 (cdar tags-alist))))
13061 (when (and tags org-use-tag-inheritance
13062 (or (not (eq t org-use-tag-inheritance))
13063 org-tags-exclude-from-inheritance))
13064 ;; selective inheritance, remove uninherited ones
13065 (setcdr (car tags-alist)
13066 (org-remove-uninherited-tags (cdar tags-alist))))
13067 (when (and
13069 ;; eval matcher only when the todo condition is OK
13070 (and (or (not todo-only) (member todo org-not-done-keywords))
13071 (let ((case-fold-search t) (org-trust-scanner-tags t))
13072 (eval matcher)))
13074 ;; Call the skipper, but return t if it does not skip,
13075 ;; so that the `and' form continues evaluating
13076 (progn
13077 (unless (eq action 'sparse-tree) (org-agenda-skip))
13080 ;; Check if timestamps are deselecting this entry
13081 (or (not todo-only)
13082 (and (member todo org-not-done-keywords)
13083 (or (not org-agenda-tags-todo-honor-ignore-options)
13084 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13086 ;; Extra check for the archive tag
13087 ;; FIXME: Does the skipper already do this????
13089 (not (member org-archive-tag tags-list))
13090 ;; we have an archive tag, should we use this anyway?
13091 (or (not org-agenda-skip-archived-trees)
13092 (and (eq action 'agenda) org-agenda-archives-mode))))
13094 ;; select this headline
13096 (cond
13097 ((eq action 'sparse-tree)
13098 (and org-highlight-sparse-tree-matches
13099 (org-get-heading) (match-end 0)
13100 (org-highlight-new-match
13101 (match-beginning 1) (match-end 1)))
13102 (org-show-context 'tags-tree))
13103 ((eq action 'agenda)
13104 (setq txt (org-agenda-format-item
13106 (concat
13107 (if (eq org-tags-match-list-sublevels 'indented)
13108 (make-string (1- level) ?.) "")
13109 (org-get-heading))
13110 category
13111 tags-list)
13112 priority (org-get-priority txt))
13113 (goto-char lspos)
13114 (setq marker (org-agenda-new-marker))
13115 (org-add-props txt props
13116 'org-marker marker 'org-hd-marker marker 'org-category category
13117 'todo-state todo
13118 'priority priority 'type "tagsmatch")
13119 (push txt rtn))
13120 ((functionp action)
13121 (setq org-map-continue-from nil)
13122 (save-excursion
13123 (setq rtn1 (funcall action))
13124 (push rtn1 rtn)))
13125 (t (error "Invalid action")))
13127 ;; if we are to skip sublevels, jump to end of subtree
13128 (unless org-tags-match-list-sublevels
13129 (org-end-of-subtree t)
13130 (backward-char 1))))
13131 ;; Get the correct position from where to continue
13132 (if org-map-continue-from
13133 (goto-char org-map-continue-from)
13134 (and (= (point) lspos) (end-of-line 1)))))
13135 (when (and (eq action 'sparse-tree)
13136 (not org-sparse-tree-open-archived-trees))
13137 (org-hide-archived-subtrees (point-min) (point-max)))
13138 (nreverse rtn)))
13140 (defun org-remove-uninherited-tags (tags)
13141 "Remove all tags that are not inherited from the list TAGS."
13142 (cond
13143 ((eq org-use-tag-inheritance t)
13144 (if org-tags-exclude-from-inheritance
13145 (org-delete-all org-tags-exclude-from-inheritance tags)
13146 tags))
13147 ((not org-use-tag-inheritance) nil)
13148 ((stringp org-use-tag-inheritance)
13149 (delq nil (mapcar
13150 (lambda (x)
13151 (if (and (string-match org-use-tag-inheritance x)
13152 (not (member x org-tags-exclude-from-inheritance)))
13153 x nil))
13154 tags)))
13155 ((listp org-use-tag-inheritance)
13156 (delq nil (mapcar
13157 (lambda (x)
13158 (if (member x org-use-tag-inheritance) x nil))
13159 tags)))))
13161 (defun org-match-sparse-tree (&optional todo-only match)
13162 "Create a sparse tree according to tags string MATCH.
13163 MATCH can contain positive and negative selection of tags, like
13164 \"+WORK+URGENT-WITHBOSS\".
13165 If optional argument TODO-ONLY is non-nil, only select lines that are
13166 also TODO lines."
13167 (interactive "P")
13168 (org-prepare-agenda-buffers (list (current-buffer)))
13169 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13171 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13173 (defvar org-cached-props nil)
13174 (defun org-cached-entry-get (pom property)
13175 (if (or (eq t org-use-property-inheritance)
13176 (and (stringp org-use-property-inheritance)
13177 (string-match org-use-property-inheritance property))
13178 (and (listp org-use-property-inheritance)
13179 (member property org-use-property-inheritance)))
13180 ;; Caching is not possible, check it directly
13181 (org-entry-get pom property 'inherit)
13182 ;; Get all properties, so that we can do complicated checks easily
13183 (cdr (assoc property (or org-cached-props
13184 (setq org-cached-props
13185 (org-entry-properties pom)))))))
13187 (defun org-global-tags-completion-table (&optional files)
13188 "Return the list of all tags in all agenda buffer/files.
13189 Optional FILES argument is a list of files to which can be used
13190 instead of the agenda files."
13191 (save-excursion
13192 (org-uniquify
13193 (delq nil
13194 (apply 'append
13195 (mapcar
13196 (lambda (file)
13197 (set-buffer (find-file-noselect file))
13198 (append (org-get-buffer-tags)
13199 (mapcar (lambda (x) (if (stringp (car-safe x))
13200 (list (car-safe x)) nil))
13201 org-tag-alist)))
13202 (if (and files (car files))
13203 files
13204 (org-agenda-files))))))))
13206 (defun org-make-tags-matcher (match)
13207 "Create the TAGS/TODO matcher form for the selection string MATCH.
13209 The variable `todo-only' is scoped dynamically into this function; it will be
13210 set to t if the matcher restricts matching to TODO entries,
13211 otherwise will not be touched.
13213 Returns a cons of the selection string MATCH and the constructed
13214 lisp form implementing the matcher. The matcher is to be
13215 evaluated at an Org entry, with point on the headline,
13216 and returns t if the entry matches the
13217 selection string MATCH. The returned lisp form references
13218 two variables with information about the entry, which must be
13219 bound around the form's evaluation: todo, the TODO keyword at the
13220 entry (or nil of none); and tags-list, the list of all tags at the
13221 entry including inherited ones. Additionally, the category
13222 of the entry (if any) must be specified as the text property
13223 'org-category on the headline.
13225 See also `org-scan-tags'.
13227 (declare (special todo-only))
13228 (unless (boundp 'todo-only)
13229 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13230 (unless match
13231 ;; Get a new match request, with completion
13232 (let ((org-last-tags-completion-table
13233 (org-global-tags-completion-table)))
13234 (setq match (org-completing-read-no-i
13235 "Match: " 'org-tags-completion-function nil nil nil
13236 'org-tags-history))))
13238 ;; Parse the string and create a lisp form
13239 (let ((match0 match)
13240 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13241 minus tag mm
13242 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13243 orterms term orlist re-p str-p level-p level-op time-p
13244 prop-p pn pv po gv rest)
13245 (if (string-match "/+" match)
13246 ;; match contains also a todo-matching request
13247 (progn
13248 (setq tagsmatch (substring match 0 (match-beginning 0))
13249 todomatch (substring match (match-end 0)))
13250 (if (string-match "^!" todomatch)
13251 (setq todo-only t todomatch (substring todomatch 1)))
13252 (if (string-match "^\\s-*$" todomatch)
13253 (setq todomatch nil)))
13254 ;; only matching tags
13255 (setq tagsmatch match todomatch nil))
13257 ;; Make the tags matcher
13258 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13259 (setq tagsmatcher t)
13260 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13261 (while (setq term (pop orterms))
13262 (while (and (equal (substring term -1) "\\") orterms)
13263 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13264 (while (string-match re term)
13265 (setq rest (substring term (match-end 0))
13266 minus (and (match-end 1)
13267 (equal (match-string 1 term) "-"))
13268 tag (save-match-data (replace-regexp-in-string
13269 "\\\\-" "-"
13270 (match-string 2 term)))
13271 re-p (equal (string-to-char tag) ?{)
13272 level-p (match-end 4)
13273 prop-p (match-end 5)
13274 mm (cond
13275 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13276 (level-p
13277 (setq level-op (org-op-to-function (match-string 3 term)))
13278 `(,level-op level ,(string-to-number
13279 (match-string 4 term))))
13280 (prop-p
13281 (setq pn (match-string 5 term)
13282 po (match-string 6 term)
13283 pv (match-string 7 term)
13284 re-p (equal (string-to-char pv) ?{)
13285 str-p (equal (string-to-char pv) ?\")
13286 time-p (save-match-data
13287 (string-match "^\"[[<].*[]>]\"$" pv))
13288 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13289 (if time-p (setq pv (org-matcher-time pv)))
13290 (setq po (org-op-to-function po (if time-p 'time str-p)))
13291 (cond
13292 ((equal pn "CATEGORY")
13293 (setq gv '(get-text-property (point) 'org-category)))
13294 ((equal pn "TODO")
13295 (setq gv 'todo))
13297 (setq gv `(org-cached-entry-get nil ,pn))))
13298 (if re-p
13299 (if (eq po 'org<>)
13300 `(not (string-match ,pv (or ,gv "")))
13301 `(string-match ,pv (or ,gv "")))
13302 (if str-p
13303 `(,po (or ,gv "") ,pv)
13304 `(,po (string-to-number (or ,gv ""))
13305 ,(string-to-number pv) ))))
13306 (t `(member ,tag tags-list)))
13307 mm (if minus (list 'not mm) mm)
13308 term rest)
13309 (push mm tagsmatcher))
13310 (push (if (> (length tagsmatcher) 1)
13311 (cons 'and tagsmatcher)
13312 (car tagsmatcher))
13313 orlist)
13314 (setq tagsmatcher nil))
13315 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13316 (setq tagsmatcher
13317 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13318 ;; Make the todo matcher
13319 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13320 (setq todomatcher t)
13321 (setq orterms (org-split-string todomatch "|") orlist nil)
13322 (while (setq term (pop orterms))
13323 (while (string-match re term)
13324 (setq minus (and (match-end 1)
13325 (equal (match-string 1 term) "-"))
13326 kwd (match-string 2 term)
13327 re-p (equal (string-to-char kwd) ?{)
13328 term (substring term (match-end 0))
13329 mm (if re-p
13330 `(string-match ,(substring kwd 1 -1) todo)
13331 (list 'equal 'todo kwd))
13332 mm (if minus (list 'not mm) mm))
13333 (push mm todomatcher))
13334 (push (if (> (length todomatcher) 1)
13335 (cons 'and todomatcher)
13336 (car todomatcher))
13337 orlist)
13338 (setq todomatcher nil))
13339 (setq todomatcher (if (> (length orlist) 1)
13340 (cons 'or orlist) (car orlist))))
13342 ;; Return the string and lisp forms of the matcher
13343 (setq matcher (if todomatcher
13344 (list 'and tagsmatcher todomatcher)
13345 tagsmatcher))
13346 (when todo-only
13347 (setq matcher (list 'and '(member todo org-not-done-keywords)
13348 matcher)))
13349 (cons match0 matcher)))
13351 (defun org-op-to-function (op &optional stringp)
13352 "Turn an operator into the appropriate function."
13353 (setq op
13354 (cond
13355 ((equal op "<" ) '(< string< org-time<))
13356 ((equal op ">" ) '(> org-string> org-time>))
13357 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13358 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13359 ((member op '("=" "==")) '(= string= org-time=))
13360 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13361 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13363 (defun org<> (a b) (not (= a b)))
13364 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13365 (defun org-string>= (a b) (not (string< a b)))
13366 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13367 (defun org-string<> (a b) (not (string= a b)))
13368 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13369 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13370 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13371 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13372 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13373 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13374 (defun org-2ft (s)
13375 "Convert S to a floating point time.
13376 If S is already a number, just return it. If it is a string, parse
13377 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13378 (cond
13379 ((numberp s) s)
13380 ((stringp s)
13381 (condition-case nil
13382 (float-time (apply 'encode-time (org-parse-time-string s)))
13383 (error 0.)))
13384 (t 0.)))
13386 (defun org-time-today ()
13387 "Time in seconds today at 0:00.
13388 Returns the float number of seconds since the beginning of the
13389 epoch to the beginning of today (00:00)."
13390 (float-time (apply 'encode-time
13391 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13393 (defun org-matcher-time (s)
13394 "Interpret a time comparison value."
13395 (save-match-data
13396 (cond
13397 ((string= s "<now>") (float-time))
13398 ((string= s "<today>") (org-time-today))
13399 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13400 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13401 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13402 (+ (org-time-today)
13403 (* (string-to-number (match-string 1 s))
13404 (cdr (assoc (match-string 2 s)
13405 '(("d" . 86400.0) ("w" . 604800.0)
13406 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13407 (t (org-2ft s)))))
13409 (defun org-match-any-p (re list)
13410 "Does re match any element of list?"
13411 (setq list (mapcar (lambda (x) (string-match re x)) list))
13412 (delq nil list))
13414 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13415 (defvar org-tags-overlay (make-overlay 1 1))
13416 (org-detach-overlay org-tags-overlay)
13418 (defun org-get-local-tags-at (&optional pos)
13419 "Get a list of tags defined in the current headline."
13420 (org-get-tags-at pos 'local))
13422 (defun org-get-local-tags ()
13423 "Get a list of tags defined in the current headline."
13424 (org-get-tags-at nil 'local))
13426 (defun org-get-tags-at (&optional pos local)
13427 "Get a list of all headline tags applicable at POS.
13428 POS defaults to point. If tags are inherited, the list contains
13429 the targets in the same sequence as the headlines appear, i.e.
13430 the tags of the current headline come last.
13431 When LOCAL is non-nil, only return tags from the current headline,
13432 ignore inherited ones."
13433 (interactive)
13434 (if (and org-trust-scanner-tags
13435 (or (not pos) (equal pos (point)))
13436 (not local))
13437 org-scanner-tags
13438 (let (tags ltags lastpos parent)
13439 (save-excursion
13440 (save-restriction
13441 (widen)
13442 (goto-char (or pos (point)))
13443 (save-match-data
13444 (catch 'done
13445 (condition-case nil
13446 (progn
13447 (org-back-to-heading t)
13448 (while (not (equal lastpos (point)))
13449 (setq lastpos (point))
13450 (when (looking-at
13451 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13452 (setq ltags (org-split-string
13453 (org-match-string-no-properties 1) ":"))
13454 (when parent
13455 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13456 (setq tags (append
13457 (if parent
13458 (org-remove-uninherited-tags ltags)
13459 ltags)
13460 tags)))
13461 (or org-use-tag-inheritance (throw 'done t))
13462 (if local (throw 'done t))
13463 (or (org-up-heading-safe) (error nil))
13464 (setq parent t)))
13465 (error nil)))))
13466 (if local
13467 tags
13468 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13470 (defun org-add-prop-inherited (s)
13471 (add-text-properties 0 (length s) '(inherited t) s)
13474 (defun org-toggle-tag (tag &optional onoff)
13475 "Toggle the tag TAG for the current line.
13476 If ONOFF is `on' or `off', don't toggle but set to this state."
13477 (let (res current)
13478 (save-excursion
13479 (org-back-to-heading t)
13480 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13481 (point-at-eol) t)
13482 (progn
13483 (setq current (match-string 1))
13484 (replace-match ""))
13485 (setq current ""))
13486 (setq current (nreverse (org-split-string current ":")))
13487 (cond
13488 ((eq onoff 'on)
13489 (setq res t)
13490 (or (member tag current) (push tag current)))
13491 ((eq onoff 'off)
13492 (or (not (member tag current)) (setq current (delete tag current))))
13493 (t (if (member tag current)
13494 (setq current (delete tag current))
13495 (setq res t)
13496 (push tag current))))
13497 (end-of-line 1)
13498 (if current
13499 (progn
13500 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13501 (org-set-tags nil t))
13502 (delete-horizontal-space))
13503 (run-hooks 'org-after-tags-change-hook))
13504 res))
13506 (defun org-align-tags-here (to-col)
13507 ;; Assumes that this is a headline
13508 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13509 (beginning-of-line 1)
13510 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13511 (< pos (match-beginning 2)))
13512 (progn
13513 (setq tags-l (- (match-end 2) (match-beginning 2)))
13514 (goto-char (match-beginning 1))
13515 (insert " ")
13516 (delete-region (point) (1+ (match-beginning 2)))
13517 (setq ncol (max (current-column)
13518 (1+ col)
13519 (if (> to-col 0)
13520 to-col
13521 (- (abs to-col) tags-l))))
13522 (setq p (point))
13523 (insert (make-string (- ncol (current-column)) ?\ ))
13524 (setq ncol (current-column))
13525 (when indent-tabs-mode (tabify p (point-at-eol)))
13526 (org-move-to-column (min ncol col) t))
13527 (goto-char pos))))
13529 (defun org-set-tags-command (&optional arg just-align)
13530 "Call the set-tags command for the current entry."
13531 (interactive "P")
13532 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13533 (org-set-tags arg just-align)
13534 (save-excursion
13535 (org-back-to-heading t)
13536 (org-set-tags arg just-align))))
13538 (defun org-set-tags-to (data)
13539 "Set the tags of the current entry to DATA, replacing the current tags.
13540 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13541 If DATA is nil or the empty string, any tags will be removed."
13542 (interactive "sTags: ")
13543 (setq data
13544 (cond
13545 ((eq data nil) "")
13546 ((equal data "") "")
13547 ((stringp data)
13548 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13549 ":"))
13550 ((listp data)
13551 (concat ":" (mapconcat 'identity data ":") ":"))
13552 (t nil)))
13553 (when data
13554 (save-excursion
13555 (org-back-to-heading t)
13556 (when (looking-at org-complex-heading-regexp)
13557 (if (match-end 5)
13558 (progn
13559 (goto-char (match-beginning 5))
13560 (insert data)
13561 (delete-region (point) (point-at-eol))
13562 (org-set-tags nil 'align))
13563 (goto-char (point-at-eol))
13564 (insert " " data)
13565 (org-set-tags nil 'align)))
13566 (beginning-of-line 1)
13567 (if (looking-at ".*?\\([ \t]+\\)$")
13568 (delete-region (match-beginning 1) (match-end 1))))))
13570 (defun org-align-all-tags ()
13571 "Align the tags i all headings."
13572 (interactive)
13573 (save-excursion
13574 (or (ignore-errors (org-back-to-heading t))
13575 (outline-next-heading))
13576 (if (org-at-heading-p)
13577 (org-set-tags t)
13578 (message "No headings"))))
13580 (defvar org-indent-indentation-per-level)
13581 (defun org-set-tags (&optional arg just-align)
13582 "Set the tags for the current headline.
13583 With prefix ARG, realign all tags in headings in the current buffer."
13584 (interactive "P")
13585 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13586 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13587 'region-start-level 'region))
13588 org-loop-over-headlines-in-active-region)
13589 (org-map-entries
13590 ;; We don't use ARG and JUST-ALIGN here these args are not
13591 ;; useful when looping over headlines
13592 `(org-set-tags)
13593 org-loop-over-headlines-in-active-region
13594 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13595 (let* ((re org-outline-regexp-bol)
13596 (current (unless arg (org-get-tags-string)))
13597 (col (current-column))
13598 (org-setting-tags t)
13599 table current-tags inherited-tags ; computed below when needed
13600 tags p0 c0 c1 rpl di tc level)
13601 (if arg
13602 (save-excursion
13603 (goto-char (point-min))
13604 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13605 (while (re-search-forward re nil t)
13606 (org-set-tags nil t)
13607 (end-of-line 1)))
13608 (message "All tags realigned to column %d" org-tags-column))
13609 (if just-align
13610 (setq tags current)
13611 ;; Get a new set of tags from the user
13612 (save-excursion
13613 (setq table (append org-tag-persistent-alist
13614 (or org-tag-alist (org-get-buffer-tags))
13615 (and
13616 org-complete-tags-always-offer-all-agenda-tags
13617 (org-global-tags-completion-table
13618 (org-agenda-files))))
13619 org-last-tags-completion-table table
13620 current-tags (org-split-string current ":")
13621 inherited-tags (nreverse
13622 (nthcdr (length current-tags)
13623 (nreverse (org-get-tags-at))))
13624 tags
13625 (if (or (eq t org-use-fast-tag-selection)
13626 (and org-use-fast-tag-selection
13627 (delq nil (mapcar 'cdr table))))
13628 (org-fast-tag-selection
13629 current-tags inherited-tags table
13630 (if org-fast-tag-selection-include-todo
13631 org-todo-key-alist))
13632 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13633 (org-trim
13634 (org-icompleting-read "Tags: "
13635 'org-tags-completion-function
13636 nil nil current 'org-tags-history))))))
13637 (while (string-match "[-+&]+" tags)
13638 ;; No boolean logic, just a list
13639 (setq tags (replace-match ":" t t tags))))
13641 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13643 (if org-tags-sort-function
13644 (setq tags (mapconcat 'identity
13645 (sort (org-split-string
13646 tags (org-re "[^[:alnum:]_@#%]+"))
13647 org-tags-sort-function) ":")))
13649 (if (string-match "\\`[\t ]*\\'" tags)
13650 (setq tags "")
13651 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13652 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13654 ;; Insert new tags at the correct column
13655 (beginning-of-line 1)
13656 (setq level (or (and (looking-at org-outline-regexp)
13657 (- (match-end 0) (point) 1))
13659 (cond
13660 ((and (equal current "") (equal tags "")))
13661 ((re-search-forward
13662 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13663 (point-at-eol) t)
13664 (if (equal tags "")
13665 (setq rpl "")
13666 (goto-char (match-beginning 0))
13667 (setq c0 (current-column)
13668 ;; compute offset for the case of org-indent-mode active
13669 di (if org-indent-mode
13670 (* (1- org-indent-indentation-per-level) (1- level))
13672 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13673 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13674 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13675 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13676 (replace-match rpl t t)
13677 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13678 tags)
13679 (t (error "Tags alignment failed")))
13680 (org-move-to-column col)
13681 (unless just-align
13682 (run-hooks 'org-after-tags-change-hook))))))
13684 (defun org-change-tag-in-region (beg end tag off)
13685 "Add or remove TAG for each entry in the region.
13686 This works in the agenda, and also in an org-mode buffer."
13687 (interactive
13688 (list (region-beginning) (region-end)
13689 (let ((org-last-tags-completion-table
13690 (if (derived-mode-p 'org-mode)
13691 (org-get-buffer-tags)
13692 (org-global-tags-completion-table))))
13693 (org-icompleting-read
13694 "Tag: " 'org-tags-completion-function nil nil nil
13695 'org-tags-history))
13696 (progn
13697 (message "[s]et or [r]emove? ")
13698 (equal (read-char-exclusive) ?r))))
13699 (if (fboundp 'deactivate-mark) (deactivate-mark))
13700 (let ((agendap (equal major-mode 'org-agenda-mode))
13701 l1 l2 m buf pos newhead (cnt 0))
13702 (goto-char end)
13703 (setq l2 (1- (org-current-line)))
13704 (goto-char beg)
13705 (setq l1 (org-current-line))
13706 (loop for l from l1 to l2 do
13707 (org-goto-line l)
13708 (setq m (get-text-property (point) 'org-hd-marker))
13709 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13710 (and agendap m))
13711 (setq buf (if agendap (marker-buffer m) (current-buffer))
13712 pos (if agendap m (point)))
13713 (with-current-buffer buf
13714 (save-excursion
13715 (save-restriction
13716 (goto-char pos)
13717 (setq cnt (1+ cnt))
13718 (org-toggle-tag tag (if off 'off 'on))
13719 (setq newhead (org-get-heading)))))
13720 (and agendap (org-agenda-change-all-lines newhead m))))
13721 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13723 (defun org-tags-completion-function (string predicate &optional flag)
13724 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13725 (confirm (lambda (x) (stringp (car x)))))
13726 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13727 (setq s1 (match-string 1 string)
13728 s2 (match-string 2 string))
13729 (setq s1 "" s2 string))
13730 (cond
13731 ((eq flag nil)
13732 ;; try completion
13733 (setq rtn (try-completion s2 ctable confirm))
13734 (if (stringp rtn)
13735 (setq rtn
13736 (concat s1 s2 (substring rtn (length s2))
13737 (if (and org-add-colon-after-tag-completion
13738 (assoc rtn ctable))
13739 ":" ""))))
13740 rtn)
13741 ((eq flag t)
13742 ;; all-completions
13743 (all-completions s2 ctable confirm)
13745 ((eq flag 'lambda)
13746 ;; exact match?
13747 (assoc s2 ctable)))
13750 (defun org-fast-tag-insert (kwd tags face &optional end)
13751 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13752 (insert (format "%-12s" (concat kwd ":"))
13753 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13754 (or end "")))
13756 (defun org-fast-tag-show-exit (flag)
13757 (save-excursion
13758 (org-goto-line 3)
13759 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13760 (replace-match ""))
13761 (when flag
13762 (end-of-line 1)
13763 (org-move-to-column (- (window-width) 19) t)
13764 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13766 (defun org-set-current-tags-overlay (current prefix)
13767 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13768 (if (featurep 'xemacs)
13769 (org-overlay-display org-tags-overlay (concat prefix s)
13770 'secondary-selection)
13771 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13772 (org-overlay-display org-tags-overlay (concat prefix s)))))
13774 (defvar org-last-tag-selection-key nil)
13775 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13776 "Fast tag selection with single keys.
13777 CURRENT is the current list of tags in the headline, INHERITED is the
13778 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13779 possibly with grouping information. TODO-TABLE is a similar table with
13780 TODO keywords, should these have keys assigned to them.
13781 If the keys are nil, a-z are automatically assigned.
13782 Returns the new tags string, or nil to not change the current settings."
13783 (let* ((fulltable (append table todo-table))
13784 (maxlen (apply 'max (mapcar
13785 (lambda (x)
13786 (if (stringp (car x)) (string-width (car x)) 0))
13787 fulltable)))
13788 (buf (current-buffer))
13789 (expert (eq org-fast-tag-selection-single-key 'expert))
13790 (buffer-tags nil)
13791 (fwidth (+ maxlen 3 1 3))
13792 (ncol (/ (- (window-width) 4) fwidth))
13793 (i-face 'org-done)
13794 (c-face 'org-todo)
13795 tg cnt e c char c1 c2 ntable tbl rtn
13796 ov-start ov-end ov-prefix
13797 (exit-after-next org-fast-tag-selection-single-key)
13798 (done-keywords org-done-keywords)
13799 groups ingroup)
13800 (save-excursion
13801 (beginning-of-line 1)
13802 (if (looking-at
13803 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13804 (setq ov-start (match-beginning 1)
13805 ov-end (match-end 1)
13806 ov-prefix "")
13807 (setq ov-start (1- (point-at-eol))
13808 ov-end (1+ ov-start))
13809 (skip-chars-forward "^\n\r")
13810 (setq ov-prefix
13811 (concat
13812 (buffer-substring (1- (point)) (point))
13813 (if (> (current-column) org-tags-column)
13815 (make-string (- org-tags-column (current-column)) ?\ ))))))
13816 (move-overlay org-tags-overlay ov-start ov-end)
13817 (save-window-excursion
13818 (if expert
13819 (set-buffer (get-buffer-create " *Org tags*"))
13820 (delete-other-windows)
13821 (split-window-vertically)
13822 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13823 (erase-buffer)
13824 (org-set-local 'org-done-keywords done-keywords)
13825 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13826 (org-fast-tag-insert "Current" current c-face "\n\n")
13827 (org-fast-tag-show-exit exit-after-next)
13828 (org-set-current-tags-overlay current ov-prefix)
13829 (setq tbl fulltable char ?a cnt 0)
13830 (while (setq e (pop tbl))
13831 (cond
13832 ((equal (car e) :startgroup)
13833 (push '() groups) (setq ingroup t)
13834 (when (not (= cnt 0))
13835 (setq cnt 0)
13836 (insert "\n"))
13837 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13838 ((equal (car e) :endgroup)
13839 (setq ingroup nil cnt 0)
13840 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13841 ((equal e '(:newline))
13842 (when (not (= cnt 0))
13843 (setq cnt 0)
13844 (insert "\n")
13845 (setq e (car tbl))
13846 (while (equal (car tbl) '(:newline))
13847 (insert "\n")
13848 (setq tbl (cdr tbl)))))
13850 (setq tg (copy-sequence (car e)) c2 nil)
13851 (if (cdr e)
13852 (setq c (cdr e))
13853 ;; automatically assign a character.
13854 (setq c1 (string-to-char
13855 (downcase (substring
13856 tg (if (= (string-to-char tg) ?@) 1 0)))))
13857 (if (or (rassoc c1 ntable) (rassoc c1 table))
13858 (while (or (rassoc char ntable) (rassoc char table))
13859 (setq char (1+ char)))
13860 (setq c2 c1))
13861 (setq c (or c2 char)))
13862 (if ingroup (push tg (car groups)))
13863 (setq tg (org-add-props tg nil 'face
13864 (cond
13865 ((not (assoc tg table))
13866 (org-get-todo-face tg))
13867 ((member tg current) c-face)
13868 ((member tg inherited) i-face)
13869 (t nil))))
13870 (if (and (= cnt 0) (not ingroup)) (insert " "))
13871 (insert "[" c "] " tg (make-string
13872 (- fwidth 4 (length tg)) ?\ ))
13873 (push (cons tg c) ntable)
13874 (when (= (setq cnt (1+ cnt)) ncol)
13875 (insert "\n")
13876 (if ingroup (insert " "))
13877 (setq cnt 0)))))
13878 (setq ntable (nreverse ntable))
13879 (insert "\n")
13880 (goto-char (point-min))
13881 (if (not expert) (org-fit-window-to-buffer))
13882 (setq rtn
13883 (catch 'exit
13884 (while t
13885 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13886 (if (not groups) "no " "")
13887 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13888 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13889 (setq org-last-tag-selection-key c)
13890 (cond
13891 ((= c ?\r) (throw 'exit t))
13892 ((= c ?!)
13893 (setq groups (not groups))
13894 (goto-char (point-min))
13895 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13896 ((= c ?\C-c)
13897 (if (not expert)
13898 (org-fast-tag-show-exit
13899 (setq exit-after-next (not exit-after-next)))
13900 (setq expert nil)
13901 (delete-other-windows)
13902 (set-window-buffer (split-window-vertically) " *Org tags*")
13903 (org-switch-to-buffer-other-window " *Org tags*")
13904 (org-fit-window-to-buffer)))
13905 ((or (= c ?\C-g)
13906 (and (= c ?q) (not (rassoc c ntable))))
13907 (org-detach-overlay org-tags-overlay)
13908 (setq quit-flag t))
13909 ((= c ?\ )
13910 (setq current nil)
13911 (if exit-after-next (setq exit-after-next 'now)))
13912 ((= c ?\t)
13913 (condition-case nil
13914 (setq tg (org-icompleting-read
13915 "Tag: "
13916 (or buffer-tags
13917 (with-current-buffer buf
13918 (org-get-buffer-tags)))))
13919 (quit (setq tg "")))
13920 (when (string-match "\\S-" tg)
13921 (add-to-list 'buffer-tags (list tg))
13922 (if (member tg current)
13923 (setq current (delete tg current))
13924 (push tg current)))
13925 (if exit-after-next (setq exit-after-next 'now)))
13926 ((setq e (rassoc c todo-table) tg (car e))
13927 (with-current-buffer buf
13928 (save-excursion (org-todo tg)))
13929 (if exit-after-next (setq exit-after-next 'now)))
13930 ((setq e (rassoc c ntable) tg (car e))
13931 (if (member tg current)
13932 (setq current (delete tg current))
13933 (loop for g in groups do
13934 (if (member tg g)
13935 (mapc (lambda (x)
13936 (setq current (delete x current)))
13937 g)))
13938 (push tg current))
13939 (if exit-after-next (setq exit-after-next 'now))))
13941 ;; Create a sorted list
13942 (setq current
13943 (sort current
13944 (lambda (a b)
13945 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13946 (if (eq exit-after-next 'now) (throw 'exit t))
13947 (goto-char (point-min))
13948 (beginning-of-line 2)
13949 (delete-region (point) (point-at-eol))
13950 (org-fast-tag-insert "Current" current c-face)
13951 (org-set-current-tags-overlay current ov-prefix)
13952 (while (re-search-forward
13953 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13954 (setq tg (match-string 1))
13955 (add-text-properties
13956 (match-beginning 1) (match-end 1)
13957 (list 'face
13958 (cond
13959 ((member tg current) c-face)
13960 ((member tg inherited) i-face)
13961 (t (get-text-property (match-beginning 1) 'face))))))
13962 (goto-char (point-min)))))
13963 (org-detach-overlay org-tags-overlay)
13964 (if rtn
13965 (mapconcat 'identity current ":")
13966 nil))))
13968 (defun org-get-tags-string ()
13969 "Get the TAGS string in the current headline."
13970 (unless (org-at-heading-p t)
13971 (error "Not on a heading"))
13972 (save-excursion
13973 (beginning-of-line 1)
13974 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13975 (org-match-string-no-properties 1)
13976 "")))
13978 (defun org-get-tags ()
13979 "Get the list of tags specified in the current headline."
13980 (org-split-string (org-get-tags-string) ":"))
13982 (defun org-get-buffer-tags ()
13983 "Get a table of all tags used in the buffer, for completion."
13984 (let (tags)
13985 (save-excursion
13986 (goto-char (point-min))
13987 (while (re-search-forward
13988 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13989 (when (equal (char-after (point-at-bol 0)) ?*)
13990 (mapc (lambda (x) (add-to-list 'tags x))
13991 (org-split-string (org-match-string-no-properties 1) ":")))))
13992 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13993 (mapcar 'list tags)))
13995 ;;;; The mapping API
13997 ;;;###autoload
13998 (defun org-map-entries (func &optional match scope &rest skip)
13999 "Call FUNC at each headline selected by MATCH in SCOPE.
14001 FUNC is a function or a lisp form. The function will be called without
14002 arguments, with the cursor positioned at the beginning of the headline.
14003 The return values of all calls to the function will be collected and
14004 returned as a list.
14006 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14007 does not need to preserve point. After evaluation, the cursor will be
14008 moved to the end of the line (presumably of the headline of the
14009 processed entry) and search continues from there. Under some
14010 circumstances, this may not produce the wanted results. For example,
14011 if you have removed (e.g. archived) the current (sub)tree it could
14012 mean that the next entry will be skipped entirely. In such cases, you
14013 can specify the position from where search should continue by making
14014 FUNC set the variable `org-map-continue-from' to the desired buffer
14015 position.
14017 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14018 Only headlines that are matched by this query will be considered during
14019 the iteration. When MATCH is nil or t, all headlines will be
14020 visited by the iteration.
14022 SCOPE determines the scope of this command. It can be any of:
14024 nil The current buffer, respecting the restriction if any
14025 tree The subtree started with the entry at point
14026 region The entries within the active region, if any
14027 region-start-level
14028 The entries within the active region, but only those at
14029 the same level than the first one.
14030 file The current buffer, without restriction
14031 file-with-archives
14032 The current buffer, and any archives associated with it
14033 agenda All agenda files
14034 agenda-with-archives
14035 All agenda files with any archive files associated with them
14036 \(file1 file2 ...)
14037 If this is a list, all files in the list will be scanned
14039 The remaining args are treated as settings for the skipping facilities of
14040 the scanner. The following items can be given here:
14042 archive skip trees with the archive tag.
14043 comment skip trees with the COMMENT keyword
14044 function or Emacs Lisp form:
14045 will be used as value for `org-agenda-skip-function', so whenever
14046 the function returns t, FUNC will not be called for that
14047 entry and search will continue from the point where the
14048 function leaves it.
14050 If your function needs to retrieve the tags including inherited tags
14051 at the *current* entry, you can use the value of the variable
14052 `org-scanner-tags' which will be much faster than getting the value
14053 with `org-get-tags-at'. If your function gets properties with
14054 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14055 to t around the call to `org-entry-properties' to get the same speedup.
14056 Note that if your function moves around to retrieve tags and properties at
14057 a *different* entry, you cannot use these techniques."
14058 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14059 (not (org-region-active-p)))
14060 (let* ((org-agenda-archives-mode nil) ; just to make sure
14061 (org-agenda-skip-archived-trees (memq 'archive skip))
14062 (org-agenda-skip-comment-trees (memq 'comment skip))
14063 (org-agenda-skip-function
14064 (car (org-delete-all '(comment archive) skip)))
14065 (org-tags-match-list-sublevels t)
14066 (start-level (eq scope 'region-start-level))
14067 matcher file res
14068 org-todo-keywords-for-agenda
14069 org-done-keywords-for-agenda
14070 org-todo-keyword-alist-for-agenda
14071 org-drawers-for-agenda
14072 org-tag-alist-for-agenda
14073 todo-only)
14075 (cond
14076 ((eq match t) (setq matcher t))
14077 ((eq match nil) (setq matcher t))
14078 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14080 (save-excursion
14081 (save-restriction
14082 (cond ((eq scope 'tree)
14083 (org-back-to-heading t)
14084 (org-narrow-to-subtree)
14085 (setq scope nil))
14086 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14087 (org-region-active-p))
14088 ;; If needed, set start-level to a string like "2"
14089 (when start-level
14090 (save-excursion
14091 (goto-char (region-beginning))
14092 (unless (org-at-heading-p) (outline-next-heading))
14093 (setq start-level (org-current-level))))
14094 (narrow-to-region (region-beginning)
14095 (save-excursion
14096 (goto-char (region-end))
14097 (unless (and (bolp) (org-at-heading-p))
14098 (outline-next-heading))
14099 (point)))
14100 (setq scope nil)))
14102 (if (not scope)
14103 (progn
14104 (org-prepare-agenda-buffers
14105 (list (buffer-file-name (current-buffer))))
14106 (setq res (org-scan-tags func matcher todo-only start-level)))
14107 ;; Get the right scope
14108 (cond
14109 ((and scope (listp scope) (symbolp (car scope)))
14110 (setq scope (eval scope)))
14111 ((eq scope 'agenda)
14112 (setq scope (org-agenda-files t)))
14113 ((eq scope 'agenda-with-archives)
14114 (setq scope (org-agenda-files t))
14115 (setq scope (org-add-archive-files scope)))
14116 ((eq scope 'file)
14117 (setq scope (list (buffer-file-name))))
14118 ((eq scope 'file-with-archives)
14119 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14120 (org-prepare-agenda-buffers scope)
14121 (while (setq file (pop scope))
14122 (with-current-buffer (org-find-base-buffer-visiting file)
14123 (save-excursion
14124 (save-restriction
14125 (widen)
14126 (goto-char (point-min))
14127 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14128 res)))
14130 ;;;; Properties
14132 ;;; Setting and retrieving properties
14134 (defconst org-special-properties
14135 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14136 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
14137 "The special properties valid in Org-mode.
14139 These are properties that are not defined in the property drawer,
14140 but in some other way.")
14142 (defconst org-default-properties
14143 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14144 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14145 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14146 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14147 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14148 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14149 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14150 "Some properties that are used by Org-mode for various purposes.
14151 Being in this list makes sure that they are offered for completion.")
14153 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14154 "Regular expression matching the first line of a property drawer.")
14156 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14157 "Regular expression matching the last line of a property drawer.")
14159 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14160 "Regular expression matching the first line of a property drawer.")
14162 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14163 "Regular expression matching the first line of a property drawer.")
14165 (defconst org-property-drawer-re
14166 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14167 org-property-end-re "\\)\n?")
14168 "Matches an entire property drawer.")
14170 (defconst org-clock-drawer-re
14171 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14172 org-property-end-re "\\)\n?")
14173 "Matches an entire clock drawer.")
14175 (defsubst org-re-property (property)
14176 "Return a regexp matching a PROPERTY line.
14177 Match group 1 will be set to the value."
14178 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14180 (defsubst org-re-property-keyword (property)
14181 "Return a regexp matching a PROPERTY line, possibly with no
14182 value for the property."
14183 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14185 (defun org-property-action ()
14186 "Do an action on properties."
14187 (interactive)
14188 (let (c)
14189 (org-at-property-p)
14190 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14191 (setq c (read-char-exclusive))
14192 (cond
14193 ((equal c ?s)
14194 (call-interactively 'org-set-property))
14195 ((equal c ?d)
14196 (call-interactively 'org-delete-property))
14197 ((equal c ?D)
14198 (call-interactively 'org-delete-property-globally))
14199 ((equal c ?c)
14200 (call-interactively 'org-compute-property-at-point))
14201 (t (error "No such property action %c" c)))))
14203 (defun org-inc-effort ()
14204 "Increment the value of the effort property in the current entry."
14205 (interactive)
14206 (org-set-effort nil t))
14208 (defun org-set-effort (&optional value increment)
14209 "Set the effort property of the current entry.
14210 With numerical prefix arg, use the nth allowed value, 0 stands for the
14211 10th allowed value.
14213 When INCREMENT is non-nil, set the property to the next allowed value."
14214 (interactive "P")
14215 (if (equal value 0) (setq value 10))
14216 (let* ((completion-ignore-case t)
14217 (prop org-effort-property)
14218 (cur (org-entry-get nil prop))
14219 (allowed (org-property-get-allowed-values nil prop 'table))
14220 (existing (mapcar 'list (org-property-values prop)))
14222 (val (cond
14223 ((stringp value) value)
14224 ((and allowed (integerp value))
14225 (or (car (nth (1- value) allowed))
14226 (car (org-last allowed))))
14227 ((and allowed increment)
14228 (or (caadr (member (list cur) allowed))
14229 (error "Allowed effort values are not set")))
14230 (allowed
14231 (message "Select 1-9,0, [RET%s]: %s"
14232 (if cur (concat "=" cur) "")
14233 (mapconcat 'car allowed " "))
14234 (setq rpl (read-char-exclusive))
14235 (if (equal rpl ?\r)
14237 (setq rpl (- rpl ?0))
14238 (if (equal rpl 0) (setq rpl 10))
14239 (if (and (> rpl 0) (<= rpl (length allowed)))
14240 (car (nth (1- rpl) allowed))
14241 (org-completing-read "Effort: " allowed nil))))
14243 (let (org-completion-use-ido org-completion-use-iswitchb)
14244 (org-completing-read
14245 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14246 (concat "[" cur "]") "")
14247 ": ")
14248 existing nil nil "" nil cur))))))
14249 (unless (equal (org-entry-get nil prop) val)
14250 (org-entry-put nil prop val))
14251 (message "%s is now %s" prop val)))
14253 (defun org-at-property-p ()
14254 "Is cursor inside a property drawer?"
14255 (save-excursion
14256 (beginning-of-line 1)
14257 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14258 (save-match-data ;; Used by calling procedures
14259 (let ((p (point))
14260 (range (unless (org-before-first-heading-p)
14261 (org-get-property-block))))
14262 (and range (<= (car range) p) (< p (cdr range))))))))
14264 (defun org-get-property-block (&optional beg end force)
14265 "Return the (beg . end) range of the body of the property drawer.
14266 BEG and END can be beginning and end of subtree, if not given
14267 they will be found.
14268 If the drawer does not exist and FORCE is non-nil, create the drawer."
14269 (catch 'exit
14270 (save-excursion
14271 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14272 (end (or end (progn (outline-next-heading) (point)))))
14273 (goto-char beg)
14274 (if (re-search-forward org-property-start-re end t)
14275 (setq beg (1+ (match-end 0)))
14276 (if force
14277 (save-excursion
14278 (org-insert-property-drawer)
14279 (setq end (progn (outline-next-heading) (point))))
14280 (throw 'exit nil))
14281 (goto-char beg)
14282 (if (re-search-forward org-property-start-re end t)
14283 (setq beg (1+ (match-end 0)))))
14284 (if (re-search-forward org-property-end-re end t)
14285 (setq end (match-beginning 0))
14286 (or force (throw 'exit nil))
14287 (goto-char beg)
14288 (setq end beg)
14289 (org-indent-line)
14290 (insert ":END:\n"))
14291 (cons beg end)))))
14293 (defun org-entry-properties (&optional pom which specific)
14294 "Get all properties of the entry at point-or-marker POM.
14295 This includes the TODO keyword, the tags, time strings for deadline,
14296 scheduled, and clocking, and any additional properties defined in the
14297 entry. The return value is an alist, keys may occur multiple times
14298 if the property key was used several times.
14299 POM may also be nil, in which case the current entry is used.
14300 If WHICH is nil or `all', get all properties. If WHICH is
14301 `special' or `standard', only get that subclass. If WHICH
14302 is a string only get exactly this property. SPECIFIC can be a string, the
14303 specific property we are interested in. Specifying it can speed
14304 things up because then unnecessary parsing is avoided."
14305 (setq which (or which 'all))
14306 (org-with-point-at pom
14307 (let ((clockstr (substring org-clock-string 0 -1))
14308 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14309 (case-fold-search nil)
14310 beg end range props sum-props key key1 value string clocksum)
14311 (save-excursion
14312 (when (condition-case nil
14313 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14314 (error nil))
14315 (setq beg (point))
14316 (setq sum-props (get-text-property (point) 'org-summaries))
14317 (setq clocksum (get-text-property (point) :org-clock-minutes))
14318 (outline-next-heading)
14319 (setq end (point))
14320 (when (memq which '(all special))
14321 ;; Get the special properties, like TODO and tags
14322 (goto-char beg)
14323 (when (and (or (not specific) (string= specific "TODO"))
14324 (looking-at org-todo-line-regexp) (match-end 2))
14325 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14326 (when (and (or (not specific) (string= specific "PRIORITY"))
14327 (looking-at org-priority-regexp))
14328 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14329 (when (or (not specific) (string= specific "FILE"))
14330 (push (cons "FILE" buffer-file-name) props))
14331 (when (and (or (not specific) (string= specific "TAGS"))
14332 (setq value (org-get-tags-string))
14333 (string-match "\\S-" value))
14334 (push (cons "TAGS" value) props))
14335 (when (and (or (not specific) (string= specific "ALLTAGS"))
14336 (setq value (org-get-tags-at)))
14337 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14338 ":"))
14339 props))
14340 (when (or (not specific) (string= specific "BLOCKED"))
14341 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14342 (when (or (not specific)
14343 (member specific
14344 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14345 "TIMESTAMP" "TIMESTAMP_IA")))
14346 (catch 'match
14347 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14348 (setq key (if (match-end 1)
14349 (substring (org-match-string-no-properties 1)
14350 0 -1))
14351 string (if (equal key clockstr)
14352 (org-no-properties
14353 (org-trim
14354 (buffer-substring
14355 (match-beginning 3) (goto-char
14356 (point-at-eol)))))
14357 (substring (org-match-string-no-properties 3)
14358 1 -1)))
14359 ;; Get the correct property name from the key. This is
14360 ;; necessary if the user has configured time keywords.
14361 (setq key1 (concat key ":"))
14362 (cond
14363 ((not key)
14364 (setq key
14365 (if (= (char-after (match-beginning 3)) ?\[)
14366 "TIMESTAMP_IA" "TIMESTAMP")))
14367 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14368 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14369 ((equal key1 org-closed-string) (setq key "CLOSED"))
14370 ((equal key1 org-clock-string) (setq key "CLOCK")))
14371 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14372 (progn
14373 (push (cons key string) props)
14374 ;; no need to search further if match is found
14375 (throw 'match t))
14376 (when (or (equal key "CLOCK") (not (assoc key props)))
14377 (push (cons key string) props))))))
14380 (when (memq which '(all standard))
14381 ;; Get the standard properties, like :PROP: ...
14382 (setq range (org-get-property-block beg end))
14383 (when range
14384 (goto-char (car range))
14385 (while (re-search-forward
14386 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14387 (cdr range) t)
14388 (setq key (org-match-string-no-properties 1)
14389 value (org-trim (or (org-match-string-no-properties 2) "")))
14390 (unless (member key excluded)
14391 (push (cons key (or value "")) props)))))
14392 (if clocksum
14393 (push (cons "CLOCKSUM"
14394 (org-columns-number-to-string (/ (float clocksum) 60.)
14395 'add_times))
14396 props))
14397 (unless (assoc "CATEGORY" props)
14398 (push (cons "CATEGORY" (org-get-category)) props))
14399 (append sum-props (nreverse props)))))))
14401 (defun org-entry-get (pom property &optional inherit literal-nil)
14402 "Get value of PROPERTY for entry at point-or-marker POM.
14403 If INHERIT is non-nil and the entry does not have the property,
14404 then also check higher levels of the hierarchy.
14405 If INHERIT is the symbol `selective', use inheritance only if the setting
14406 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14407 If the property is present but empty, the return value is the empty string.
14408 If the property is not present at all, nil is returned.
14410 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14411 do not interpret it as the list atom nil. This is used for inheritance
14412 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14413 (org-with-point-at pom
14414 (if (and inherit (if (eq inherit 'selective)
14415 (org-property-inherit-p property)
14417 (org-entry-get-with-inheritance property literal-nil)
14418 (if (member property org-special-properties)
14419 ;; We need a special property. Use `org-entry-properties' to
14420 ;; retrieve it, but specify the wanted property
14421 (cdr (assoc property (org-entry-properties nil 'special property)))
14422 (let ((range (unless (org-before-first-heading-p)
14423 (org-get-property-block)))
14424 (props (list (or (assoc property org-file-properties)
14425 (assoc property org-global-properties)
14426 (assoc property org-global-properties-fixed))))
14427 val)
14428 (org-flet ((ap (key)
14429 (when (re-search-forward
14430 (org-re-property key) (cdr range) t)
14431 (setq props
14432 (org-update-property-plist
14434 (if (match-end 1)
14435 (org-match-string-no-properties 1) "")
14436 props)))))
14437 (when (and range (goto-char (car range)))
14438 (ap property)
14439 (goto-char (car range))
14440 (while (ap (concat property "+")))
14441 (setq val (cdr (assoc property props)))
14442 (when val (if literal-nil val (org-not-nil val))))))))))
14444 (defun org-property-or-variable-value (var &optional inherit)
14445 "Check if there is a property fixing the value of VAR.
14446 If yes, return this value. If not, return the current value of the variable."
14447 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14448 (if (and prop (stringp prop) (string-match "\\S-" prop))
14449 (read prop)
14450 (symbol-value var))))
14452 (defun org-entry-delete (pom property)
14453 "Delete the property PROPERTY from entry at point-or-marker POM."
14454 (org-with-point-at pom
14455 (if (member property org-special-properties)
14456 nil ; cannot delete these properties.
14457 (let ((range (org-get-property-block)))
14458 (if (and range
14459 (goto-char (car range))
14460 (re-search-forward
14461 (org-re-property property)
14462 (cdr range) t))
14463 (progn
14464 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14466 nil)))))
14468 ;; Multi-values properties are properties that contain multiple values
14469 ;; These values are assumed to be single words, separated by whitespace.
14470 (defun org-entry-add-to-multivalued-property (pom property value)
14471 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14472 (let* ((old (org-entry-get pom property))
14473 (values (and old (org-split-string old "[ \t]"))))
14474 (setq value (org-entry-protect-space value))
14475 (unless (member value values)
14476 (setq values (cons value values))
14477 (org-entry-put pom property
14478 (mapconcat 'identity values " ")))))
14480 (defun org-entry-remove-from-multivalued-property (pom property value)
14481 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14482 (let* ((old (org-entry-get pom property))
14483 (values (and old (org-split-string old "[ \t]"))))
14484 (setq value (org-entry-protect-space value))
14485 (when (member value values)
14486 (setq values (delete value values))
14487 (org-entry-put pom property
14488 (mapconcat 'identity values " ")))))
14490 (defun org-entry-member-in-multivalued-property (pom property value)
14491 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14492 (let* ((old (org-entry-get pom property))
14493 (values (and old (org-split-string old "[ \t]"))))
14494 (setq value (org-entry-protect-space value))
14495 (member value values)))
14497 (defun org-entry-get-multivalued-property (pom property)
14498 "Return a list of values in a multivalued property."
14499 (let* ((value (org-entry-get pom property))
14500 (values (and value (org-split-string value "[ \t]"))))
14501 (mapcar 'org-entry-restore-space values)))
14503 (defun org-entry-put-multivalued-property (pom property &rest values)
14504 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14505 VALUES should be a list of strings. Spaces will be protected."
14506 (org-entry-put pom property
14507 (mapconcat 'org-entry-protect-space values " "))
14508 (let* ((value (org-entry-get pom property))
14509 (values (and value (org-split-string value "[ \t]"))))
14510 (mapcar 'org-entry-restore-space values)))
14512 (defun org-entry-protect-space (s)
14513 "Protect spaces and newline in string S."
14514 (while (string-match " " s)
14515 (setq s (replace-match "%20" t t s)))
14516 (while (string-match "\n" s)
14517 (setq s (replace-match "%0A" t t s)))
14520 (defun org-entry-restore-space (s)
14521 "Restore spaces and newline in string S."
14522 (while (string-match "%20" s)
14523 (setq s (replace-match " " t t s)))
14524 (while (string-match "%0A" s)
14525 (setq s (replace-match "\n" t t s)))
14528 (defvar org-entry-property-inherited-from (make-marker)
14529 "Marker pointing to the entry from where a property was inherited.
14530 Each call to `org-entry-get-with-inheritance' will set this marker to the
14531 location of the entry where the inheritance search matched. If there was
14532 no match, the marker will point nowhere.
14533 Note that also `org-entry-get' calls this function, if the INHERIT flag
14534 is set.")
14536 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14537 "Get entry property, and search higher levels if not present.
14538 The search will stop at the first ancestor which has the property defined.
14539 If the value found is \"nil\", return nil to show that the property
14540 should be considered as undefined (this is the meaning of nil here).
14541 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14542 (move-marker org-entry-property-inherited-from nil)
14543 (let (tmp)
14544 (unless (org-before-first-heading-p)
14545 (save-excursion
14546 (save-restriction
14547 (widen)
14548 (catch 'ex
14549 (while t
14550 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14551 (org-back-to-heading t)
14552 (move-marker org-entry-property-inherited-from (point))
14553 (throw 'ex tmp))
14554 (or (org-up-heading-safe) (throw 'ex nil)))))))
14555 (setq tmp (or tmp
14556 (cdr (assoc property org-file-properties))
14557 (cdr (assoc property org-global-properties))
14558 (cdr (assoc property org-global-properties-fixed))))
14559 (if literal-nil tmp (org-not-nil tmp))))
14561 (defvar org-property-changed-functions nil
14562 "Hook called when the value of a property has changed.
14563 Each hook function should accept two arguments, the name of the property
14564 and the new value.")
14566 (defun org-entry-put (pom property value)
14567 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14568 (org-with-point-at pom
14569 (org-back-to-heading t)
14570 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14571 range)
14572 (cond
14573 ((equal property "TODO")
14574 (when (and (stringp value) (string-match "\\S-" value)
14575 (not (member value org-todo-keywords-1)))
14576 (error "\"%s\" is not a valid TODO state" value))
14577 (if (or (not value)
14578 (not (string-match "\\S-" value)))
14579 (setq value 'none))
14580 (org-todo value)
14581 (org-set-tags nil 'align))
14582 ((equal property "PRIORITY")
14583 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14584 (string-to-char value) ?\ ))
14585 (org-set-tags nil 'align))
14586 ((equal property "SCHEDULED")
14587 (if (re-search-forward org-scheduled-time-regexp end t)
14588 (cond
14589 ((eq value 'earlier) (org-timestamp-change -1 'day))
14590 ((eq value 'later) (org-timestamp-change 1 'day))
14591 (t (call-interactively 'org-schedule)))
14592 (call-interactively 'org-schedule)))
14593 ((equal property "DEADLINE")
14594 (if (re-search-forward org-deadline-time-regexp end t)
14595 (cond
14596 ((eq value 'earlier) (org-timestamp-change -1 'day))
14597 ((eq value 'later) (org-timestamp-change 1 'day))
14598 (t (call-interactively 'org-deadline)))
14599 (call-interactively 'org-deadline)))
14600 ((member property org-special-properties)
14601 (error "The %s property can not yet be set with `org-entry-put'"
14602 property))
14603 (t ; a non-special property
14604 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14605 (setq range (org-get-property-block beg end 'force))
14606 (goto-char (car range))
14607 (if (re-search-forward
14608 (org-re-property-keyword property) (cdr range) t)
14609 (progn
14610 (delete-region (match-beginning 0) (match-end 0))
14611 (goto-char (match-beginning 0)))
14612 (goto-char (cdr range))
14613 (insert "\n")
14614 (backward-char 1)
14615 (org-indent-line))
14616 (insert ":" property ":")
14617 (and value (insert " " value))
14618 (org-indent-line)))))
14619 (run-hook-with-args 'org-property-changed-functions property value)))
14621 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14622 "Get all property keys in the current buffer.
14623 With INCLUDE-SPECIALS, also list the special properties that reflect things
14624 like tags and TODO state.
14625 With INCLUDE-DEFAULTS, also include properties that has special meaning
14626 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14627 and others.
14628 With INCLUDE-COLUMNS, also include property names given in COLUMN
14629 formats in the current buffer."
14630 (let (rtn range cfmt s p)
14631 (save-excursion
14632 (save-restriction
14633 (widen)
14634 (goto-char (point-min))
14635 (while (re-search-forward org-property-start-re nil t)
14636 (setq range (org-get-property-block))
14637 (goto-char (car range))
14638 (while (re-search-forward
14639 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14640 (cdr range) t)
14641 (add-to-list 'rtn (org-match-string-no-properties 1)))
14642 (outline-next-heading))))
14644 (when include-specials
14645 (setq rtn (append org-special-properties rtn)))
14647 (when include-defaults
14648 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14649 (add-to-list 'rtn org-effort-property))
14651 (when include-columns
14652 (save-excursion
14653 (save-restriction
14654 (widen)
14655 (goto-char (point-min))
14656 (while (re-search-forward
14657 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14658 nil t)
14659 (setq cfmt (match-string 2) s 0)
14660 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14661 cfmt s)
14662 (setq s (match-end 0)
14663 p (match-string 1 cfmt))
14664 (unless (or (equal p "ITEM")
14665 (member p org-special-properties))
14666 (add-to-list 'rtn (match-string 1 cfmt))))))))
14668 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14670 (defun org-property-values (key)
14671 "Return a list of all values of property KEY in the current buffer."
14672 (save-excursion
14673 (save-restriction
14674 (widen)
14675 (goto-char (point-min))
14676 (let ((re (org-re-property key))
14677 values)
14678 (while (re-search-forward re nil t)
14679 (add-to-list 'values (org-trim (match-string 1))))
14680 (delete "" values)))))
14682 (defun org-insert-property-drawer ()
14683 "Insert a property drawer into the current entry."
14684 (org-back-to-heading t)
14685 (looking-at org-outline-regexp)
14686 (let ((indent (if org-adapt-indentation
14687 (- (match-end 0) (match-beginning 0))
14689 (beg (point))
14690 (re (concat "^[ \t]*" org-keyword-time-regexp))
14691 end hiddenp)
14692 (outline-next-heading)
14693 (setq end (point))
14694 (goto-char beg)
14695 (while (re-search-forward re end t))
14696 (setq hiddenp (outline-invisible-p))
14697 (end-of-line 1)
14698 (and (equal (char-after) ?\n) (forward-char 1))
14699 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14700 (if (member (match-string 1) '("CLOCK:" ":END:"))
14701 ;; just skip this line
14702 (beginning-of-line 2)
14703 ;; Drawer start, find the end
14704 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14705 (beginning-of-line 1)))
14706 (org-skip-over-state-notes)
14707 (skip-chars-backward " \t\n\r")
14708 (if (eq (char-before) ?*) (forward-char 1))
14709 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14710 (beginning-of-line 0)
14711 (org-indent-to-column indent)
14712 (beginning-of-line 2)
14713 (org-indent-to-column indent)
14714 (beginning-of-line 0)
14715 (if hiddenp
14716 (save-excursion
14717 (org-back-to-heading t)
14718 (hide-entry))
14719 (org-flag-drawer t))))
14721 (defun org-insert-drawer (&optional arg drawer)
14722 "Insert a drawer at point.
14724 Optional argument DRAWER, when non-nil, is a string representing
14725 drawer's name. Otherwise, the user is prompted for a name.
14727 If a region is active, insert the drawer around that region
14728 instead.
14730 Point is left between drawer's boundaries."
14731 (interactive "P")
14732 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14733 "LOGBOOK"))
14734 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14735 ;; internally by Org. They are meant to be inserted
14736 ;; automatically.
14737 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14738 ;; Remove system drawers from list. Note: For some reason,
14739 ;; `org-completing-read' ignores the predicate while
14740 ;; `completing-read' handles it fine.
14741 (drawer (if arg "PROPERTIES"
14742 (or drawer
14743 (completing-read
14744 "Drawer: " org-drawers
14745 (lambda (d) (not (member d system-drawers))))))))
14746 (cond
14747 ;; With C-u, fall back on `org-insert-property-drawer'
14748 (arg (org-insert-property-drawer))
14749 ;; With an active region, insert a drawer at point.
14750 ((not (org-region-active-p))
14751 (progn
14752 (unless (bolp) (insert "\n"))
14753 (insert (format ":%s:\n\n:END:\n" drawer))
14754 (forward-line -2)))
14755 ;; Otherwise, insert the drawer at point
14757 (let ((rbeg (region-beginning))
14758 (rend (copy-marker (region-end))))
14759 (unwind-protect
14760 (progn
14761 (goto-char rbeg)
14762 (beginning-of-line)
14763 (when (save-excursion
14764 (re-search-forward org-outline-regexp-bol rend t))
14765 (error "Drawers cannot contain headlines"))
14766 ;; Position point at the beginning of the first
14767 ;; non-blank line in region. Insert drawer's opening
14768 ;; there, then indent it.
14769 (org-skip-whitespace)
14770 (beginning-of-line)
14771 (insert ":" drawer ":\n")
14772 (forward-line -1)
14773 (indent-for-tab-command)
14774 ;; Move point to the beginning of the first blank line
14775 ;; after the last non-blank line in region. Insert
14776 ;; drawer's closing, then indent it.
14777 (goto-char rend)
14778 (skip-chars-backward " \r\t\n")
14779 (insert "\n:END:")
14780 (indent-for-tab-command)
14781 (unless (eolp) (insert "\n")))
14782 ;; Clear marker, whatever the outcome of insertion is.
14783 (set-marker rend nil)))))))
14785 (defvar org-property-set-functions-alist nil
14786 "Property set function alist.
14787 Each entry should have the following format:
14789 (PROPERTY . READ-FUNCTION)
14791 The read function will be called with the same argument as
14792 `org-completing-read'.")
14794 (defun org-set-property-function (property)
14795 "Get the function that should be used to set PROPERTY.
14796 This is computed according to `org-property-set-functions-alist'."
14797 (or (cdr (assoc property org-property-set-functions-alist))
14798 'org-completing-read))
14800 (defun org-read-property-value (property)
14801 "Read PROPERTY value from user."
14802 (let* ((completion-ignore-case t)
14803 (allowed (org-property-get-allowed-values nil property 'table))
14804 (cur (org-entry-get nil property))
14805 (prompt (concat property " value"
14806 (if (and cur (string-match "\\S-" cur))
14807 (concat " [" cur "]") "") ": "))
14808 (set-function (org-set-property-function property))
14809 (val (if allowed
14810 (funcall set-function prompt allowed nil
14811 (not (get-text-property 0 'org-unrestricted
14812 (caar allowed))))
14813 (let (org-completion-use-ido org-completion-use-iswitchb)
14814 (funcall set-function prompt
14815 (mapcar 'list (org-property-values property))
14816 nil nil "" nil cur)))))
14817 (if (equal val "")
14819 val)))
14821 (defvar org-last-set-property nil)
14822 (defun org-read-property-name ()
14823 "Read a property name."
14824 (let* ((completion-ignore-case t)
14825 (keys (org-buffer-property-keys nil t t))
14826 (default-prop (or (save-excursion
14827 (save-match-data
14828 (beginning-of-line)
14829 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14830 (null (string= (match-string 1) "END"))
14831 (match-string 1))))
14832 org-last-set-property))
14833 (property (org-icompleting-read
14834 (concat "Property"
14835 (if default-prop (concat " [" default-prop "]") "")
14836 ": ")
14837 (mapcar 'list keys)
14838 nil nil nil nil
14839 default-prop
14841 (if (member property keys)
14842 property
14843 (or (cdr (assoc (downcase property)
14844 (mapcar (lambda (x) (cons (downcase x) x))
14845 keys)))
14846 property))))
14848 (defun org-set-property (property value)
14849 "In the current entry, set PROPERTY to VALUE.
14850 When called interactively, this will prompt for a property name, offering
14851 completion on existing and default properties. And then it will prompt
14852 for a value, offering completion either on allowed values (via an inherited
14853 xxx_ALL property) or on existing values in other instances of this property
14854 in the current file."
14855 (interactive (list nil nil))
14856 (let* ((property (or property (org-read-property-name)))
14857 (value (or value (org-read-property-value property)))
14858 (fn (cdr (assoc property org-properties-postprocess-alist))))
14859 (setq org-last-set-property property)
14860 ;; Possibly postprocess the inserted value:
14861 (when fn (setq value (funcall fn value)))
14862 (unless (equal (org-entry-get nil property) value)
14863 (org-entry-put nil property value))))
14865 (defun org-delete-property (property)
14866 "In the current entry, delete PROPERTY."
14867 (interactive
14868 (let* ((completion-ignore-case t)
14869 (prop (org-icompleting-read "Property: "
14870 (org-entry-properties nil 'standard))))
14871 (list prop)))
14872 (message "Property %s %s" property
14873 (if (org-entry-delete nil property)
14874 "deleted"
14875 "was not present in the entry")))
14877 (defun org-delete-property-globally (property)
14878 "Remove PROPERTY globally, from all entries."
14879 (interactive
14880 (let* ((completion-ignore-case t)
14881 (prop (org-icompleting-read
14882 "Globally remove property: "
14883 (mapcar 'list (org-buffer-property-keys)))))
14884 (list prop)))
14885 (save-excursion
14886 (save-restriction
14887 (widen)
14888 (goto-char (point-min))
14889 (let ((cnt 0))
14890 (while (re-search-forward
14891 (org-re-property property)
14892 nil t)
14893 (setq cnt (1+ cnt))
14894 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14895 (message "Property \"%s\" removed from %d entries" property cnt)))))
14897 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14899 (defun org-compute-property-at-point ()
14900 "Compute the property at point.
14901 This looks for an enclosing column format, extracts the operator and
14902 then applies it to the property in the column format's scope."
14903 (interactive)
14904 (unless (org-at-property-p)
14905 (error "Not at a property"))
14906 (let ((prop (org-match-string-no-properties 2)))
14907 (org-columns-get-format-and-top-level)
14908 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14909 (error "No operator defined for property %s" prop))
14910 (org-columns-compute prop)))
14912 (defvar org-property-allowed-value-functions nil
14913 "Hook for functions supplying allowed values for a specific property.
14914 The functions must take a single argument, the name of the property, and
14915 return a flat list of allowed values. If \":ETC\" is one of
14916 the values, this means that these values are intended as defaults for
14917 completion, but that other values should be allowed too.
14918 The functions must return nil if they are not responsible for this
14919 property.")
14921 (defun org-property-get-allowed-values (pom property &optional table)
14922 "Get allowed values for the property PROPERTY.
14923 When TABLE is non-nil, return an alist that can directly be used for
14924 completion."
14925 (let (vals)
14926 (cond
14927 ((equal property "TODO")
14928 (setq vals (org-with-point-at pom
14929 (append org-todo-keywords-1 '("")))))
14930 ((equal property "PRIORITY")
14931 (let ((n org-lowest-priority))
14932 (while (>= n org-highest-priority)
14933 (push (char-to-string n) vals)
14934 (setq n (1- n)))))
14935 ((member property org-special-properties))
14936 ((setq vals (run-hook-with-args-until-success
14937 'org-property-allowed-value-functions property)))
14939 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14940 (when (and vals (string-match "\\S-" vals))
14941 (setq vals (car (read-from-string (concat "(" vals ")"))))
14942 (setq vals (mapcar (lambda (x)
14943 (cond ((stringp x) x)
14944 ((numberp x) (number-to-string x))
14945 ((symbolp x) (symbol-name x))
14946 (t "???")))
14947 vals)))))
14948 (when (member ":ETC" vals)
14949 (setq vals (remove ":ETC" vals))
14950 (org-add-props (car vals) '(org-unrestricted t)))
14951 (if table (mapcar 'list vals) vals)))
14953 (defun org-property-previous-allowed-value (&optional previous)
14954 "Switch to the next allowed value for this property."
14955 (interactive)
14956 (org-property-next-allowed-value t))
14958 (defun org-property-next-allowed-value (&optional previous)
14959 "Switch to the next allowed value for this property."
14960 (interactive)
14961 (unless (org-at-property-p)
14962 (error "Not at a property"))
14963 (let* ((key (match-string 2))
14964 (value (match-string 3))
14965 (allowed (or (org-property-get-allowed-values (point) key)
14966 (and (member value '("[ ]" "[-]" "[X]"))
14967 '("[ ]" "[X]"))))
14968 nval)
14969 (unless allowed
14970 (error "Allowed values for this property have not been defined"))
14971 (if previous (setq allowed (reverse allowed)))
14972 (if (member value allowed)
14973 (setq nval (car (cdr (member value allowed)))))
14974 (setq nval (or nval (car allowed)))
14975 (if (equal nval value)
14976 (error "Only one allowed value for this property"))
14977 (org-at-property-p)
14978 (replace-match (concat " :" key ": " nval) t t)
14979 (org-indent-line)
14980 (beginning-of-line 1)
14981 (skip-chars-forward " \t")
14982 (run-hook-with-args 'org-property-changed-functions key nval)))
14984 (defun org-find-olp (path &optional this-buffer)
14985 "Return a marker pointing to the entry at outline path OLP.
14986 If anything goes wrong, throw an error.
14987 You can wrap this call to catch the error like this:
14989 (condition-case msg
14990 (org-mobile-locate-entry (match-string 4))
14991 (error (nth 1 msg)))
14993 The return value will then be either a string with the error message,
14994 or a marker if everything is OK.
14996 If THIS-BUFFER is set, the outline path does not contain a file,
14997 only headings."
14998 (let* ((file (if this-buffer buffer-file-name (pop path)))
14999 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15000 (level 1)
15001 (lmin 1)
15002 (lmax 1)
15003 limit re end found pos heading cnt flevel)
15004 (unless buffer (error "File not found :%s" file))
15005 (with-current-buffer buffer
15006 (save-excursion
15007 (save-restriction
15008 (widen)
15009 (setq limit (point-max))
15010 (goto-char (point-min))
15011 (while (setq heading (pop path))
15012 (setq re (format org-complex-heading-regexp-format
15013 (regexp-quote heading)))
15014 (setq cnt 0 pos (point))
15015 (while (re-search-forward re end t)
15016 (setq level (- (match-end 1) (match-beginning 1)))
15017 (if (and (>= level lmin) (<= level lmax))
15018 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15019 (when (= cnt 0) (error "Heading not found on level %d: %s"
15020 lmax heading))
15021 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15022 lmax heading))
15023 (goto-char found)
15024 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15025 (setq end (save-excursion (org-end-of-subtree t t))))
15026 (when (org-at-heading-p)
15027 (move-marker (make-marker) (point))))))))
15029 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15030 "Find node HEADING in BUFFER.
15031 Return a marker to the heading if it was found, or nil if not.
15032 If POS-ONLY is set, return just the position instead of a marker.
15034 The heading text must match exact, but it may have a TODO keyword,
15035 a priority cookie and tags in the standard locations."
15036 (with-current-buffer (or buffer (current-buffer))
15037 (save-excursion
15038 (save-restriction
15039 (widen)
15040 (goto-char (point-min))
15041 (let (case-fold-search)
15042 (if (re-search-forward
15043 (format org-complex-heading-regexp-format
15044 (regexp-quote heading)) nil t)
15045 (if pos-only
15046 (match-beginning 0)
15047 (move-marker (make-marker) (match-beginning 0)))))))))
15049 (defun org-find-exact-heading-in-directory (heading &optional dir)
15050 "Find Org node headline HEADING in all .org files in directory DIR.
15051 When the target headline is found, return a marker to this location."
15052 (let ((files (directory-files (or dir default-directory)
15053 nil "\\`[^.#].*\\.org\\'"))
15054 file visiting m buffer)
15055 (catch 'found
15056 (while (setq file (pop files))
15057 (message "trying %s" file)
15058 (setq visiting (org-find-base-buffer-visiting file))
15059 (setq buffer (or visiting (find-file-noselect file)))
15060 (setq m (org-find-exact-headline-in-buffer
15061 heading buffer))
15062 (when (and (not m) (not visiting)) (kill-buffer buffer))
15063 (and m (throw 'found m))))))
15065 (defun org-find-entry-with-id (ident)
15066 "Locate the entry that contains the ID property with exact value IDENT.
15067 IDENT can be a string, a symbol or a number, this function will search for
15068 the string representation of it.
15069 Return the position where this entry starts, or nil if there is no such entry."
15070 (interactive "sID: ")
15071 (let ((id (cond
15072 ((stringp ident) ident)
15073 ((symbol-name ident) (symbol-name ident))
15074 ((numberp ident) (number-to-string ident))
15075 (t (error "IDENT %s must be a string, symbol or number" ident))))
15076 (case-fold-search nil))
15077 (save-excursion
15078 (save-restriction
15079 (widen)
15080 (goto-char (point-min))
15081 (when (re-search-forward
15082 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15083 nil t)
15084 (org-back-to-heading t)
15085 (point))))))
15087 ;;;; Timestamps
15089 (defvar org-last-changed-timestamp nil)
15090 (defvar org-last-inserted-timestamp nil
15091 "The last time stamp inserted with `org-insert-time-stamp'.")
15092 (defvar org-time-was-given) ; dynamically scoped parameter
15093 (defvar org-end-time-was-given) ; dynamically scoped parameter
15094 (defvar org-ts-what) ; dynamically scoped parameter
15096 (defun org-time-stamp (arg &optional inactive)
15097 "Prompt for a date/time and insert a time stamp.
15098 If the user specifies a time like HH:MM or if this command is
15099 called with at least one prefix argument, the time stamp contains
15100 the date and the time. Otherwise, only the date is be included.
15102 All parts of a date not specified by the user is filled in from
15103 the current date/time. So if you just press return without
15104 typing anything, the time stamp will represent the current
15105 date/time.
15107 If there is already a timestamp at the cursor, it will be
15108 modified.
15110 With two universal prefix arguments, insert an active timestamp
15111 with the current time without prompting the user."
15112 (interactive "P")
15113 (let* ((ts nil)
15114 (default-time
15115 ;; Default time is either today, or, when entering a range,
15116 ;; the range start.
15117 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15118 (save-excursion
15119 (re-search-backward
15120 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15121 (- (point) 20) t)))
15122 (apply 'encode-time (org-parse-time-string (match-string 1)))
15123 (current-time)))
15124 (default-input (and ts (org-get-compact-tod ts)))
15125 (repeater (save-excursion
15126 (save-match-data
15127 (beginning-of-line)
15128 (when (re-search-forward
15129 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15130 (save-excursion (progn (end-of-line) (point))) t)
15131 (match-string 0)))))
15132 org-time-was-given org-end-time-was-given time)
15133 (cond
15134 ((and (org-at-timestamp-p t)
15135 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15136 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15137 (insert "--")
15138 (setq time (let ((this-command this-command))
15139 (org-read-date arg 'totime nil nil
15140 default-time default-input inactive)))
15141 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15142 ((org-at-timestamp-p t)
15143 (setq time (let ((this-command this-command))
15144 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15145 (when (org-at-timestamp-p t) ; just to get the match data
15146 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15147 (replace-match "")
15148 (setq org-last-changed-timestamp
15149 (org-insert-time-stamp
15150 time (or org-time-was-given arg)
15151 inactive nil nil (list org-end-time-was-given)))
15152 (when repeater (goto-char (1- (point))) (insert " " repeater)
15153 (setq org-last-changed-timestamp
15154 (concat (substring org-last-inserted-timestamp 0 -1)
15155 " " repeater ">"))))
15156 (message "Timestamp updated"))
15157 ((equal arg '(16))
15158 (org-insert-time-stamp (current-time) t))
15160 (setq time (let ((this-command this-command))
15161 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15162 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15163 nil nil (list org-end-time-was-given))))))
15165 ;; FIXME: can we use this for something else, like computing time differences?
15166 (defun org-get-compact-tod (s)
15167 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15168 (let* ((t1 (match-string 1 s))
15169 (h1 (string-to-number (match-string 2 s)))
15170 (m1 (string-to-number (match-string 3 s)))
15171 (t2 (and (match-end 4) (match-string 5 s)))
15172 (h2 (and t2 (string-to-number (match-string 6 s))))
15173 (m2 (and t2 (string-to-number (match-string 7 s))))
15174 dh dm)
15175 (if (not t2)
15177 (setq dh (- h2 h1) dm (- m2 m1))
15178 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15179 (concat t1 "+" (number-to-string dh)
15180 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15182 (defun org-time-stamp-inactive (&optional arg)
15183 "Insert an inactive time stamp.
15184 An inactive time stamp is enclosed in square brackets instead of angle
15185 brackets. It is inactive in the sense that it does not trigger agenda entries,
15186 does not link to the calendar and cannot be changed with the S-cursor keys.
15187 So these are more for recording a certain time/date."
15188 (interactive "P")
15189 (org-time-stamp arg 'inactive))
15191 (defvar org-date-ovl (make-overlay 1 1))
15192 (overlay-put org-date-ovl 'face 'org-date-selected)
15193 (org-detach-overlay org-date-ovl)
15195 (defvar org-ans1) ; dynamically scoped parameter
15196 (defvar org-ans2) ; dynamically scoped parameter
15198 (defvar org-plain-time-of-day-regexp) ; defined below
15200 (defvar org-overriding-default-time nil) ; dynamically scoped
15201 (defvar org-read-date-overlay nil)
15202 (defvar org-dcst nil) ; dynamically scoped
15203 (defvar org-read-date-history nil)
15204 (defvar org-read-date-final-answer nil)
15205 (defvar org-read-date-analyze-futurep nil)
15206 (defvar org-read-date-analyze-forced-year nil)
15207 (defvar org-read-date-inactive)
15209 (defun org-read-date (&optional org-with-time to-time from-string prompt
15210 default-time default-input inactive)
15211 "Read a date, possibly a time, and make things smooth for the user.
15212 The prompt will suggest to enter an ISO date, but you can also enter anything
15213 which will at least partially be understood by `parse-time-string'.
15214 Unrecognized parts of the date will default to the current day, month, year,
15215 hour and minute. If this command is called to replace a timestamp at point,
15216 or to enter the second timestamp of a range, the default time is taken
15217 from the existing stamp. Furthermore, the command prefers the future,
15218 so if you are giving a date where the year is not given, and the day-month
15219 combination is already past in the current year, it will assume you
15220 mean next year. For details, see the manual. A few examples:
15222 3-2-5 --> 2003-02-05
15223 feb 15 --> currentyear-02-15
15224 2/15 --> currentyear-02-15
15225 sep 12 9 --> 2009-09-12
15226 12:45 --> today 12:45
15227 22 sept 0:34 --> currentyear-09-22 0:34
15228 12 --> currentyear-currentmonth-12
15229 Fri --> nearest Friday (today or later)
15230 etc.
15232 Furthermore you can specify a relative date by giving, as the *first* thing
15233 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15234 change in days weeks, months, years.
15235 With a single plus or minus, the date is relative to today. With a double
15236 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15237 +4d --> four days from today
15238 +4 --> same as above
15239 +2w --> two weeks from today
15240 ++5 --> five days from default date
15242 The function understands only English month and weekday abbreviations.
15244 While prompting, a calendar is popped up - you can also select the
15245 date with the mouse (button 1). The calendar shows a period of three
15246 months. To scroll it to other months, use the keys `>' and `<'.
15247 If you don't like the calendar, turn it off with
15248 \(setq org-read-date-popup-calendar nil)
15250 With optional argument TO-TIME, the date will immediately be converted
15251 to an internal time.
15252 With an optional argument WITH-TIME, the prompt will suggest to also
15253 insert a time. Note that when WITH-TIME is not set, you can still
15254 enter a time, and this function will inform the calling routine about
15255 this change. The calling routine may then choose to change the format
15256 used to insert the time stamp into the buffer to include the time.
15257 With optional argument FROM-STRING, read from this string instead from
15258 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15259 the time/date that is used for everything that is not specified by the
15260 user."
15261 (require 'parse-time)
15262 (let* ((org-time-stamp-rounding-minutes
15263 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15264 (org-dcst org-display-custom-times)
15265 (ct (org-current-time))
15266 (org-def (or org-overriding-default-time default-time ct))
15267 (org-defdecode (decode-time org-def))
15268 (dummy (progn
15269 (when (< (nth 2 org-defdecode) org-extend-today-until)
15270 (setcar (nthcdr 2 org-defdecode) -1)
15271 (setcar (nthcdr 1 org-defdecode) 59)
15272 (setq org-def (apply 'encode-time org-defdecode)
15273 org-defdecode (decode-time org-def)))))
15274 (calendar-frame-setup nil)
15275 (calendar-setup nil)
15276 (calendar-move-hook nil)
15277 (calendar-view-diary-initially-flag nil)
15278 (calendar-view-holidays-initially-flag nil)
15279 (timestr (format-time-string
15280 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15281 (prompt (concat (if prompt (concat prompt " ") "")
15282 (format "Date+time [%s]: " timestr)))
15283 ans (org-ans0 "") org-ans1 org-ans2 final)
15285 (cond
15286 (from-string (setq ans from-string))
15287 (org-read-date-popup-calendar
15288 (save-excursion
15289 (save-window-excursion
15290 (calendar)
15291 (org-eval-in-calendar '(setq cursor-type nil) t)
15292 (unwind-protect
15293 (progn
15294 (calendar-forward-day (- (time-to-days org-def)
15295 (calendar-absolute-from-gregorian
15296 (calendar-current-date))))
15297 (org-eval-in-calendar nil t)
15298 (let* ((old-map (current-local-map))
15299 (map (copy-keymap calendar-mode-map))
15300 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15301 (org-defkey map (kbd "RET") 'org-calendar-select)
15302 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15303 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15304 (org-defkey minibuffer-local-map [(meta shift left)]
15305 (lambda () (interactive)
15306 (org-eval-in-calendar '(calendar-backward-month 1))))
15307 (org-defkey minibuffer-local-map [(meta shift right)]
15308 (lambda () (interactive)
15309 (org-eval-in-calendar '(calendar-forward-month 1))))
15310 (org-defkey minibuffer-local-map [(meta shift up)]
15311 (lambda () (interactive)
15312 (org-eval-in-calendar '(calendar-backward-year 1))))
15313 (org-defkey minibuffer-local-map [(meta shift down)]
15314 (lambda () (interactive)
15315 (org-eval-in-calendar '(calendar-forward-year 1))))
15316 (org-defkey minibuffer-local-map [?\e (shift left)]
15317 (lambda () (interactive)
15318 (org-eval-in-calendar '(calendar-backward-month 1))))
15319 (org-defkey minibuffer-local-map [?\e (shift right)]
15320 (lambda () (interactive)
15321 (org-eval-in-calendar '(calendar-forward-month 1))))
15322 (org-defkey minibuffer-local-map [?\e (shift up)]
15323 (lambda () (interactive)
15324 (org-eval-in-calendar '(calendar-backward-year 1))))
15325 (org-defkey minibuffer-local-map [?\e (shift down)]
15326 (lambda () (interactive)
15327 (org-eval-in-calendar '(calendar-forward-year 1))))
15328 (org-defkey minibuffer-local-map [(shift up)]
15329 (lambda () (interactive)
15330 (org-eval-in-calendar '(calendar-backward-week 1))))
15331 (org-defkey minibuffer-local-map [(shift down)]
15332 (lambda () (interactive)
15333 (org-eval-in-calendar '(calendar-forward-week 1))))
15334 (org-defkey minibuffer-local-map [(shift left)]
15335 (lambda () (interactive)
15336 (org-eval-in-calendar '(calendar-backward-day 1))))
15337 (org-defkey minibuffer-local-map [(shift right)]
15338 (lambda () (interactive)
15339 (org-eval-in-calendar '(calendar-forward-day 1))))
15340 (org-defkey minibuffer-local-map ">"
15341 (lambda () (interactive)
15342 (org-eval-in-calendar '(scroll-calendar-left 1))))
15343 (org-defkey minibuffer-local-map "<"
15344 (lambda () (interactive)
15345 (org-eval-in-calendar '(scroll-calendar-right 1))))
15346 (org-defkey minibuffer-local-map "\C-v"
15347 (lambda () (interactive)
15348 (org-eval-in-calendar
15349 '(calendar-scroll-left-three-months 1))))
15350 (org-defkey minibuffer-local-map "\M-v"
15351 (lambda () (interactive)
15352 (org-eval-in-calendar
15353 '(calendar-scroll-right-three-months 1))))
15354 (run-hooks 'org-read-date-minibuffer-setup-hook)
15355 (unwind-protect
15356 (progn
15357 (use-local-map map)
15358 (setq org-read-date-inactive inactive)
15359 (add-hook 'post-command-hook 'org-read-date-display)
15360 (setq org-ans0 (read-string prompt default-input
15361 'org-read-date-history nil))
15362 ;; org-ans0: from prompt
15363 ;; org-ans1: from mouse click
15364 ;; org-ans2: from calendar motion
15365 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15366 (remove-hook 'post-command-hook 'org-read-date-display)
15367 (use-local-map old-map)
15368 (when org-read-date-overlay
15369 (delete-overlay org-read-date-overlay)
15370 (setq org-read-date-overlay nil)))))
15371 (bury-buffer "*Calendar*")))))
15373 (t ; Naked prompt only
15374 (unwind-protect
15375 (setq ans (read-string prompt default-input
15376 'org-read-date-history timestr))
15377 (when org-read-date-overlay
15378 (delete-overlay org-read-date-overlay)
15379 (setq org-read-date-overlay nil)))))
15381 (setq final (org-read-date-analyze ans org-def org-defdecode))
15383 (when org-read-date-analyze-forced-year
15384 (message "Year was forced into %s"
15385 (if org-read-date-force-compatible-dates
15386 "compatible range (1970-2037)"
15387 "range representable on this machine"))
15388 (ding))
15390 ;; One round trip to get rid of 34th of August and stuff like that....
15391 (setq final (decode-time (apply 'encode-time final)))
15393 (setq org-read-date-final-answer ans)
15395 (if to-time
15396 (apply 'encode-time final)
15397 (if (and (boundp 'org-time-was-given) org-time-was-given)
15398 (format "%04d-%02d-%02d %02d:%02d"
15399 (nth 5 final) (nth 4 final) (nth 3 final)
15400 (nth 2 final) (nth 1 final))
15401 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15403 (defvar org-def)
15404 (defvar org-defdecode)
15405 (defvar org-with-time)
15406 (defun org-read-date-display ()
15407 "Display the current date prompt interpretation in the minibuffer."
15408 (when org-read-date-display-live
15409 (when org-read-date-overlay
15410 (delete-overlay org-read-date-overlay))
15411 (when (minibufferp (current-buffer))
15412 (save-excursion
15413 (end-of-line 1)
15414 (while (not (equal (buffer-substring
15415 (max (point-min) (- (point) 4)) (point))
15416 " "))
15417 (insert " ")))
15418 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15419 " " (or org-ans1 org-ans2)))
15420 (org-end-time-was-given nil)
15421 (f (org-read-date-analyze ans org-def org-defdecode))
15422 (fmts (if org-dcst
15423 org-time-stamp-custom-formats
15424 org-time-stamp-formats))
15425 (fmt (if (or org-with-time
15426 (and (boundp 'org-time-was-given) org-time-was-given))
15427 (cdr fmts)
15428 (car fmts)))
15429 (txt (format-time-string fmt (apply 'encode-time f)))
15430 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15431 (txt (concat "=> " txt)))
15432 (when (and org-end-time-was-given
15433 (string-match org-plain-time-of-day-regexp txt))
15434 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15435 org-end-time-was-given
15436 (substring txt (match-end 0)))))
15437 (when org-read-date-analyze-futurep
15438 (setq txt (concat txt " (=>F)")))
15439 (setq org-read-date-overlay
15440 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15441 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15443 (defun org-read-date-analyze (ans org-def org-defdecode)
15444 "Analyze the combined answer of the date prompt."
15445 ;; FIXME: cleanup and comment
15446 (let ((nowdecode (decode-time (current-time)))
15447 delta deltan deltaw deltadef year month day
15448 hour minute second wday pm h2 m2 tl wday1
15449 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15450 (setq org-read-date-analyze-futurep nil
15451 org-read-date-analyze-forced-year nil)
15452 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15453 (setq ans "+0"))
15455 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15456 (setq ans (replace-match "" t t ans)
15457 deltan (car delta)
15458 deltaw (nth 1 delta)
15459 deltadef (nth 2 delta)))
15461 ;; Check if there is an iso week date in there
15462 ;; If yes, store the info and postpone interpreting it until the rest
15463 ;; of the parsing is done
15464 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15465 (setq iso-year (if (match-end 1)
15466 (org-small-year-to-year
15467 (string-to-number (match-string 1 ans))))
15468 iso-weekday (if (match-end 3)
15469 (string-to-number (match-string 3 ans)))
15470 iso-week (string-to-number (match-string 2 ans)))
15471 (setq ans (replace-match "" t t ans)))
15473 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15474 (when (string-match
15475 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15476 (setq year (if (match-end 2)
15477 (string-to-number (match-string 2 ans))
15478 (progn (setq kill-year t)
15479 (string-to-number (format-time-string "%Y"))))
15480 month (string-to-number (match-string 3 ans))
15481 day (string-to-number (match-string 4 ans)))
15482 (if (< year 100) (setq year (+ 2000 year)))
15483 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15484 t nil ans)))
15486 ;; Help matching dotted european dates
15487 (when (string-match
15488 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15489 (setq year (if (match-end 3)
15490 (string-to-number (match-string 3 ans))
15491 (progn (setq kill-year t)
15492 (string-to-number (format-time-string "%Y"))))
15493 day (string-to-number (match-string 1 ans))
15494 month (string-to-number (match-string 2 ans))
15495 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15496 t nil ans)))
15498 ;; Help matching american dates, like 5/30 or 5/30/7
15499 (when (string-match
15500 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15501 (setq year (if (match-end 4)
15502 (string-to-number (match-string 4 ans))
15503 (progn (setq kill-year t)
15504 (string-to-number (format-time-string "%Y"))))
15505 month (string-to-number (match-string 1 ans))
15506 day (string-to-number (match-string 2 ans)))
15507 (if (< year 100) (setq year (+ 2000 year)))
15508 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15509 t nil ans)))
15510 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15511 ;; If there is a time with am/pm, and *no* time without it, we convert
15512 ;; so that matching will be successful.
15513 (loop for i from 1 to 2 do ; twice, for end time as well
15514 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15515 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15516 (setq hour (string-to-number (match-string 1 ans))
15517 minute (if (match-end 3)
15518 (string-to-number (match-string 3 ans))
15520 pm (equal ?p
15521 (string-to-char (downcase (match-string 4 ans)))))
15522 (if (and (= hour 12) (not pm))
15523 (setq hour 0)
15524 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15525 (setq ans (replace-match (format "%02d:%02d" hour minute)
15526 t t ans))))
15528 ;; Check if a time range is given as a duration
15529 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15530 (setq hour (string-to-number (match-string 1 ans))
15531 h2 (+ hour (string-to-number (match-string 3 ans)))
15532 minute (string-to-number (match-string 2 ans))
15533 m2 (+ minute (if (match-end 5) (string-to-number
15534 (match-string 5 ans))0)))
15535 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15536 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15537 t t ans)))
15539 ;; Check if there is a time range
15540 (when (boundp 'org-end-time-was-given)
15541 (setq org-time-was-given nil)
15542 (when (and (string-match org-plain-time-of-day-regexp ans)
15543 (match-end 8))
15544 (setq org-end-time-was-given (match-string 8 ans))
15545 (setq ans (concat (substring ans 0 (match-beginning 7))
15546 (substring ans (match-end 7))))))
15548 (setq tl (parse-time-string ans)
15549 day (or (nth 3 tl) (nth 3 org-defdecode))
15550 month (or (nth 4 tl)
15551 (if (and org-read-date-prefer-future
15552 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15553 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15554 (nth 4 org-defdecode)))
15555 year (or (and (not kill-year) (nth 5 tl))
15556 (if (and org-read-date-prefer-future
15557 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15558 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15559 (nth 5 org-defdecode)))
15560 hour (or (nth 2 tl) (nth 2 org-defdecode))
15561 minute (or (nth 1 tl) (nth 1 org-defdecode))
15562 second (or (nth 0 tl) 0)
15563 wday (nth 6 tl))
15565 (when (and (eq org-read-date-prefer-future 'time)
15566 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15567 (equal day (nth 3 nowdecode))
15568 (equal month (nth 4 nowdecode))
15569 (equal year (nth 5 nowdecode))
15570 (nth 2 tl)
15571 (or (< (nth 2 tl) (nth 2 nowdecode))
15572 (and (= (nth 2 tl) (nth 2 nowdecode))
15573 (nth 1 tl)
15574 (< (nth 1 tl) (nth 1 nowdecode)))))
15575 (setq day (1+ day)
15576 futurep t))
15578 ;; Special date definitions below
15579 (cond
15580 (iso-week
15581 ;; There was an iso week
15582 (require 'cal-iso)
15583 (setq futurep nil)
15584 (setq year (or iso-year year)
15585 day (or iso-weekday wday 1)
15586 wday nil ; to make sure that the trigger below does not match
15587 iso-date (calendar-gregorian-from-absolute
15588 (calendar-absolute-from-iso
15589 (list iso-week day year))))
15590 ; FIXME: Should we also push ISO weeks into the future?
15591 ; (when (and org-read-date-prefer-future
15592 ; (not iso-year)
15593 ; (< (calendar-absolute-from-gregorian iso-date)
15594 ; (time-to-days (current-time))))
15595 ; (setq year (1+ year)
15596 ; iso-date (calendar-gregorian-from-absolute
15597 ; (calendar-absolute-from-iso
15598 ; (list iso-week day year)))))
15599 (setq month (car iso-date)
15600 year (nth 2 iso-date)
15601 day (nth 1 iso-date)))
15602 (deltan
15603 (setq futurep nil)
15604 (unless deltadef
15605 (let ((now (decode-time (current-time))))
15606 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15607 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15608 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15609 ((equal deltaw "m") (setq month (+ month deltan)))
15610 ((equal deltaw "y") (setq year (+ year deltan)))))
15611 ((and wday (not (nth 3 tl)))
15612 (setq futurep nil)
15613 ;; Weekday was given, but no day, so pick that day in the week
15614 ;; on or after the derived date.
15615 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15616 (unless (equal wday wday1)
15617 (setq day (+ day (% (- wday wday1 -7) 7))))))
15618 (if (and (boundp 'org-time-was-given)
15619 (nth 2 tl))
15620 (setq org-time-was-given t))
15621 (if (< year 100) (setq year (+ 2000 year)))
15622 ;; Check of the date is representable
15623 (if org-read-date-force-compatible-dates
15624 (progn
15625 (if (< year 1970)
15626 (setq year 1970 org-read-date-analyze-forced-year t))
15627 (if (> year 2037)
15628 (setq year 2037 org-read-date-analyze-forced-year t)))
15629 (condition-case nil
15630 (ignore (encode-time second minute hour day month year))
15631 (error
15632 (setq year (nth 5 org-defdecode))
15633 (setq org-read-date-analyze-forced-year t))))
15634 (setq org-read-date-analyze-futurep futurep)
15635 (list second minute hour day month year)))
15637 (defvar parse-time-weekdays)
15638 (defun org-read-date-get-relative (s today default)
15639 "Check string S for special relative date string.
15640 TODAY and DEFAULT are internal times, for today and for a default.
15641 Return shift list (N what def-flag)
15642 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15643 N is the number of WHATs to shift.
15644 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15645 the DEFAULT date rather than TODAY."
15646 (require 'parse-time)
15647 (when (and
15648 (string-match
15649 (concat
15650 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15651 "\\([0-9]+\\)?"
15652 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15653 "\\([ \t]\\|$\\)") s)
15654 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15655 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15656 (string-to-char (substring (match-string 1 s) -1))
15657 ?+))
15658 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15659 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15660 (what (if (match-end 3) (match-string 3 s) "d"))
15661 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15662 (date (if rel default today))
15663 (wday (nth 6 (decode-time date)))
15664 delta)
15665 (if wday1
15666 (progn
15667 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15668 (if (= dir ?-) (setq delta (- delta 7)))
15669 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15670 (list delta "d" rel))
15671 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15673 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15674 "Turn a user-specified date into the internal representation.
15675 The internal representation needed by the calendar is (month day year).
15676 This is a wrapper to handle the brain-dead convention in calendar that
15677 user function argument order change dependent on argument order."
15678 (if (boundp 'calendar-date-style)
15679 (cond
15680 ((eq calendar-date-style 'american)
15681 (list arg1 arg2 arg3))
15682 ((eq calendar-date-style 'european)
15683 (list arg2 arg1 arg3))
15684 ((eq calendar-date-style 'iso)
15685 (list arg2 arg3 arg1)))
15686 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15687 (if (org-bound-and-true-p european-calendar-style)
15688 (list arg2 arg1 arg3)
15689 (list arg1 arg2 arg3)))))
15691 (defun org-eval-in-calendar (form &optional keepdate)
15692 "Eval FORM in the calendar window and return to current window.
15693 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15694 otherwise stick to the current value of `org-ans2'."
15695 (let ((sf (selected-frame))
15696 (sw (selected-window)))
15697 (select-window (get-buffer-window "*Calendar*" t))
15698 (eval form)
15699 (when (and (not keepdate) (calendar-cursor-to-date))
15700 (let* ((date (calendar-cursor-to-date))
15701 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15702 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15703 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15704 (select-window sw)
15705 (org-select-frame-set-input-focus sf)))
15707 (defun org-calendar-select ()
15708 "Return to `org-read-date' with the date currently selected.
15709 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15710 (interactive)
15711 (when (calendar-cursor-to-date)
15712 (let* ((date (calendar-cursor-to-date))
15713 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15714 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15715 (if (active-minibuffer-window) (exit-minibuffer))))
15717 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15718 "Insert a date stamp for the date given by the internal TIME.
15719 WITH-HM means use the stamp format that includes the time of the day.
15720 INACTIVE means use square brackets instead of angular ones, so that the
15721 stamp will not contribute to the agenda.
15722 PRE and POST are optional strings to be inserted before and after the
15723 stamp.
15724 The command returns the inserted time stamp."
15725 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15726 stamp)
15727 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15728 (insert-before-markers (or pre ""))
15729 (when (listp extra)
15730 (setq extra (car extra))
15731 (if (and (stringp extra)
15732 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15733 (setq extra (format "-%02d:%02d"
15734 (string-to-number (match-string 1 extra))
15735 (string-to-number (match-string 2 extra))))
15736 (setq extra nil)))
15737 (when extra
15738 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15739 (insert-before-markers (setq stamp (format-time-string fmt time)))
15740 (insert-before-markers (or post ""))
15741 (setq org-last-inserted-timestamp stamp)))
15743 (defun org-toggle-time-stamp-overlays ()
15744 "Toggle the use of custom time stamp formats."
15745 (interactive)
15746 (setq org-display-custom-times (not org-display-custom-times))
15747 (unless org-display-custom-times
15748 (let ((p (point-min)) (bmp (buffer-modified-p)))
15749 (while (setq p (next-single-property-change p 'display))
15750 (if (and (get-text-property p 'display)
15751 (eq (get-text-property p 'face) 'org-date))
15752 (remove-text-properties
15753 p (setq p (next-single-property-change p 'display))
15754 '(display t))))
15755 (set-buffer-modified-p bmp)))
15756 (if (featurep 'xemacs)
15757 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15758 (org-restart-font-lock)
15759 (setq org-table-may-need-update t)
15760 (if org-display-custom-times
15761 (message "Time stamps are overlaid with custom format")
15762 (message "Time stamp overlays removed")))
15764 (defun org-display-custom-time (beg end)
15765 "Overlay modified time stamp format over timestamp between BEG and END."
15766 (let* ((ts (buffer-substring beg end))
15767 t1 w1 with-hm tf time str w2 (off 0))
15768 (save-match-data
15769 (setq t1 (org-parse-time-string ts t))
15770 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15771 (setq off (- (match-end 0) (match-beginning 0)))))
15772 (setq end (- end off))
15773 (setq w1 (- end beg)
15774 with-hm (and (nth 1 t1) (nth 2 t1))
15775 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15776 time (org-fix-decoded-time t1)
15777 str (org-add-props
15778 (format-time-string
15779 (substring tf 1 -1) (apply 'encode-time time))
15780 nil 'mouse-face 'highlight)
15781 w2 (length str))
15782 (if (not (= w2 w1))
15783 (add-text-properties (1+ beg) (+ 2 beg)
15784 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15785 (if (featurep 'xemacs)
15786 (progn
15787 (put-text-property beg end 'invisible t)
15788 (put-text-property beg end 'end-glyph (make-glyph str)))
15789 (put-text-property beg end 'display str))))
15791 (defun org-translate-time (string)
15792 "Translate all timestamps in STRING to custom format.
15793 But do this only if the variable `org-display-custom-times' is set."
15794 (when org-display-custom-times
15795 (save-match-data
15796 (let* ((start 0)
15797 (re org-ts-regexp-both)
15798 t1 with-hm inactive tf time str beg end)
15799 (while (setq start (string-match re string start))
15800 (setq beg (match-beginning 0)
15801 end (match-end 0)
15802 t1 (save-match-data
15803 (org-parse-time-string (substring string beg end) t))
15804 with-hm (and (nth 1 t1) (nth 2 t1))
15805 inactive (equal (substring string beg (1+ beg)) "[")
15806 tf (funcall (if with-hm 'cdr 'car)
15807 org-time-stamp-custom-formats)
15808 time (org-fix-decoded-time t1)
15809 str (format-time-string
15810 (concat
15811 (if inactive "[" "<") (substring tf 1 -1)
15812 (if inactive "]" ">"))
15813 (apply 'encode-time time))
15814 string (replace-match str t t string)
15815 start (+ start (length str)))))))
15816 string)
15818 (defun org-fix-decoded-time (time)
15819 "Set 0 instead of nil for the first 6 elements of time.
15820 Don't touch the rest."
15821 (let ((n 0))
15822 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15824 (defun org-days-to-time (timestamp-string)
15825 "Difference between TIMESTAMP-STRING and now in days."
15826 (- (time-to-days (org-time-string-to-time timestamp-string))
15827 (time-to-days (current-time))))
15829 (defun org-deadline-close (timestamp-string &optional ndays)
15830 "Is the time in TIMESTAMP-STRING close to the current date?"
15831 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15832 (and (< (org-days-to-time timestamp-string) ndays)
15833 (not (org-entry-is-done-p))))
15835 (defun org-get-wdays (ts)
15836 "Get the deadline lead time appropriate for timestring TS."
15837 (cond
15838 ((<= org-deadline-warning-days 0)
15839 ;; 0 or negative, enforce this value no matter what
15840 (- org-deadline-warning-days))
15841 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15842 ;; lead time is specified.
15843 (floor (* (string-to-number (match-string 1 ts))
15844 (cdr (assoc (match-string 2 ts)
15845 '(("d" . 1) ("w" . 7)
15846 ("m" . 30.4) ("y" . 365.25)))))))
15847 ;; go for the default.
15848 (t org-deadline-warning-days)))
15850 (defun org-calendar-select-mouse (ev)
15851 "Return to `org-read-date' with the date currently selected.
15852 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15853 (interactive "e")
15854 (mouse-set-point ev)
15855 (when (calendar-cursor-to-date)
15856 (let* ((date (calendar-cursor-to-date))
15857 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15858 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15859 (if (active-minibuffer-window) (exit-minibuffer))))
15861 (defun org-check-deadlines (ndays)
15862 "Check if there are any deadlines due or past due.
15863 A deadline is considered due if it happens within `org-deadline-warning-days'
15864 days from today's date. If the deadline appears in an entry marked DONE,
15865 it is not shown. The prefix arg NDAYS can be used to test that many
15866 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15867 (interactive "P")
15868 (let* ((org-warn-days
15869 (cond
15870 ((equal ndays '(4)) 100000)
15871 (ndays (prefix-numeric-value ndays))
15872 (t (abs org-deadline-warning-days))))
15873 (case-fold-search nil)
15874 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15875 (callback
15876 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15878 (message "%d deadlines past-due or due within %d days"
15879 (org-occur regexp nil callback)
15880 org-warn-days)))
15882 (defsubst org-re-timestamp (type)
15883 "Return a regexp for timestamp TYPE.
15884 Allowed values for TYPE are:
15886 all: all timestamps
15887 active: only active timestamps (<...>)
15888 inactive: only inactive timestamps ([...])
15889 scheduled: only scheduled timestamps
15890 deadline: only deadline timestamps
15892 When TYPE is nil, fall back on returning a regexp that matches
15893 both scheduled and deadline timestamps."
15894 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15895 ((eq type 'active) org-ts-regexp)
15896 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15897 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15898 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15899 ((eq type 'scheduled-or-deadline)
15900 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15902 (defun org-check-before-date (date)
15903 "Check if there are deadlines or scheduled entries before DATE."
15904 (interactive (list (org-read-date)))
15905 (let ((case-fold-search nil)
15906 (regexp (org-re-timestamp org-ts-type))
15907 (callback
15908 (lambda () (time-less-p
15909 (org-time-string-to-time (match-string 1))
15910 (org-time-string-to-time date)))))
15911 (message "%d entries before %s"
15912 (org-occur regexp nil callback) date)))
15914 (defun org-check-after-date (date)
15915 "Check if there are deadlines or scheduled entries after DATE."
15916 (interactive (list (org-read-date)))
15917 (let ((case-fold-search nil)
15918 (regexp (org-re-timestamp org-ts-type))
15919 (callback
15920 (lambda () (not
15921 (time-less-p
15922 (org-time-string-to-time (match-string 1))
15923 (org-time-string-to-time date))))))
15924 (message "%d entries after %s"
15925 (org-occur regexp nil callback) date)))
15927 (defun org-check-dates-range (start-date end-date)
15928 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15929 (interactive (list (org-read-date nil nil nil "Range starts")
15930 (org-read-date nil nil nil "Range end")))
15931 (let ((case-fold-search nil)
15932 (regexp (org-re-timestamp org-ts-type))
15933 (callback
15934 (lambda ()
15935 (let ((match (match-string 1)))
15936 (and
15937 (not (time-less-p
15938 (org-time-string-to-time match)
15939 (org-time-string-to-time start-date)))
15940 (time-less-p
15941 (org-time-string-to-time match)
15942 (org-time-string-to-time end-date)))))))
15943 (message "%d entries between %s and %s"
15944 (org-occur regexp nil callback) start-date end-date)))
15946 (defun org-evaluate-time-range (&optional to-buffer)
15947 "Evaluate a time range by computing the difference between start and end.
15948 Normally the result is just printed in the echo area, but with prefix arg
15949 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15950 If the time range is actually in a table, the result is inserted into the
15951 next column.
15952 For time difference computation, a year is assumed to be exactly 365
15953 days in order to avoid rounding problems."
15954 (interactive "P")
15956 (org-clock-update-time-maybe)
15957 (save-excursion
15958 (unless (org-at-date-range-p t)
15959 (goto-char (point-at-bol))
15960 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15961 (if (not (org-at-date-range-p t))
15962 (error "Not at a time-stamp range, and none found in current line")))
15963 (let* ((ts1 (match-string 1))
15964 (ts2 (match-string 2))
15965 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15966 (match-end (match-end 0))
15967 (time1 (org-time-string-to-time ts1))
15968 (time2 (org-time-string-to-time ts2))
15969 (t1 (org-float-time time1))
15970 (t2 (org-float-time time2))
15971 (diff (abs (- t2 t1)))
15972 (negative (< (- t2 t1) 0))
15973 ;; (ys (floor (* 365 24 60 60)))
15974 (ds (* 24 60 60))
15975 (hs (* 60 60))
15976 (fy "%dy %dd %02d:%02d")
15977 (fy1 "%dy %dd")
15978 (fd "%dd %02d:%02d")
15979 (fd1 "%dd")
15980 (fh "%02d:%02d")
15981 y d h m align)
15982 (if havetime
15983 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15985 d (floor (/ diff ds)) diff (mod diff ds)
15986 h (floor (/ diff hs)) diff (mod diff hs)
15987 m (floor (/ diff 60)))
15988 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15990 d (floor (+ (/ diff ds) 0.5))
15991 h 0 m 0))
15992 (if (not to-buffer)
15993 (message "%s" (org-make-tdiff-string y d h m))
15994 (if (org-at-table-p)
15995 (progn
15996 (goto-char match-end)
15997 (setq align t)
15998 (and (looking-at " *|") (goto-char (match-end 0))))
15999 (goto-char match-end))
16000 (if (looking-at
16001 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16002 (replace-match ""))
16003 (if negative (insert " -"))
16004 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16005 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16006 (insert " " (format fh h m))))
16007 (if align (org-table-align))
16008 (message "Time difference inserted")))))
16010 (defun org-make-tdiff-string (y d h m)
16011 (let ((fmt "")
16012 (l nil))
16013 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16014 l (push y l)))
16015 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16016 l (push d l)))
16017 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16018 l (push h l)))
16019 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16020 l (push m l)))
16021 (apply 'format fmt (nreverse l))))
16023 (defun org-time-string-to-time (s &optional buffer pos)
16024 (condition-case errdata
16025 (apply 'encode-time (org-parse-time-string s))
16026 (error (error "Bad timestamp `%s'%s\nError was: %s"
16027 s (if (not (and buffer pos))
16029 (format " at %d in buffer `%s'" pos buffer))
16030 (cdr errdata)))))
16032 (defun org-time-string-to-seconds (s)
16033 (org-float-time (org-time-string-to-time s)))
16035 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16036 "Convert a time stamp to an absolute day number.
16037 If there is a specifier for a cyclic time stamp, get the closest date to
16038 DAYNR.
16039 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16040 The variable date is bound by the calendar when this is called."
16041 (cond
16042 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16043 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16044 daynr
16045 (+ daynr 1000)))
16046 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16047 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16048 (time-to-days (current-time))) (match-string 0 s)
16049 prefer show-all))
16050 (t (time-to-days
16051 (condition-case errdata
16052 (apply 'encode-time (org-parse-time-string s))
16053 (error (error "Bad timestamp `%s'%s\nError was: %s"
16054 s (if (not (and buffer pos))
16056 (format " at %d in buffer `%s'" pos buffer))
16057 (cdr errdata))))))))
16059 (defun org-days-to-iso-week (days)
16060 "Return the iso week number."
16061 (require 'cal-iso)
16062 (car (calendar-iso-from-absolute days)))
16064 (defun org-small-year-to-year (year)
16065 "Convert 2-digit years into 4-digit years.
16066 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16067 The year 2000 cannot be abbreviated. Any year larger than 99
16068 is returned unchanged."
16069 (if (< year 38)
16070 (setq year (+ 2000 year))
16071 (if (< year 100)
16072 (setq year (+ 1900 year))))
16073 year)
16075 (defun org-time-from-absolute (d)
16076 "Return the time corresponding to date D.
16077 D may be an absolute day number, or a calendar-type list (month day year)."
16078 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16079 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16081 (defun org-calendar-holiday ()
16082 "List of holidays, for Diary display in Org-mode."
16083 (require 'holidays)
16084 (let ((hl (funcall
16085 (if (fboundp 'calendar-check-holidays)
16086 'calendar-check-holidays 'check-calendar-holidays) date)))
16087 (if hl (mapconcat 'identity hl "; "))))
16089 (defun org-diary-sexp-entry (sexp entry date)
16090 "Process a SEXP diary ENTRY for DATE."
16091 (require 'diary-lib)
16092 (let ((result (if calendar-debug-sexp
16093 (let ((stack-trace-on-error t))
16094 (eval (car (read-from-string sexp))))
16095 (condition-case nil
16096 (eval (car (read-from-string sexp)))
16097 (error
16098 (beep)
16099 (message "Bad sexp at line %d in %s: %s"
16100 (org-current-line)
16101 (buffer-file-name) sexp)
16102 (sleep-for 2))))))
16103 (cond ((stringp result) (split-string result "; "))
16104 ((and (consp result)
16105 (not (consp (cdr result)))
16106 (stringp (cdr result))) (cdr result))
16107 ((and (consp result)
16108 (stringp (car result))) result)
16109 (result entry)
16110 (t nil))))
16112 (defun org-diary-to-ical-string (frombuf)
16113 "Get iCalendar entries from diary entries in buffer FROMBUF.
16114 This uses the icalendar.el library."
16115 (let* ((tmpdir (if (featurep 'xemacs)
16116 (temp-directory)
16117 temporary-file-directory))
16118 (tmpfile (make-temp-name
16119 (expand-file-name "orgics" tmpdir)))
16120 buf rtn b e)
16121 (with-current-buffer frombuf
16122 (icalendar-export-region (point-min) (point-max) tmpfile)
16123 (setq buf (find-buffer-visiting tmpfile))
16124 (set-buffer buf)
16125 (goto-char (point-min))
16126 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16127 (setq b (match-beginning 0)))
16128 (goto-char (point-max))
16129 (if (re-search-backward "^END:VEVENT" nil t)
16130 (setq e (match-end 0)))
16131 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16132 (kill-buffer buf)
16133 (delete-file tmpfile)
16134 rtn))
16136 (defun org-closest-date (start current change prefer show-all)
16137 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16138 When PREFER is `past', return a date that is either CURRENT or past.
16139 When PREFER is `future', return a date that is either CURRENT or future.
16140 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16141 ;; Make the proper lists from the dates
16142 (catch 'exit
16143 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16144 dn dw sday cday n1 n2 n0
16145 d m y y1 y2 date1 date2 nmonths nm ny m2)
16147 (setq start (org-date-to-gregorian start)
16148 current (org-date-to-gregorian
16149 (if show-all
16150 current
16151 (time-to-days (current-time))))
16152 sday (calendar-absolute-from-gregorian start)
16153 cday (calendar-absolute-from-gregorian current))
16155 (if (<= cday sday) (throw 'exit sday))
16157 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16158 (setq dn (string-to-number (match-string 1 change))
16159 dw (cdr (assoc (match-string 2 change) a1)))
16160 (error "Invalid change specifier: %s" change))
16161 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16162 (cond
16163 ((eq dw 'day)
16164 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16165 n2 (+ n1 dn)))
16166 ((eq dw 'year)
16167 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16168 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16169 (setq date1 (list m d y1)
16170 n1 (calendar-absolute-from-gregorian date1)
16171 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16172 n2 (calendar-absolute-from-gregorian date2)))
16173 ((eq dw 'month)
16174 ;; approx number of month between the two dates
16175 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16176 ;; How often does dn fit in there?
16177 (setq d (nth 1 start) m (car start) y (nth 2 start)
16178 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16179 m (+ m nm)
16180 ny (floor (/ m 12))
16181 y (+ y ny)
16182 m (- m (* ny 12)))
16183 (while (> m 12) (setq m (- m 12) y (1+ y)))
16184 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16185 (setq m2 (+ m dn) y2 y)
16186 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16187 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16188 (while (<= n2 cday)
16189 (setq n1 n2 m m2 y y2)
16190 (setq m2 (+ m dn) y2 y)
16191 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16192 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16193 ;; Make sure n1 is the earlier date
16194 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16195 (if show-all
16196 (cond
16197 ((eq prefer 'past) (if (= cday n2) n2 n1))
16198 ((eq prefer 'future) (if (= cday n1) n1 n2))
16199 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16200 (cond
16201 ((eq prefer 'past) (if (= cday n2) n2 n1))
16202 ((eq prefer 'future) (if (= cday n1) n1 n2))
16203 (t (if (= cday n1) n1 n2)))))))
16205 (defun org-date-to-gregorian (date)
16206 "Turn any specification of DATE into a Gregorian date for the calendar."
16207 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16208 ((and (listp date) (= (length date) 3)) date)
16209 ((stringp date)
16210 (setq date (org-parse-time-string date))
16211 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16212 ((listp date)
16213 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16215 (defun org-parse-time-string (s &optional nodefault)
16216 "Parse the standard Org-mode time string.
16217 This should be a lot faster than the normal `parse-time-string'.
16218 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16219 hour and minute fields will be nil if not given."
16220 (if (string-match org-ts-regexp0 s)
16221 (list 0
16222 (if (or (match-beginning 8) (not nodefault))
16223 (string-to-number (or (match-string 8 s) "0")))
16224 (if (or (match-beginning 7) (not nodefault))
16225 (string-to-number (or (match-string 7 s) "0")))
16226 (string-to-number (match-string 4 s))
16227 (string-to-number (match-string 3 s))
16228 (string-to-number (match-string 2 s))
16229 nil nil nil)
16230 (error "Not a standard Org-mode time string: %s" s)))
16232 (defun org-timestamp-up (&optional arg)
16233 "Increase the date item at the cursor by one.
16234 If the cursor is on the year, change the year. If it is on the month,
16235 the day or the time, change that.
16236 With prefix ARG, change by that many units."
16237 (interactive "p")
16238 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16240 (defun org-timestamp-down (&optional arg)
16241 "Decrease the date item at the cursor by one.
16242 If the cursor is on the year, change the year. If it is on the month,
16243 the day or the time, change that.
16244 With prefix ARG, change by that many units."
16245 (interactive "p")
16246 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16248 (defun org-timestamp-up-day (&optional arg)
16249 "Increase the date in the time stamp by one day.
16250 With prefix ARG, change that many days."
16251 (interactive "p")
16252 (if (and (not (org-at-timestamp-p t))
16253 (org-at-heading-p))
16254 (org-todo 'up)
16255 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16257 (defun org-timestamp-down-day (&optional arg)
16258 "Decrease the date in the time stamp by one day.
16259 With prefix ARG, change that many days."
16260 (interactive "p")
16261 (if (and (not (org-at-timestamp-p t))
16262 (org-at-heading-p))
16263 (org-todo 'down)
16264 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16266 (defun org-at-timestamp-p (&optional inactive-ok)
16267 "Determine if the cursor is in or at a timestamp."
16268 (interactive)
16269 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16270 (pos (point))
16271 (ans (or (looking-at tsr)
16272 (save-excursion
16273 (skip-chars-backward "^[<\n\r\t")
16274 (if (> (point) (point-min)) (backward-char 1))
16275 (and (looking-at tsr)
16276 (> (- (match-end 0) pos) -1))))))
16277 (and ans
16278 (boundp 'org-ts-what)
16279 (setq org-ts-what
16280 (cond
16281 ((= pos (match-beginning 0)) 'bracket)
16282 ;; Point is considered to be "on the bracket" whether
16283 ;; it's really on it or right after it.
16284 ((= pos (1- (match-end 0))) 'bracket)
16285 ((= pos (match-end 0)) 'after)
16286 ((org-pos-in-match-range pos 2) 'year)
16287 ((org-pos-in-match-range pos 3) 'month)
16288 ((org-pos-in-match-range pos 7) 'hour)
16289 ((org-pos-in-match-range pos 8) 'minute)
16290 ((or (org-pos-in-match-range pos 4)
16291 (org-pos-in-match-range pos 5)) 'day)
16292 ((and (> pos (or (match-end 8) (match-end 5)))
16293 (< pos (match-end 0)))
16294 (- pos (or (match-end 8) (match-end 5))))
16295 (t 'day))))
16296 ans))
16298 (defun org-toggle-timestamp-type ()
16299 "Toggle the type (<active> or [inactive]) of a time stamp."
16300 (interactive)
16301 (when (org-at-timestamp-p t)
16302 (let ((beg (match-beginning 0)) (end (match-end 0))
16303 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16304 (save-excursion
16305 (goto-char beg)
16306 (while (re-search-forward "[][<>]" end t)
16307 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16308 t t)))
16309 (message "Timestamp is now %sactive"
16310 (if (equal (char-after beg) ?<) "" "in")))))
16312 (defvar org-clock-history) ; defined in org-clock.el
16313 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16314 (defun org-timestamp-change (n &optional what updown)
16315 "Change the date in the time stamp at point.
16316 The date will be changed by N times WHAT. WHAT can be `day', `month',
16317 `year', `minute', `second'. If WHAT is not given, the cursor position
16318 in the timestamp determines what will be changed."
16319 (let ((origin (point)) origin-cat
16320 with-hm inactive
16321 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16322 org-ts-what
16323 extra rem
16324 ts time time0 fixnext clrgx)
16325 (if (not (org-at-timestamp-p t))
16326 (error "Not at a timestamp"))
16327 (if (and (not what) (eq org-ts-what 'bracket))
16328 (org-toggle-timestamp-type)
16329 ;; Point isn't on brackets. Remember the part of the time-stamp
16330 ;; the point was in. Indeed, size of time-stamps may change,
16331 ;; but point must be kept in the same category nonetheless.
16332 (setq origin-cat org-ts-what)
16333 (if (and (not what) (not (eq org-ts-what 'day))
16334 org-display-custom-times
16335 (get-text-property (point) 'display)
16336 (not (get-text-property (1- (point)) 'display)))
16337 (setq org-ts-what 'day))
16338 (setq org-ts-what (or what org-ts-what)
16339 inactive (= (char-after (match-beginning 0)) ?\[)
16340 ts (match-string 0))
16341 (replace-match "")
16342 (if (string-match
16343 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16345 (setq extra (match-string 1 ts)))
16346 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16347 (setq with-hm t))
16348 (setq time0 (org-parse-time-string ts))
16349 (when (and updown
16350 (eq org-ts-what 'minute)
16351 (not current-prefix-arg))
16352 ;; This looks like s-up and s-down. Change by one rounding step.
16353 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16354 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16355 (setcar (cdr time0) (+ (nth 1 time0)
16356 (if (> n 0) (- rem) (- dm rem))))))
16357 (setq time
16358 (encode-time (or (car time0) 0)
16359 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16360 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16361 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16362 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16363 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16364 (nthcdr 6 time0)))
16365 (when (and (member org-ts-what '(hour minute))
16366 extra
16367 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16368 (setq extra (org-modify-ts-extra
16369 extra
16370 (if (eq org-ts-what 'hour) 2 5)
16371 n dm)))
16372 (when (integerp org-ts-what)
16373 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16374 (if (eq what 'calendar)
16375 (let ((cal-date (org-get-date-from-calendar)))
16376 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16377 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16378 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16379 (setcar time0 (or (car time0) 0))
16380 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16381 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16382 (setq time (apply 'encode-time time0))))
16383 ;; Insert the new time-stamp, and ensure point stays in the same
16384 ;; category as before (i.e. not after the last position in that
16385 ;; category).
16386 (let ((pos (point)))
16387 ;; Stay before inserted string. `save-excursion' is of no use.
16388 (setq org-last-changed-timestamp
16389 (org-insert-time-stamp time with-hm inactive nil nil extra))
16390 (goto-char pos))
16391 (save-match-data
16392 (looking-at org-ts-regexp3)
16393 (goto-char (cond
16394 ;; `day' category ends before `hour' if any, or at
16395 ;; the end of the day name.
16396 ((eq origin-cat 'day)
16397 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16398 ((eq origin-cat 'hour) (min (match-end 7) origin))
16399 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16400 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16401 ;; `year' and `month' have both fixed size: point
16402 ;; couldn't have moved into another part.
16403 (t origin))))
16404 ;; Update clock if on a CLOCK line.
16405 (org-clock-update-time-maybe)
16406 ;; Maybe adjust the closest clock in `org-clock-history'
16407 (when org-clock-adjust-closest
16408 (if (not (and (org-at-clock-log-p)
16409 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16410 org-clock-history))))))
16411 (message "No clock to adjust")
16412 (cond ((save-excursion ; fix previous clock?
16413 (re-search-backward org-ts-regexp0 nil t)
16414 (looking-back (concat org-clock-string " \\[")))
16415 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16416 ((save-excursion ; fix next clock?
16417 (re-search-backward org-ts-regexp0 nil t)
16418 (looking-at (concat org-ts-regexp0 "\\] =>")))
16419 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16420 (save-window-excursion
16421 ;; Find closest clock to point, adjust the previous/next one in history
16422 (let* ((p (save-excursion (org-back-to-heading t)))
16423 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16424 (clfixnth
16425 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16426 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16427 (if (not clfixpos)
16428 (message "No clock to adjust")
16429 (org-goto-marker-or-bmk clfixpos)
16430 (org-show-subtree)
16431 (when (re-search-forward clrgx nil t)
16432 (goto-char (match-beginning 1))
16433 (let (org-clock-adjust-closest)
16434 (org-timestamp-change n org-ts-what updown))
16435 (message "Clock adjusted in %s for heading: %s"
16436 (file-name-nondirectory (buffer-file-name))
16437 (org-get-heading t t))))))))
16438 ;; Try to recenter the calendar window, if any.
16439 (if (and org-calendar-follow-timestamp-change
16440 (get-buffer-window "*Calendar*" t)
16441 (memq org-ts-what '(day month year)))
16442 (org-recenter-calendar (time-to-days time))))))
16444 (defun org-modify-ts-extra (s pos n dm)
16445 "Change the different parts of the lead-time and repeat fields in timestamp."
16446 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16447 ng h m new rem)
16448 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16449 (cond
16450 ((or (org-pos-in-match-range pos 2)
16451 (org-pos-in-match-range pos 3))
16452 (setq m (string-to-number (match-string 3 s))
16453 h (string-to-number (match-string 2 s)))
16454 (if (org-pos-in-match-range pos 2)
16455 (setq h (+ h n))
16456 (setq n (* dm (org-no-warnings (signum n))))
16457 (when (not (= 0 (setq rem (% m dm))))
16458 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16459 (setq m (+ m n)))
16460 (if (< m 0) (setq m (+ m 60) h (1- h)))
16461 (if (> m 59) (setq m (- m 60) h (1+ h)))
16462 (setq h (min 24 (max 0 h)))
16463 (setq ng 1 new (format "-%02d:%02d" h m)))
16464 ((org-pos-in-match-range pos 6)
16465 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16466 ((org-pos-in-match-range pos 5)
16467 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16469 ((org-pos-in-match-range pos 9)
16470 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16471 ((org-pos-in-match-range pos 8)
16472 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16474 (when ng
16475 (setq s (concat
16476 (substring s 0 (match-beginning ng))
16478 (substring s (match-end ng))))))
16481 (defun org-recenter-calendar (date)
16482 "If the calendar is visible, recenter it to DATE."
16483 (let ((cwin (get-buffer-window "*Calendar*" t)))
16484 (when cwin
16485 (let ((calendar-move-hook nil))
16486 (with-selected-window cwin
16487 (calendar-goto-date (if (listp date) date
16488 (calendar-gregorian-from-absolute date))))))))
16490 (defun org-goto-calendar (&optional arg)
16491 "Go to the Emacs calendar at the current date.
16492 If there is a time stamp in the current line, go to that date.
16493 A prefix ARG can be used to force the current date."
16494 (interactive "P")
16495 (let ((tsr org-ts-regexp) diff
16496 (calendar-move-hook nil)
16497 (calendar-view-holidays-initially-flag nil)
16498 (calendar-view-diary-initially-flag nil))
16499 (if (or (org-at-timestamp-p)
16500 (save-excursion
16501 (beginning-of-line 1)
16502 (looking-at (concat ".*" tsr))))
16503 (let ((d1 (time-to-days (current-time)))
16504 (d2 (time-to-days
16505 (org-time-string-to-time (match-string 1)))))
16506 (setq diff (- d2 d1))))
16507 (calendar)
16508 (calendar-goto-today)
16509 (if (and diff (not arg)) (calendar-forward-day diff))))
16511 (defun org-get-date-from-calendar ()
16512 "Return a list (month day year) of date at point in calendar."
16513 (with-current-buffer "*Calendar*"
16514 (save-match-data
16515 (calendar-cursor-to-date))))
16517 (defun org-date-from-calendar ()
16518 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16519 If there is already a time stamp at the cursor position, update it."
16520 (interactive)
16521 (if (org-at-timestamp-p t)
16522 (org-timestamp-change 0 'calendar)
16523 (let ((cal-date (org-get-date-from-calendar)))
16524 (org-insert-time-stamp
16525 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16527 (defun org-minutes-to-hh:mm-string (m)
16528 "Compute H:MM from a number of minutes."
16529 (let ((h (/ m 60)))
16530 (setq m (- m (* 60 h)))
16531 (format org-time-clocksum-format h m)))
16533 (defun org-hh:mm-string-to-minutes (s)
16534 "Convert a string H:MM to a number of minutes.
16535 If the string is just a number, interpret it as minutes.
16536 In fact, the first hh:mm or number in the string will be taken,
16537 there can be extra stuff in the string.
16538 If no number is found, the return value is 0."
16539 (cond
16540 ((integerp s) s)
16541 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16542 (+ (* (string-to-number (match-string 1 s)) 60)
16543 (string-to-number (match-string 2 s))))
16544 ((string-match "\\([0-9]+\\)" s)
16545 (string-to-number (match-string 1 s)))
16546 (t 0)))
16548 (defcustom org-effort-durations
16549 `(("h" . 60)
16550 ("d" . ,(* 60 8))
16551 ("w" . ,(* 60 8 5))
16552 ("m" . ,(* 60 8 5 4))
16553 ("y" . ,(* 60 8 5 40)))
16554 "Conversion factor to minutes for an effort modifier.
16556 Each entry has the form (MODIFIER . MINUTES).
16558 In an effort string, a number followed by MODIFIER is multiplied
16559 by the specified number of MINUTES to obtain an effort in
16560 minutes.
16562 For example, if the value of this variable is ((\"hours\" . 60)), then an
16563 effort string \"2hours\" is equivalent to 120 minutes."
16564 :group 'org-agenda
16565 :version "24.1"
16566 :type '(alist :key-type (string :tag "Modifier")
16567 :value-type (number :tag "Minutes")))
16569 (defun org-duration-string-to-minutes (s &optional output-to-string)
16570 "Convert a duration string S to minutes.
16572 A bare number is interpreted as minutes, modifiers can be set by
16573 customizing `org-effort-durations' (which see).
16575 Entries containing a colon are interpreted as H:MM by
16576 `org-hh:mm-string-to-minutes'."
16577 (let ((result 0)
16578 (re (concat "\\([0-9.]+\\) *\\("
16579 (regexp-opt (mapcar 'car org-effort-durations))
16580 "\\)")))
16581 (while (string-match re s)
16582 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16583 (string-to-number (match-string 1 s))))
16584 (setq s (replace-match "" nil t s)))
16585 (setq result (floor result))
16586 (incf result (org-hh:mm-string-to-minutes s))
16587 (if output-to-string (number-to-string result) result)))
16589 ;;;; Files
16591 (defun org-save-all-org-buffers ()
16592 "Save all Org-mode buffers without user confirmation."
16593 (interactive)
16594 (message "Saving all Org-mode buffers...")
16595 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16596 (when (featurep 'org-id) (org-id-locations-save))
16597 (message "Saving all Org-mode buffers... done"))
16599 (defun org-revert-all-org-buffers ()
16600 "Revert all Org-mode buffers.
16601 Prompt for confirmation when there are unsaved changes.
16602 Be sure you know what you are doing before letting this function
16603 overwrite your changes.
16605 This function is useful in a setup where one tracks org files
16606 with a version control system, to revert on one machine after pulling
16607 changes from another. I believe the procedure must be like this:
16609 1. M-x org-save-all-org-buffers
16610 2. Pull changes from the other machine, resolve conflicts
16611 3. M-x org-revert-all-org-buffers"
16612 (interactive)
16613 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16614 (error "Abort"))
16615 (save-excursion
16616 (save-window-excursion
16617 (mapc
16618 (lambda (b)
16619 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16620 (with-current-buffer b buffer-file-name))
16621 (org-pop-to-buffer-same-window b)
16622 (revert-buffer t 'no-confirm)))
16623 (buffer-list))
16624 (when (and (featurep 'org-id) org-id-track-globally)
16625 (org-id-locations-load)))))
16627 ;;;; Agenda files
16629 ;;;###autoload
16630 (defun org-switchb (&optional arg)
16631 "Switch between Org buffers.
16632 With one prefix argument, restrict available buffers to files.
16633 With two prefix arguments, restrict available buffers to agenda files.
16635 Defaults to `iswitchb' for buffer name completion.
16636 Set `org-completion-use-ido' to make it use ido instead."
16637 (interactive "P")
16638 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16639 ((equal arg '(16)) (org-buffer-list 'agenda))
16640 (t (org-buffer-list))))
16641 (org-completion-use-iswitchb org-completion-use-iswitchb)
16642 (org-completion-use-ido org-completion-use-ido))
16643 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16644 (setq org-completion-use-iswitchb t))
16645 (org-pop-to-buffer-same-window
16646 (org-icompleting-read "Org buffer: "
16647 (mapcar 'list (mapcar 'buffer-name blist))
16648 nil t))))
16650 ;;; Define some older names previously used for this functionality
16651 ;;;###autoload
16652 (defalias 'org-ido-switchb 'org-switchb)
16653 ;;;###autoload
16654 (defalias 'org-iswitchb 'org-switchb)
16656 (defun org-buffer-list (&optional predicate exclude-tmp)
16657 "Return a list of Org buffers.
16658 PREDICATE can be `export', `files' or `agenda'.
16660 export restrict the list to Export buffers.
16661 files restrict the list to buffers visiting Org files.
16662 agenda restrict the list to buffers visiting agenda files.
16664 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16665 (let* ((bfn nil)
16666 (agenda-files (and (eq predicate 'agenda)
16667 (mapcar 'file-truename (org-agenda-files t))))
16668 (filter
16669 (cond
16670 ((eq predicate 'files)
16671 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16672 ((eq predicate 'export)
16673 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16674 ((eq predicate 'agenda)
16675 (lambda (b)
16676 (with-current-buffer b
16677 (and (derived-mode-p 'org-mode)
16678 (setq bfn (buffer-file-name b))
16679 (member (file-truename bfn) agenda-files)))))
16680 (t (lambda (b) (with-current-buffer b
16681 (or (derived-mode-p 'org-mode)
16682 (string-match "\*Org .*Export"
16683 (buffer-name b)))))))))
16684 (delq nil
16685 (mapcar
16686 (lambda(b)
16687 (if (and (funcall filter b)
16688 (or (not exclude-tmp)
16689 (not (string-match "tmp" (buffer-name b)))))
16691 nil))
16692 (buffer-list)))))
16694 (defun org-agenda-files (&optional unrestricted archives)
16695 "Get the list of agenda files.
16696 Optional UNRESTRICTED means return the full list even if a restriction
16697 is currently in place.
16698 When ARCHIVES is t, include all archive files that are really being
16699 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16700 `org-agenda-archives-mode' is t."
16701 (let ((files
16702 (cond
16703 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16704 ((stringp org-agenda-files) (org-read-agenda-file-list))
16705 ((listp org-agenda-files) org-agenda-files)
16706 (t (error "Invalid value of `org-agenda-files'")))))
16707 (setq files (apply 'append
16708 (mapcar (lambda (f)
16709 (if (file-directory-p f)
16710 (directory-files
16711 f t org-agenda-file-regexp)
16712 (list f)))
16713 files)))
16714 (when org-agenda-skip-unavailable-files
16715 (setq files (delq nil
16716 (mapcar (function
16717 (lambda (file)
16718 (and (file-readable-p file) file)))
16719 files))))
16720 (when (or (eq archives t)
16721 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16722 (setq files (org-add-archive-files files)))
16723 files))
16725 (defun org-agenda-file-p (&optional file)
16726 "Return non-nil, if FILE is an agenda file.
16727 If FILE is omitted, use the file associated with the current
16728 buffer."
16729 (member (or file (buffer-file-name))
16730 (org-agenda-files t)))
16732 (defun org-edit-agenda-file-list ()
16733 "Edit the list of agenda files.
16734 Depending on setup, this either uses customize to edit the variable
16735 `org-agenda-files', or it visits the file that is holding the list. In the
16736 latter case, the buffer is set up in a way that saving it automatically kills
16737 the buffer and restores the previous window configuration."
16738 (interactive)
16739 (if (stringp org-agenda-files)
16740 (let ((cw (current-window-configuration)))
16741 (find-file org-agenda-files)
16742 (org-set-local 'org-window-configuration cw)
16743 (org-add-hook 'after-save-hook
16744 (lambda ()
16745 (set-window-configuration
16746 (prog1 org-window-configuration
16747 (kill-buffer (current-buffer))))
16748 (org-install-agenda-files-menu)
16749 (message "New agenda file list installed"))
16750 nil 'local)
16751 (message "%s" (substitute-command-keys
16752 "Edit list and finish with \\[save-buffer]")))
16753 (customize-variable 'org-agenda-files)))
16755 (defun org-store-new-agenda-file-list (list)
16756 "Set new value for the agenda file list and save it correctly."
16757 (if (stringp org-agenda-files)
16758 (let ((fe (org-read-agenda-file-list t)) b u)
16759 (while (setq b (find-buffer-visiting org-agenda-files))
16760 (kill-buffer b))
16761 (with-temp-file org-agenda-files
16762 (insert
16763 (mapconcat
16764 (lambda (f) ;; Keep un-expanded entries.
16765 (if (setq u (assoc f fe))
16766 (cdr u)
16768 list "\n")
16769 "\n")))
16770 (let ((org-mode-hook nil) (org-inhibit-startup t)
16771 (org-insert-mode-line-in-empty-file nil))
16772 (setq org-agenda-files list)
16773 (customize-save-variable 'org-agenda-files org-agenda-files))))
16775 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16776 "Read the list of agenda files from a file.
16777 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16778 filenames, used by `org-store-new-agenda-file-list' to write back
16779 un-expanded file names."
16780 (when (file-directory-p org-agenda-files)
16781 (error "`org-agenda-files' cannot be a single directory"))
16782 (when (stringp org-agenda-files)
16783 (with-temp-buffer
16784 (insert-file-contents org-agenda-files)
16785 (mapcar
16786 (lambda (f)
16787 (let ((e (expand-file-name (substitute-in-file-name f)
16788 org-directory)))
16789 (if pair-with-expansion
16790 (cons e f)
16791 e)))
16792 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16794 ;;;###autoload
16795 (defun org-cycle-agenda-files ()
16796 "Cycle through the files in `org-agenda-files'.
16797 If the current buffer visits an agenda file, find the next one in the list.
16798 If the current buffer does not, find the first agenda file."
16799 (interactive)
16800 (let* ((fs (org-agenda-files t))
16801 (files (append fs (list (car fs))))
16802 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16803 file)
16804 (unless files (error "No agenda files"))
16805 (catch 'exit
16806 (while (setq file (pop files))
16807 (if (equal (file-truename file) tcf)
16808 (when (car files)
16809 (find-file (car files))
16810 (throw 'exit t))))
16811 (find-file (car fs)))
16812 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16814 (defun org-agenda-file-to-front (&optional to-end)
16815 "Move/add the current file to the top of the agenda file list.
16816 If the file is not present in the list, it is added to the front. If it is
16817 present, it is moved there. With optional argument TO-END, add/move to the
16818 end of the list."
16819 (interactive "P")
16820 (let ((org-agenda-skip-unavailable-files nil)
16821 (file-alist (mapcar (lambda (x)
16822 (cons (file-truename x) x))
16823 (org-agenda-files t)))
16824 (ctf (file-truename buffer-file-name))
16825 x had)
16826 (setq x (assoc ctf file-alist) had x)
16828 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16829 (if to-end
16830 (setq file-alist (append (delq x file-alist) (list x)))
16831 (setq file-alist (cons x (delq x file-alist))))
16832 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16833 (org-install-agenda-files-menu)
16834 (message "File %s to %s of agenda file list"
16835 (if had "moved" "added") (if to-end "end" "front"))))
16837 (defun org-remove-file (&optional file)
16838 "Remove current file from the list of files in variable `org-agenda-files'.
16839 These are the files which are being checked for agenda entries.
16840 Optional argument FILE means use this file instead of the current."
16841 (interactive)
16842 (let* ((org-agenda-skip-unavailable-files nil)
16843 (file (or file buffer-file-name))
16844 (true-file (file-truename file))
16845 (afile (abbreviate-file-name file))
16846 (files (delq nil (mapcar
16847 (lambda (x)
16848 (if (equal true-file
16849 (file-truename x))
16850 nil x))
16851 (org-agenda-files t)))))
16852 (if (not (= (length files) (length (org-agenda-files t))))
16853 (progn
16854 (org-store-new-agenda-file-list files)
16855 (org-install-agenda-files-menu)
16856 (message "Removed file: %s" afile))
16857 (message "File was not in list: %s (not removed)" afile))))
16859 (defun org-file-menu-entry (file)
16860 (vector file (list 'find-file file) t))
16862 (defun org-check-agenda-file (file)
16863 "Make sure FILE exists. If not, ask user what to do."
16864 (when (not (file-exists-p file))
16865 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16866 (abbreviate-file-name file))
16867 (let ((r (downcase (read-char-exclusive))))
16868 (cond
16869 ((equal r ?r)
16870 (org-remove-file file)
16871 (throw 'nextfile t))
16872 (t (error "Abort"))))))
16874 (defun org-get-agenda-file-buffer (file)
16875 "Get a buffer visiting FILE. If the buffer needs to be created, add
16876 it to the list of buffers which might be released later."
16877 (let ((buf (org-find-base-buffer-visiting file)))
16878 (if buf
16879 buf ; just return it
16880 ;; Make a new buffer and remember it
16881 (setq buf (find-file-noselect file))
16882 (if buf (push buf org-agenda-new-buffers))
16883 buf)))
16885 (defun org-release-buffers (blist)
16886 "Release all buffers in list, asking the user for confirmation when needed.
16887 When a buffer is unmodified, it is just killed. When modified, it is saved
16888 \(if the user agrees) and then killed."
16889 (let (buf file)
16890 (while (setq buf (pop blist))
16891 (setq file (buffer-file-name buf))
16892 (when (and (buffer-modified-p buf)
16893 file
16894 (y-or-n-p (format "Save file %s? " file)))
16895 (with-current-buffer buf (save-buffer)))
16896 (kill-buffer buf))))
16898 (defun org-prepare-agenda-buffers (files)
16899 "Create buffers for all agenda files, protect archived trees and comments."
16900 (interactive)
16901 (let ((pa '(:org-archived t))
16902 (pc '(:org-comment t))
16903 (pall '(:org-archived t :org-comment t))
16904 (inhibit-read-only t)
16905 (rea (concat ":" org-archive-tag ":"))
16906 bmp file re)
16907 (save-excursion
16908 (save-restriction
16909 (while (setq file (pop files))
16910 (catch 'nextfile
16911 (if (bufferp file)
16912 (set-buffer file)
16913 (org-check-agenda-file file)
16914 (set-buffer (org-get-agenda-file-buffer file)))
16915 (widen)
16916 (setq bmp (buffer-modified-p))
16917 (org-refresh-category-properties)
16918 (setq org-todo-keywords-for-agenda
16919 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16920 (setq org-done-keywords-for-agenda
16921 (append org-done-keywords-for-agenda org-done-keywords))
16922 (setq org-todo-keyword-alist-for-agenda
16923 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16924 (setq org-drawers-for-agenda
16925 (append org-drawers-for-agenda org-drawers))
16926 (setq org-tag-alist-for-agenda
16927 (append org-tag-alist-for-agenda org-tag-alist))
16929 (save-excursion
16930 (remove-text-properties (point-min) (point-max) pall)
16931 (when org-agenda-skip-archived-trees
16932 (goto-char (point-min))
16933 (while (re-search-forward rea nil t)
16934 (if (org-at-heading-p t)
16935 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16936 (goto-char (point-min))
16937 (setq re (format org-heading-keyword-regexp-format
16938 org-comment-string))
16939 (while (re-search-forward re nil t)
16940 (add-text-properties
16941 (match-beginning 0) (org-end-of-subtree t) pc)))
16942 (set-buffer-modified-p bmp)))))
16943 (setq org-todo-keywords-for-agenda
16944 (org-uniquify org-todo-keywords-for-agenda))
16945 (setq org-todo-keyword-alist-for-agenda
16946 (org-uniquify org-todo-keyword-alist-for-agenda)
16947 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16949 ;;;; Embedded LaTeX
16951 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16952 "Keymap for the minor `org-cdlatex-mode'.")
16954 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16955 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16956 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16957 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16958 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16960 (defvar org-cdlatex-texmathp-advice-is-done nil
16961 "Flag remembering if we have applied the advice to texmathp already.")
16963 (define-minor-mode org-cdlatex-mode
16964 "Toggle the minor `org-cdlatex-mode'.
16965 This mode supports entering LaTeX environment and math in LaTeX fragments
16966 in Org-mode.
16967 \\{org-cdlatex-mode-map}"
16968 nil " OCDL" nil
16969 (when org-cdlatex-mode
16970 (require 'cdlatex)
16971 (run-hooks 'cdlatex-mode-hook)
16972 (cdlatex-compute-tables))
16973 (unless org-cdlatex-texmathp-advice-is-done
16974 (setq org-cdlatex-texmathp-advice-is-done t)
16975 (defadvice texmathp (around org-math-always-on activate)
16976 "Always return t in org-mode buffers.
16977 This is because we want to insert math symbols without dollars even outside
16978 the LaTeX math segments. If Orgmode thinks that point is actually inside
16979 an embedded LaTeX fragment, let texmathp do its job.
16980 \\[org-cdlatex-mode-map]"
16981 (interactive)
16982 (let (p)
16983 (cond
16984 ((not (derived-mode-p 'org-mode)) ad-do-it)
16985 ((eq this-command 'cdlatex-math-symbol)
16986 (setq ad-return-value t
16987 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16989 (let ((p (org-inside-LaTeX-fragment-p)))
16990 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16991 (setq ad-return-value t
16992 texmathp-why '("Org-mode embedded math" . 0))
16993 (if p ad-do-it)))))))))
16995 (defun turn-on-org-cdlatex ()
16996 "Unconditionally turn on `org-cdlatex-mode'."
16997 (org-cdlatex-mode 1))
16999 (defun org-inside-LaTeX-fragment-p ()
17000 "Test if point is inside a LaTeX fragment.
17001 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17002 sequence appearing also before point.
17003 Even though the matchers for math are configurable, this function assumes
17004 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17005 delimiters are skipped when they have been removed by customization.
17006 The return value is nil, or a cons cell with the delimiter and the
17007 position of this delimiter.
17009 This function does a reasonably good job, but can locally be fooled by
17010 for example currency specifications. For example it will assume being in
17011 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17012 fragments that are properly closed, but during editing, we have to live
17013 with the uncertainty caused by missing closing delimiters. This function
17014 looks only before point, not after."
17015 (catch 'exit
17016 (let ((pos (point))
17017 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17018 (lim (progn
17019 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17020 (point)))
17021 dd-on str (start 0) m re)
17022 (goto-char pos)
17023 (when dodollar
17024 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17025 re (nth 1 (assoc "$" org-latex-regexps)))
17026 (while (string-match re str start)
17027 (cond
17028 ((= (match-end 0) (length str))
17029 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17030 ((= (match-end 0) (- (length str) 5))
17031 (throw 'exit nil))
17032 (t (setq start (match-end 0))))))
17033 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17034 (goto-char pos)
17035 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17036 (and (match-beginning 2) (throw 'exit nil))
17037 ;; count $$
17038 (while (re-search-backward "\\$\\$" lim t)
17039 (setq dd-on (not dd-on)))
17040 (goto-char pos)
17041 (if dd-on (cons "$$" m))))))
17043 (defun org-inside-latex-macro-p ()
17044 "Is point inside a LaTeX macro or its arguments?"
17045 (save-match-data
17046 (org-in-regexp
17047 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17049 (defun org-try-cdlatex-tab ()
17050 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17051 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17052 - inside a LaTeX fragment, or
17053 - after the first word in a line, where an abbreviation expansion could
17054 insert a LaTeX environment."
17055 (when org-cdlatex-mode
17056 (cond
17057 ;; Before any word on the line: No expansion possible.
17058 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17059 ;; Just after first word on the line: Expand it. Make sure it
17060 ;; cannot happen on headlines, though.
17061 ((save-excursion
17062 (skip-chars-backward "a-zA-Z0-9*")
17063 (skip-chars-backward " \t")
17064 (and (bolp) (not (org-at-heading-p))))
17065 (cdlatex-tab) t)
17066 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17068 (defun org-cdlatex-underscore-caret (&optional arg)
17069 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17070 Revert to the normal definition outside of these fragments."
17071 (interactive "P")
17072 (if (org-inside-LaTeX-fragment-p)
17073 (call-interactively 'cdlatex-sub-superscript)
17074 (let (org-cdlatex-mode)
17075 (call-interactively (key-binding (vector last-input-event))))))
17077 (defun org-cdlatex-math-modify (&optional arg)
17078 "Execute `cdlatex-math-modify' in LaTeX fragments.
17079 Revert to the normal definition outside of these fragments."
17080 (interactive "P")
17081 (if (org-inside-LaTeX-fragment-p)
17082 (call-interactively 'cdlatex-math-modify)
17083 (let (org-cdlatex-mode)
17084 (call-interactively (key-binding (vector last-input-event))))))
17086 (defvar org-latex-fragment-image-overlays nil
17087 "List of overlays carrying the images of latex fragments.")
17088 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17090 (defun org-remove-latex-fragment-image-overlays ()
17091 "Remove all overlays with LaTeX fragment images in current buffer."
17092 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17093 (setq org-latex-fragment-image-overlays nil))
17095 (defun org-preview-latex-fragment (&optional subtree)
17096 "Preview the LaTeX fragment at point, or all locally or globally.
17097 If the cursor is in a LaTeX fragment, create the image and overlay
17098 it over the source code. If there is no fragment at point, display
17099 all fragments in the current text, from one headline to the next. With
17100 prefix SUBTREE, display all fragments in the current subtree. With a
17101 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17102 the cursor is before the first headline,
17103 display all fragments in the buffer.
17104 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17105 (interactive "P")
17106 (unless buffer-file-name
17107 (error "Can't preview LaTeX fragment in a non-file buffer"))
17108 (org-remove-latex-fragment-image-overlays)
17109 (save-excursion
17110 (save-restriction
17111 (let (beg end at msg)
17112 (cond
17113 ((or (equal subtree '(16))
17114 (not (save-excursion
17115 (re-search-backward org-outline-regexp-bol nil t))))
17116 (setq beg (point-min) end (point-max)
17117 msg "Creating images for buffer...%s"))
17118 ((equal subtree '(4))
17119 (org-back-to-heading)
17120 (setq beg (point) end (org-end-of-subtree t)
17121 msg "Creating images for subtree...%s"))
17123 (if (setq at (org-inside-LaTeX-fragment-p))
17124 (goto-char (max (point-min) (- (cdr at) 2)))
17125 (org-back-to-heading))
17126 (setq beg (point) end (progn (outline-next-heading) (point))
17127 msg (if at "Creating image...%s"
17128 "Creating images for entry...%s"))))
17129 (message msg "")
17130 (narrow-to-region beg end)
17131 (goto-char beg)
17132 (org-format-latex
17133 (concat "ltxpng/" (file-name-sans-extension
17134 (file-name-nondirectory
17135 buffer-file-name)))
17136 default-directory 'overlays msg at 'forbuffer
17137 org-latex-create-formula-image-program)
17138 (message msg "done. Use `C-c C-c' to remove images.")))))
17140 (defvar org-latex-regexps
17141 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17142 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17143 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17144 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17145 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17146 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17147 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17148 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17149 "Regular expressions for matching embedded LaTeX.")
17151 (defvar org-export-have-math nil) ;; dynamic scoping
17152 (defun org-format-latex (prefix &optional dir overlays msg at
17153 forbuffer processing-type)
17154 "Replace LaTeX fragments with links to an image, and produce images.
17155 Some of the options can be changed using the variable
17156 `org-format-latex-options'."
17157 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17158 (let* ((prefixnodir (file-name-nondirectory prefix))
17159 (absprefix (expand-file-name prefix dir))
17160 (todir (file-name-directory absprefix))
17161 (opt org-format-latex-options)
17162 (matchers (plist-get opt :matchers))
17163 (re-list org-latex-regexps)
17164 (org-format-latex-header-extra
17165 (plist-get (org-infile-export-plist) :latex-header-extra))
17166 (cnt 0) txt hash link beg end re e checkdir
17167 executables-checked string
17168 m n block-type block linkfile movefile ov)
17169 ;; Check the different regular expressions
17170 (while (setq e (pop re-list))
17171 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17172 block (if block-type "\n\n" ""))
17173 (when (member m matchers)
17174 (goto-char (point-min))
17175 (while (re-search-forward re nil t)
17176 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17177 (not (get-text-property (match-beginning n)
17178 'org-protected))
17179 (or (not overlays)
17180 (not (eq (get-char-property (match-beginning n)
17181 'org-overlay-type)
17182 'org-latex-overlay))))
17183 (setq org-export-have-math t)
17184 (cond
17185 ((eq processing-type 'verbatim)
17186 ;; Leave the text verbatim, just protect it
17187 (add-text-properties (match-beginning n) (match-end n)
17188 '(org-protected t)))
17189 ((eq processing-type 'mathjax)
17190 ;; Prepare for MathJax processing
17191 (setq string (match-string n))
17192 (if (member m '("$" "$1"))
17193 (save-excursion
17194 (delete-region (match-beginning n) (match-end n))
17195 (goto-char (match-beginning n))
17196 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17197 "\\)")
17198 '(org-protected t))))
17199 (add-text-properties (match-beginning n) (match-end n)
17200 '(org-protected t))))
17201 ((or (eq processing-type 'dvipng)
17202 (eq processing-type 'imagemagick))
17203 ;; Process to an image
17204 (setq txt (match-string n)
17205 beg (match-beginning n) end (match-end n)
17206 cnt (1+ cnt))
17207 (let (print-length print-level) ; make sure full list is printed
17208 (setq hash (sha1 (prin1-to-string
17209 (list org-format-latex-header
17210 org-format-latex-header-extra
17211 org-export-latex-default-packages-alist
17212 org-export-latex-packages-alist
17213 org-format-latex-options
17214 forbuffer txt)))
17215 linkfile (format "%s_%s.png" prefix hash)
17216 movefile (format "%s_%s.png" absprefix hash)))
17217 (setq link (concat block "[[file:" linkfile "]]" block))
17218 (if msg (message msg cnt))
17219 (goto-char beg)
17220 (unless checkdir ; make sure the directory exists
17221 (setq checkdir t)
17222 (or (file-directory-p todir) (make-directory todir t)))
17223 (cond
17224 ((eq processing-type 'dvipng)
17225 (unless executables-checked
17226 (org-check-external-command
17227 "latex" "needed to convert LaTeX fragments to images")
17228 (org-check-external-command
17229 "dvipng" "needed to convert LaTeX fragments to images")
17230 (setq executables-checked t))
17231 (unless (file-exists-p movefile)
17232 (org-create-formula-image-with-dvipng
17233 txt movefile opt forbuffer)))
17234 ((eq processing-type 'imagemagick)
17235 (unless executables-checked
17236 (org-check-external-command
17237 "convert" "you need to install imagemagick")
17238 (setq executables-checked t))
17239 (unless (file-exists-p movefile)
17240 (org-create-formula-image-with-imagemagick
17241 txt movefile opt forbuffer))))
17242 (if overlays
17243 (progn
17244 (mapc (lambda (o)
17245 (if (eq (overlay-get o 'org-overlay-type)
17246 'org-latex-overlay)
17247 (delete-overlay o)))
17248 (overlays-in beg end))
17249 (setq ov (make-overlay beg end))
17250 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17251 (if (featurep 'xemacs)
17252 (progn
17253 (overlay-put ov 'invisible t)
17254 (overlay-put
17255 ov 'end-glyph
17256 (make-glyph (vector 'png :file movefile))))
17257 (overlay-put
17258 ov 'display
17259 (list 'image :type 'png :file movefile :ascent 'center)))
17260 (push ov org-latex-fragment-image-overlays)
17261 (goto-char end))
17262 (delete-region beg end)
17263 (insert (org-add-props link
17264 (list 'org-latex-src
17265 (replace-regexp-in-string
17266 "\"" "" txt)
17267 'org-latex-src-embed-type
17268 (if block-type 'paragraph 'character))))))
17269 ((eq processing-type 'mathml)
17270 ;; Process to MathML
17271 (unless executables-checked
17272 (unless (save-match-data (org-format-latex-mathml-available-p))
17273 (error "LaTeX to MathML converter not configured"))
17274 (setq executables-checked t))
17275 (setq txt (match-string n)
17276 beg (match-beginning n) end (match-end n)
17277 cnt (1+ cnt))
17278 (if msg (message msg cnt))
17279 (goto-char beg)
17280 (delete-region beg end)
17281 (insert (org-format-latex-as-mathml
17282 txt block-type prefix dir)))
17284 (error "Unknown conversion type %s for latex fragments"
17285 processing-type)))))))))
17287 (defun org-create-math-formula (latex-frag &optional mathml-file)
17288 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17289 Use `org-latex-to-mathml-convert-command'. If the conversion is
17290 sucessful, return the portion between \"<math...> </math>\"
17291 elements otherwise return nil. When MATHML-FILE is specified,
17292 write the results in to that file. When invoked as an
17293 interactive command, prompt for LATEX-FRAG, with initial value
17294 set to the current active region and echo the results for user
17295 inspection."
17296 (interactive (list (let ((frag (when (region-active-p)
17297 (buffer-substring-no-properties
17298 (region-beginning) (region-end)))))
17299 (read-string "LaTeX Fragment: " frag nil frag))))
17300 (unless latex-frag (error "Invalid latex-frag"))
17301 (let* ((tmp-in-file (file-relative-name
17302 (make-temp-name (expand-file-name "ltxmathml-in"))))
17303 (ignore (write-region latex-frag nil tmp-in-file))
17304 (tmp-out-file (file-relative-name
17305 (make-temp-name (expand-file-name "ltxmathml-out"))))
17306 (cmd (format-spec
17307 org-latex-to-mathml-convert-command
17308 `((?j . ,(shell-quote-argument
17309 (expand-file-name org-latex-to-mathml-jar-file)))
17310 (?I . ,(shell-quote-argument tmp-in-file))
17311 (?o . ,(shell-quote-argument tmp-out-file)))))
17312 mathml shell-command-output)
17313 (when (org-called-interactively-p 'any)
17314 (unless (org-format-latex-mathml-available-p)
17315 (error "LaTeX to MathML converter not configured")))
17316 (message "Running %s" cmd)
17317 (setq shell-command-output (shell-command-to-string cmd))
17318 (setq mathml
17319 (when (file-readable-p tmp-out-file)
17320 (with-current-buffer (find-file-noselect tmp-out-file t)
17321 (goto-char (point-min))
17322 (when (re-search-forward
17323 (concat
17324 (regexp-quote
17325 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17326 "\\(.\\|\n\\)*"
17327 (regexp-quote "</math>")) nil t)
17328 (prog1 (match-string 0) (kill-buffer))))))
17329 (cond
17330 (mathml
17331 (setq mathml
17332 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17333 (when mathml-file
17334 (write-region mathml nil mathml-file))
17335 (when (org-called-interactively-p 'any)
17336 (message mathml)))
17337 ((message "LaTeX to MathML conversion failed")
17338 (message shell-command-output)))
17339 (delete-file tmp-in-file)
17340 (when (file-exists-p tmp-out-file)
17341 (delete-file tmp-out-file))
17342 mathml))
17344 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17345 prefix &optional dir)
17346 "Use `org-create-math-formula' but check local cache first."
17347 (let* ((absprefix (expand-file-name prefix dir))
17348 (print-length nil) (print-level nil)
17349 (formula-id (concat
17350 "formula-"
17351 (sha1
17352 (prin1-to-string
17353 (list latex-frag
17354 org-latex-to-mathml-convert-command)))))
17355 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17356 (formula-cache-dir (file-name-directory formula-cache)))
17358 (unless (file-directory-p formula-cache-dir)
17359 (make-directory formula-cache-dir t))
17361 (unless (file-exists-p formula-cache)
17362 (org-create-math-formula latex-frag formula-cache))
17364 (if (file-exists-p formula-cache)
17365 ;; Successful conversion. Return the link to MathML file.
17366 (org-add-props
17367 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17368 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17369 'org-latex-src-embed-type (if latex-frag-type
17370 'paragraph 'character)))
17371 ;; Failed conversion. Return the LaTeX fragment verbatim
17372 (add-text-properties
17373 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17374 latex-frag)))
17376 ;; This function borrows from Ganesh Swami's latex2png.el
17377 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17378 "This calls dvipng."
17379 (require 'org-latex)
17380 (let* ((tmpdir (if (featurep 'xemacs)
17381 (temp-directory)
17382 temporary-file-directory))
17383 (texfilebase (make-temp-name
17384 (expand-file-name "orgtex" tmpdir)))
17385 (texfile (concat texfilebase ".tex"))
17386 (dvifile (concat texfilebase ".dvi"))
17387 (pngfile (concat texfilebase ".png"))
17388 (fnh (if (featurep 'xemacs)
17389 (font-height (face-font 'default))
17390 (face-attribute 'default :height nil)))
17391 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17392 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17393 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17394 "Black"))
17395 (bg (or (plist-get options (if buffer :background :html-background))
17396 "Transparent")))
17397 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17398 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17399 (with-temp-file texfile
17400 (insert (org-splice-latex-header
17401 org-format-latex-header
17402 org-export-latex-default-packages-alist
17403 org-export-latex-packages-alist t
17404 org-format-latex-header-extra))
17405 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17406 (require 'org-latex)
17407 (org-export-latex-fix-inputenc))
17408 (let ((dir default-directory))
17409 (condition-case nil
17410 (progn
17411 (cd tmpdir)
17412 (call-process "latex" nil nil nil texfile))
17413 (error nil))
17414 (cd dir))
17415 (if (not (file-exists-p dvifile))
17416 (progn (message "Failed to create dvi file from %s" texfile) nil)
17417 (condition-case nil
17418 (if (featurep 'xemacs)
17419 (call-process "dvipng" nil nil nil
17420 "-fg" fg "-bg" bg
17421 "-T" "tight"
17422 "-o" pngfile
17423 dvifile)
17424 (call-process "dvipng" nil nil nil
17425 "-fg" fg "-bg" bg
17426 "-D" dpi
17427 ;;"-x" scale "-y" scale
17428 "-T" "tight"
17429 "-o" pngfile
17430 dvifile))
17431 (error nil))
17432 (if (not (file-exists-p pngfile))
17433 (if org-format-latex-signal-error
17434 (error "Failed to create png file from %s" texfile)
17435 (message "Failed to create png file from %s" texfile)
17436 nil)
17437 ;; Use the requested file name and clean up
17438 (copy-file pngfile tofile 'replace)
17439 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17440 (if (file-exists-p (concat texfilebase e))
17441 (delete-file (concat texfilebase e))))
17442 pngfile))))
17444 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17445 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17446 "This calls convert, which is included into imagemagick."
17447 (require 'org-latex)
17448 (let* ((tmpdir (if (featurep 'xemacs)
17449 (temp-directory)
17450 temporary-file-directory))
17451 (texfilebase (make-temp-name
17452 (expand-file-name "orgtex" tmpdir)))
17453 (texfile (concat texfilebase ".tex"))
17454 (pdffile (concat texfilebase ".pdf"))
17455 (pngfile (concat texfilebase ".png"))
17456 (fnh (if (featurep 'xemacs)
17457 (font-height (face-font 'default))
17458 (face-attribute 'default :height nil)))
17459 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17460 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17461 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17462 "black"))
17463 (bg (or (plist-get options (if buffer :background :html-background))
17464 "white")))
17465 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17466 (setq fg (org-latex-color-format fg)))
17467 (if (eq bg 'default) (setq bg (org-latex-color :background))
17468 (setq bg (org-latex-color-format
17469 (if (string= bg "Transparent")(setq bg "white")))))
17470 (with-temp-file texfile
17471 (insert (org-splice-latex-header
17472 org-format-latex-header
17473 org-export-latex-default-packages-alist
17474 org-export-latex-packages-alist t
17475 org-format-latex-header-extra))
17476 (insert "\n\\begin{document}\n"
17477 "\\definecolor{fg}{rgb}{" fg "}\n"
17478 "\\definecolor{bg}{rgb}{" bg "}\n"
17479 "\n\\pagecolor{bg}\n"
17480 "\n{\\color{fg}\n"
17481 string
17482 "\n}\n"
17483 "\n\\end{document}\n" )
17484 (require 'org-latex)
17485 (org-export-latex-fix-inputenc))
17486 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17487 (condition-case nil
17488 (progn
17489 (cd tmpdir)
17490 (setq cmds org-latex-to-pdf-process)
17491 (while cmds
17492 (setq latex-frags-cmds (pop cmds))
17493 (if (listp latex-frags-cmds)
17494 (setq cmds nil)
17495 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17496 (while latex-frags-cmds
17497 (setq cmd (pop latex-frags-cmds))
17498 (while (string-match "%b" cmd)
17499 (setq cmd (replace-match
17500 (save-match-data
17501 (shell-quote-argument texfile))
17502 t t cmd)))
17503 (while (string-match "%f" cmd)
17504 (setq cmd (replace-match
17505 (save-match-data
17506 (shell-quote-argument (file-name-nondirectory texfile)))
17507 t t cmd)))
17508 (while (string-match "%o" cmd)
17509 (setq cmd (replace-match
17510 (save-match-data
17511 (shell-quote-argument (file-name-directory texfile)))
17512 t t cmd)))
17513 (setq cmd (split-string cmd))
17514 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17515 (error nil))
17516 (cd dir))
17517 (if (not (file-exists-p pdffile))
17518 (progn (message "Failed to create pdf file from %s" texfile) nil)
17519 (condition-case nil
17520 (if (featurep 'xemacs)
17521 (call-process "convert" nil nil nil
17522 "-density" "96"
17523 "-trim"
17524 "-antialias"
17525 pdffile
17526 "-quality" "100"
17527 ;; "-sharpen" "0x1.0"
17528 pngfile)
17529 (call-process "convert" nil nil nil
17530 "-density" dpi
17531 "-trim"
17532 "-antialias"
17533 pdffile
17534 "-quality" "100"
17535 ; "-sharpen" "0x1.0"
17536 pngfile))
17537 (error nil))
17538 (if (not (file-exists-p pngfile))
17539 (if org-format-latex-signal-error
17540 (error "Failed to create png file from %s" texfile)
17541 (message "Failed to create png file from %s" texfile)
17542 nil)
17543 ;; Use the requested file name and clean up
17544 (copy-file pngfile tofile 'replace)
17545 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17546 (if (file-exists-p (concat texfilebase e))
17547 (delete-file (concat texfilebase e))))
17548 pngfile))))
17550 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17551 "Fill a LaTeX header template TPL.
17552 In the template, the following place holders will be recognized:
17554 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17555 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17556 [PACKAGES] \\usepackage statements for PKG
17557 [NO-PACKAGES] do not include PKG
17558 [EXTRA] the string EXTRA
17559 [NO-EXTRA] do not include EXTRA
17561 For backward compatibility, if both the positive and the negative place
17562 holder is missing, the positive one (without the \"NO-\") will be
17563 assumed to be present at the end of the template.
17564 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17565 EXTRA is a string.
17566 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17567 (let (rpl (end ""))
17568 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17569 (setq rpl (if (or (match-end 1) (not def-pkg))
17570 "" (org-latex-packages-to-string def-pkg snippets-p t))
17571 tpl (replace-match rpl t t tpl))
17572 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17574 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17575 (setq rpl (if (or (match-end 1) (not pkg))
17576 "" (org-latex-packages-to-string pkg snippets-p t))
17577 tpl (replace-match rpl t t tpl))
17578 (if pkg (setq end
17579 (concat end "\n"
17580 (org-latex-packages-to-string pkg snippets-p)))))
17582 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17583 (setq rpl (if (or (match-end 1) (not extra))
17584 "" (concat extra "\n"))
17585 tpl (replace-match rpl t t tpl))
17586 (if (and extra (string-match "\\S-" extra))
17587 (setq end (concat end "\n" extra))))
17589 (if (string-match "\\S-" end)
17590 (concat tpl "\n" end)
17591 tpl)))
17593 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17594 "Turn an alist of packages into a string with the \\usepackage macros."
17595 (setq pkg (mapconcat (lambda(p)
17596 (cond
17597 ((stringp p) p)
17598 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17599 (format "%% Package %s omitted" (cadr p)))
17600 ((equal "" (car p))
17601 (format "\\usepackage{%s}" (cadr p)))
17603 (format "\\usepackage[%s]{%s}"
17604 (car p) (cadr p)))))
17606 "\n"))
17607 (if newline (concat pkg "\n") pkg))
17609 (defun org-dvipng-color (attr)
17610 "Return a RGB color specification for dvipng."
17611 (apply 'format "rgb %s %s %s"
17612 (mapcar 'org-normalize-color
17613 (if (featurep 'xemacs)
17614 (color-rgb-components
17615 (face-property 'default
17616 (cond ((eq attr :foreground) 'foreground)
17617 ((eq attr :background) 'background))))
17618 (color-values (face-attribute 'default attr nil))))))
17620 (defun org-latex-color (attr)
17621 "Return a RGB color for the LaTeX color package."
17622 (apply 'format "%s,%s,%s"
17623 (mapcar 'org-normalize-color
17624 (if (featurep 'xemacs)
17625 (color-rgb-components
17626 (face-property 'default
17627 (cond ((eq attr :foreground) 'foreground)
17628 ((eq attr :background) 'background))))
17629 (color-values (face-attribute 'default attr nil))))))
17631 (defun org-latex-color-format (color-name)
17632 "Convert COLOR-NAME to a RGB color value."
17633 (apply 'format "%s,%s,%s"
17634 (mapcar 'org-normalize-color
17635 (color-values color-name))))
17637 (defun org-normalize-color (value)
17638 "Return string to be used as color value for an RGB component."
17639 (format "%g" (/ value 65535.0)))
17641 ;; Image display
17644 (defvar org-inline-image-overlays nil)
17645 (make-variable-buffer-local 'org-inline-image-overlays)
17647 (defun org-toggle-inline-images (&optional include-linked)
17648 "Toggle the display of inline images.
17649 INCLUDE-LINKED is passed to `org-display-inline-images'."
17650 (interactive "P")
17651 (if org-inline-image-overlays
17652 (progn
17653 (org-remove-inline-images)
17654 (message "Inline image display turned off"))
17655 (org-display-inline-images include-linked)
17656 (if org-inline-image-overlays
17657 (message "%d images displayed inline"
17658 (length org-inline-image-overlays))
17659 (message "No images to display inline"))))
17661 (defun org-display-inline-images (&optional include-linked refresh beg end)
17662 "Display inline images.
17663 Normally only links without a description part are inlined, because this
17664 is how it will work for export. When INCLUDE-LINKED is set, also links
17665 with a description part will be inlined. This can be nice for a quick
17666 look at those images, but it does not reflect what exported files will look
17667 like.
17668 When REFRESH is set, refresh existing images between BEG and END.
17669 This will create new image displays only if necessary.
17670 BEG and END default to the buffer boundaries."
17671 (interactive "P")
17672 (unless refresh
17673 (org-remove-inline-images)
17674 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17675 (save-excursion
17676 (save-restriction
17677 (widen)
17678 (setq beg (or beg (point-min)) end (or end (point-max)))
17679 (goto-char beg)
17680 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17681 (substring (org-image-file-name-regexp) 0 -2)
17682 "\\)\\]" (if include-linked "" "\\]")))
17683 old file ov img)
17684 (while (re-search-forward re end t)
17685 (setq old (get-char-property-and-overlay (match-beginning 1)
17686 'org-image-overlay))
17687 (setq file (expand-file-name
17688 (concat (or (match-string 3) "") (match-string 4))))
17689 (when (file-exists-p file)
17690 (if (and (car-safe old) refresh)
17691 (image-refresh (overlay-get (cdr old) 'display))
17692 (setq img (save-match-data (create-image file)))
17693 (when img
17694 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17695 (overlay-put ov 'display img)
17696 (overlay-put ov 'face 'default)
17697 (overlay-put ov 'org-image-overlay t)
17698 (overlay-put ov 'modification-hooks
17699 (list 'org-display-inline-modification-hook))
17700 (push ov org-inline-image-overlays)))))))))
17702 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17703 "Remove inline-display overlay if a corresponding region is modified."
17704 (let ((inhibit-modification-hooks t))
17705 (when (and ov after)
17706 (delete ov org-inline-image-overlays)
17707 (delete-overlay ov))))
17709 (defun org-remove-inline-images ()
17710 "Remove inline display of images."
17711 (interactive)
17712 (mapc 'delete-overlay org-inline-image-overlays)
17713 (setq org-inline-image-overlays nil))
17715 ;;;; Key bindings
17717 ;; Outline functions from `outline-mode-prefix-map'
17718 ;; that can be remapped in Org:
17719 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17720 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17721 (define-key org-mode-map [remap outline-forward-same-level]
17722 'org-forward-same-level)
17723 (define-key org-mode-map [remap outline-backward-same-level]
17724 'org-backward-same-level)
17725 (define-key org-mode-map [remap show-branches]
17726 'org-kill-note-or-show-branches)
17727 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17728 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17729 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17731 ;; Outline functions from `outline-mode-prefix-map' that can not
17732 ;; be remapped in Org:
17734 ;; - the column "key binding" shows whether the Outline function is still
17735 ;; available in Org mode on the same key that it has been bound to in
17736 ;; Outline mode:
17737 ;; - "overridden": key used for a different functionality in Org mode
17738 ;; - else: key still bound to the same Outline function in Org mode
17740 ;; | Outline function | key binding | Org replacement |
17741 ;; |------------------------------------+-------------+-----------------------|
17742 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17743 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17744 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17745 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17746 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17747 ;; | `show-entry' | overridden | no replacement |
17748 ;; | `show-children' | `C-c C-i' | visibility cycling |
17749 ;; | `show-branches' | `C-c C-k' | still same function |
17750 ;; | `show-subtree' | overridden | visibility cycling |
17751 ;; | `show-all' | overridden | no replacement |
17752 ;; | `hide-subtree' | overridden | visibility cycling |
17753 ;; | `hide-body' | overridden | no replacement |
17754 ;; | `hide-entry' | overridden | visibility cycling |
17755 ;; | `hide-leaves' | overridden | no replacement |
17756 ;; | `hide-sublevels' | overridden | no replacement |
17757 ;; | `hide-other' | overridden | no replacement |
17759 ;; Make `C-c C-x' a prefix key
17760 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17762 ;; TAB key with modifiers
17763 (org-defkey org-mode-map "\C-i" 'org-cycle)
17764 (org-defkey org-mode-map [(tab)] 'org-cycle)
17765 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17766 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17767 ;; The following line is necessary under Suse GNU/Linux
17768 (unless (featurep 'xemacs)
17769 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17770 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17771 (define-key org-mode-map [backtab] 'org-shifttab)
17773 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17774 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17775 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17777 ;; Cursor keys with modifiers
17778 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17779 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17780 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17781 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17783 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17784 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17785 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17786 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17788 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17789 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17790 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17791 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17793 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17794 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17795 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17796 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17798 ;; Babel keys
17799 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17800 (mapc (lambda (pair)
17801 (define-key org-babel-map (car pair) (cdr pair)))
17802 org-babel-key-bindings)
17804 ;;; Extra keys for tty access.
17805 ;; We only set them when really needed because otherwise the
17806 ;; menus don't show the simple keys
17808 (when (or org-use-extra-keys
17809 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17810 (not window-system))
17811 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17812 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17813 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17814 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17815 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17816 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17817 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17818 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17819 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17820 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17821 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17822 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17823 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17824 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17825 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17826 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17827 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17828 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17829 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17830 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17831 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17832 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17833 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17834 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17835 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17836 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17837 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17838 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17840 ;; All the other keys
17842 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17843 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17844 (if (boundp 'narrow-map)
17845 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17846 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17847 (if (boundp 'narrow-map)
17848 (org-defkey narrow-map "b" 'org-narrow-to-block)
17849 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17850 (if (boundp 'narrow-map)
17851 (org-defkey narrow-map "e" 'org-narrow-to-element)
17852 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17853 (org-defkey org-mode-map "\C-\M-t" 'org-element-transpose)
17854 (org-defkey org-mode-map [(control down)] 'org-element-forward)
17855 (org-defkey org-mode-map [(control up)] 'org-element-backward)
17856 (org-defkey org-mode-map "\M-}" 'org-element-forward)
17857 (org-defkey org-mode-map "\M-{" 'org-element-backward)
17858 (org-defkey org-mode-map "\C-c\C-^" 'org-element-up)
17859 (org-defkey org-mode-map "\C-c\C-_" 'org-element-down)
17860 (org-defkey org-mode-map "\C-\M-t" 'org-element-transpose)
17861 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17862 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17863 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17864 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17865 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17866 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17867 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17868 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17869 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17870 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17871 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17872 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17873 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17874 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17875 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17876 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17877 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17878 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17879 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17880 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17881 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17882 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17883 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17884 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17885 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17886 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17887 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17888 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
17889 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17890 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17891 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17892 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17893 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17894 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17895 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17896 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17897 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17898 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17899 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17900 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17901 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17902 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17903 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17904 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17905 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17906 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17907 (org-defkey org-mode-map "\C-c^" 'org-sort)
17908 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17909 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17910 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17911 (org-defkey org-mode-map "\C-m" 'org-return)
17912 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17913 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17914 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17915 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17916 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17917 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17918 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17919 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17920 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17921 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17922 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17923 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17924 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17925 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17926 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17927 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17928 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17929 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17930 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17931 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17932 (org-defkey org-mode-map "\C-c\C-@" 'org-element-mark-element)
17933 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17934 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17936 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17937 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17938 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17939 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17941 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17942 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17943 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
17944 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
17945 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17946 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17947 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
17948 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17949 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17950 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17951 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17952 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17953 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17954 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17955 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17956 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17957 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
17958 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17959 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17960 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17961 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17963 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17964 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17965 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17966 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17967 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17969 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17971 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17973 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17974 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17976 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17979 (when (featurep 'xemacs)
17980 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17983 (defconst org-speed-commands-default
17985 ("Outline Navigation")
17986 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17987 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17988 ("f" . (org-speed-move-safe 'org-forward-same-level))
17989 ("b" . (org-speed-move-safe 'org-backward-same-level))
17990 ("u" . (org-speed-move-safe 'outline-up-heading))
17991 ("j" . org-goto)
17992 ("g" . (org-refile t))
17993 ("Outline Visibility")
17994 ("c" . org-cycle)
17995 ("C" . org-shifttab)
17996 (" " . org-display-outline-path)
17997 (":" . org-columns)
17998 ("Outline Structure Editing")
17999 ("U" . org-shiftmetaup)
18000 ("D" . org-shiftmetadown)
18001 ("r" . org-metaright)
18002 ("l" . org-metaleft)
18003 ("R" . org-shiftmetaright)
18004 ("L" . org-shiftmetaleft)
18005 ("i" . (progn (forward-char 1) (call-interactively
18006 'org-insert-heading-respect-content)))
18007 ("^" . org-sort)
18008 ("w" . org-refile)
18009 ("a" . org-archive-subtree-default-with-confirmation)
18010 ("." . org-mark-subtree)
18011 ("#" . org-toggle-comment)
18012 ("Clock Commands")
18013 ("I" . org-clock-in)
18014 ("O" . org-clock-out)
18015 ("Meta Data Editing")
18016 ("t" . org-todo)
18017 ("0" . (org-priority ?\ ))
18018 ("1" . (org-priority ?A))
18019 ("2" . (org-priority ?B))
18020 ("3" . (org-priority ?C))
18021 (";" . org-set-tags-command)
18022 ("e" . org-set-effort)
18023 ("E" . org-inc-effort)
18024 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18025 (org-entry-put (point) "APPT_WARNTIME" m)))
18026 ("Agenda Views etc")
18027 ("v" . org-agenda)
18028 ("/" . org-sparse-tree)
18029 ("Misc")
18030 ("o" . org-open-at-point)
18031 ("?" . org-speed-command-help)
18032 ("<" . (org-agenda-set-restriction-lock 'subtree))
18033 (">" . (org-agenda-remove-restriction-lock))
18035 "The default speed commands.")
18037 (defun org-print-speed-command (e)
18038 (if (> (length (car e)) 1)
18039 (progn
18040 (princ "\n")
18041 (princ (car e))
18042 (princ "\n")
18043 (princ (make-string (length (car e)) ?-))
18044 (princ "\n"))
18045 (princ (car e))
18046 (princ " ")
18047 (if (symbolp (cdr e))
18048 (princ (symbol-name (cdr e)))
18049 (prin1 (cdr e)))
18050 (princ "\n")))
18052 (defun org-speed-command-help ()
18053 "Show the available speed commands."
18054 (interactive)
18055 (if (not org-use-speed-commands)
18056 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18057 (with-output-to-temp-buffer "*Help*"
18058 (princ "User-defined Speed commands\n===========================\n")
18059 (mapc 'org-print-speed-command org-speed-commands-user)
18060 (princ "\n")
18061 (princ "Built-in Speed commands\n=======================\n")
18062 (mapc 'org-print-speed-command org-speed-commands-default))
18063 (with-current-buffer "*Help*"
18064 (setq truncate-lines t))))
18066 (defun org-speed-move-safe (cmd)
18067 "Execute CMD, but make sure that the cursor always ends up in a headline.
18068 If not, return to the original position and throw an error."
18069 (interactive)
18070 (let ((pos (point)))
18071 (call-interactively cmd)
18072 (unless (and (bolp) (org-at-heading-p))
18073 (goto-char pos)
18074 (error "Boundary reached while executing %s" cmd))))
18076 (defvar org-self-insert-command-undo-counter 0)
18078 (defvar org-table-auto-blank-field) ; defined in org-table.el
18079 (defvar org-speed-command nil)
18081 (defun org-speed-command-default-hook (keys)
18082 "Hook for activating single-letter speed commands.
18083 `org-speed-commands-default' specifies a minimal command set.
18084 Use `org-speed-commands-user' for further customization."
18085 (when (or (and (bolp) (looking-at org-outline-regexp))
18086 (and (functionp org-use-speed-commands)
18087 (funcall org-use-speed-commands)))
18088 (cdr (assoc keys (append org-speed-commands-user
18089 org-speed-commands-default)))))
18091 (defun org-babel-speed-command-hook (keys)
18092 "Hook for activating single-letter code block commands."
18093 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18094 (cdr (assoc keys org-babel-key-bindings))))
18096 (defcustom org-speed-command-hook
18097 '(org-speed-command-default-hook org-babel-speed-command-hook)
18098 "Hook for activating speed commands at strategic locations.
18099 Hook functions are called in sequence until a valid handler is
18100 found.
18102 Each hook takes a single argument, a user-pressed command key
18103 which is also a `self-insert-command' from the global map.
18105 Within the hook, examine the cursor position and the command key
18106 and return nil or a valid handler as appropriate. Handler could
18107 be one of an interactive command, a function, or a form.
18109 Set `org-use-speed-commands' to non-nil value to enable this
18110 hook. The default setting is `org-speed-command-default-hook'."
18111 :group 'org-structure
18112 :version "24.1"
18113 :type 'hook)
18115 (defun org-self-insert-command (N)
18116 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18117 If the cursor is in a table looking at whitespace, the whitespace is
18118 overwritten, and the table is not marked as requiring realignment."
18119 (interactive "p")
18120 (org-check-before-invisible-edit 'insert)
18121 (cond
18122 ((and org-use-speed-commands
18123 (setq org-speed-command
18124 (run-hook-with-args-until-success
18125 'org-speed-command-hook (this-command-keys))))
18126 (cond
18127 ((commandp org-speed-command)
18128 (setq this-command org-speed-command)
18129 (call-interactively org-speed-command))
18130 ((functionp org-speed-command)
18131 (funcall org-speed-command))
18132 ((and org-speed-command (listp org-speed-command))
18133 (eval org-speed-command))
18134 (t (let (org-use-speed-commands)
18135 (call-interactively 'org-self-insert-command)))))
18136 ((and
18137 (org-table-p)
18138 (progn
18139 ;; check if we blank the field, and if that triggers align
18140 (and (featurep 'org-table) org-table-auto-blank-field
18141 (member last-command
18142 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18143 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18144 ;; got extra space, this field does not determine column width
18145 (let (org-table-may-need-update) (org-table-blank-field))
18146 ;; no extra space, this field may determine column width
18147 (org-table-blank-field)))
18149 (eq N 1)
18150 (looking-at "[^|\n]* |"))
18151 (let (org-table-may-need-update)
18152 (goto-char (1- (match-end 0)))
18153 (backward-delete-char 1)
18154 (goto-char (match-beginning 0))
18155 (self-insert-command N)))
18157 (setq org-table-may-need-update t)
18158 (self-insert-command N)
18159 (org-fix-tags-on-the-fly)
18160 (if org-self-insert-cluster-for-undo
18161 (if (not (eq last-command 'org-self-insert-command))
18162 (setq org-self-insert-command-undo-counter 1)
18163 (if (>= org-self-insert-command-undo-counter 20)
18164 (setq org-self-insert-command-undo-counter 1)
18165 (and (> org-self-insert-command-undo-counter 0)
18166 buffer-undo-list (listp buffer-undo-list)
18167 (not (cadr buffer-undo-list)) ; remove nil entry
18168 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18169 (setq org-self-insert-command-undo-counter
18170 (1+ org-self-insert-command-undo-counter))))))))
18172 (defun org-check-before-invisible-edit (kind)
18173 "Check is editing if kind KIND would be dangerous with invisible text around.
18174 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18175 ;; First, try to get out of here as quickly as possible, to reduce overhead
18176 (if (and org-catch-invisible-edits
18177 (or (not (boundp 'visible-mode)) (not visible-mode))
18178 (or (get-char-property (point) 'invisible)
18179 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18180 ;; OK, we need to take a closer look
18181 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18182 (invisible-before-point (if (bobp) nil (get-char-property
18183 (1- (point)) 'invisible)))
18184 (border-and-ok-direction
18186 ;; Check if we are acting predictably before invisible text
18187 (and invisible-at-point (not invisible-before-point)
18188 (memq kind '(insert delete-backward)))
18189 ;; Check if we are acting predictably after invisible text
18190 ;; This works not well, and I have turned it off. It seems
18191 ;; better to always show and stop after invisible text.
18192 ;; (and (not invisible-at-point) invisible-before-point
18193 ;; (memq kind '(insert delete)))
18196 (when (or (memq invisible-at-point '(outline org-hide-block))
18197 (memq invisible-before-point '(outline org-hide-block)))
18198 (if (eq org-catch-invisible-edits 'error)
18199 (error "Editing in invisible areas is prohibited - make visible first"))
18200 ;; Make the area visible
18201 (save-excursion
18202 (if invisible-before-point
18203 (goto-char (previous-single-char-property-change
18204 (point) 'invisible)))
18205 (org-cycle))
18206 (cond
18207 ((eq org-catch-invisible-edits 'show)
18208 ;; That's it, we do the edit after showing
18209 (message
18210 "Unfolding invisible region around point before editing")
18211 (sit-for 1))
18212 ((and (eq org-catch-invisible-edits 'smart)
18213 border-and-ok-direction)
18214 (message "Unfolding invisible region around point before editing"))
18216 ;; Don't do the edit, make the user repeat it in full visibility
18217 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
18219 (defun org-fix-tags-on-the-fly ()
18220 (when (and (equal (char-after (point-at-bol)) ?*)
18221 (org-at-heading-p))
18222 (org-align-tags-here org-tags-column)))
18224 (defun org-delete-backward-char (N)
18225 "Like `delete-backward-char', insert whitespace at field end in tables.
18226 When deleting backwards, in tables this function will insert whitespace in
18227 front of the next \"|\" separator, to keep the table aligned. The table will
18228 still be marked for re-alignment if the field did fill the entire column,
18229 because, in this case the deletion might narrow the column."
18230 (interactive "p")
18231 (org-check-before-invisible-edit 'delete-backward)
18232 (if (and (org-table-p)
18233 (eq N 1)
18234 (string-match "|" (buffer-substring (point-at-bol) (point)))
18235 (looking-at ".*?|"))
18236 (let ((pos (point))
18237 (noalign (looking-at "[^|\n\r]* |"))
18238 (c org-table-may-need-update))
18239 (backward-delete-char N)
18240 (if (not overwrite-mode)
18241 (progn
18242 (skip-chars-forward "^|")
18243 (insert " ")
18244 (goto-char (1- pos))))
18245 ;; noalign: if there were two spaces at the end, this field
18246 ;; does not determine the width of the column.
18247 (if noalign (setq org-table-may-need-update c)))
18248 (backward-delete-char N)
18249 (org-fix-tags-on-the-fly)))
18251 (defun org-delete-char (N)
18252 "Like `delete-char', but insert whitespace at field end in tables.
18253 When deleting characters, in tables this function will insert whitespace in
18254 front of the next \"|\" separator, to keep the table aligned. The table will
18255 still be marked for re-alignment if the field did fill the entire column,
18256 because, in this case the deletion might narrow the column."
18257 (interactive "p")
18258 (org-check-before-invisible-edit 'delete)
18259 (if (and (org-table-p)
18260 (not (bolp))
18261 (not (= (char-after) ?|))
18262 (eq N 1))
18263 (if (looking-at ".*?|")
18264 (let ((pos (point))
18265 (noalign (looking-at "[^|\n\r]* |"))
18266 (c org-table-may-need-update))
18267 (replace-match (concat
18268 (substring (match-string 0) 1 -1)
18269 " |"))
18270 (goto-char pos)
18271 ;; noalign: if there were two spaces at the end, this field
18272 ;; does not determine the width of the column.
18273 (if noalign (setq org-table-may-need-update c)))
18274 (delete-char N))
18275 (delete-char N)
18276 (org-fix-tags-on-the-fly)))
18278 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18279 (put 'org-self-insert-command 'delete-selection t)
18280 (put 'orgtbl-self-insert-command 'delete-selection t)
18281 (put 'org-delete-char 'delete-selection 'supersede)
18282 (put 'org-delete-backward-char 'delete-selection 'supersede)
18283 (put 'org-yank 'delete-selection 'yank)
18285 ;; Make `flyspell-mode' delay after some commands
18286 (put 'org-self-insert-command 'flyspell-delayed t)
18287 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18288 (put 'org-delete-char 'flyspell-delayed t)
18289 (put 'org-delete-backward-char 'flyspell-delayed t)
18291 ;; Make pabbrev-mode expand after org-mode commands
18292 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18293 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18295 ;; How to do this: Measure non-white length of current string
18296 ;; If equal to column width, we should realign.
18298 (defun org-remap (map &rest commands)
18299 "In MAP, remap the functions given in COMMANDS.
18300 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18301 (let (new old)
18302 (while commands
18303 (setq old (pop commands) new (pop commands))
18304 (if (fboundp 'command-remapping)
18305 (org-defkey map (vector 'remap old) new)
18306 (substitute-key-definition old new map global-map)))))
18308 (when (eq org-enable-table-editor 'optimized)
18309 ;; If the user wants maximum table support, we need to hijack
18310 ;; some standard editing functions
18311 (org-remap org-mode-map
18312 'self-insert-command 'org-self-insert-command
18313 'delete-char 'org-delete-char
18314 'delete-backward-char 'org-delete-backward-char)
18315 (org-defkey org-mode-map "|" 'org-force-self-insert))
18317 (defvar org-ctrl-c-ctrl-c-hook nil
18318 "Hook for functions attaching themselves to `C-c C-c'.
18320 This can be used to add additional functionality to the C-c C-c
18321 key which executes context-dependent commands. This hook is run
18322 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18323 run after the last test.
18325 Each function will be called with no arguments. The function
18326 must check if the context is appropriate for it to act. If yes,
18327 it should do its thing and then return a non-nil value. If the
18328 context is wrong, just do nothing and return nil.")
18330 (defvar org-ctrl-c-ctrl-c-final-hook nil
18331 "Hook for functions attaching themselves to `C-c C-c'.
18333 This can be used to add additional functionality to the C-c C-c
18334 key which executes context-dependent commands. This hook is run
18335 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18336 before the first test.
18338 Each function will be called with no arguments. The function
18339 must check if the context is appropriate for it to act. If yes,
18340 it should do its thing and then return a non-nil value. If the
18341 context is wrong, just do nothing and return nil.")
18343 (defvar org-tab-first-hook nil
18344 "Hook for functions to attach themselves to TAB.
18345 See `org-ctrl-c-ctrl-c-hook' for more information.
18346 This hook runs as the first action when TAB is pressed, even before
18347 `org-cycle' messes around with the `outline-regexp' to cater for
18348 inline tasks and plain list item folding.
18349 If any function in this hook returns t, any other actions that
18350 would have been caused by TAB (such as table field motion or visibility
18351 cycling) will not occur.")
18353 (defvar org-tab-after-check-for-table-hook nil
18354 "Hook for functions to attach themselves to TAB.
18355 See `org-ctrl-c-ctrl-c-hook' for more information.
18356 This hook runs after it has been established that the cursor is not in a
18357 table, but before checking if the cursor is in a headline or if global cycling
18358 should be done.
18359 If any function in this hook returns t, not other actions like visibility
18360 cycling will be done.")
18362 (defvar org-tab-after-check-for-cycling-hook nil
18363 "Hook for functions to attach themselves to TAB.
18364 See `org-ctrl-c-ctrl-c-hook' for more information.
18365 This hook runs after it has been established that not table field motion and
18366 not visibility should be done because of current context. This is probably
18367 the place where a package like yasnippets can hook in.")
18369 (defvar org-tab-before-tab-emulation-hook nil
18370 "Hook for functions to attach themselves to TAB.
18371 See `org-ctrl-c-ctrl-c-hook' for more information.
18372 This hook runs after every other options for TAB have been exhausted, but
18373 before indentation and \t insertion takes place.")
18375 (defvar org-metaleft-hook nil
18376 "Hook for functions attaching themselves to `M-left'.
18377 See `org-ctrl-c-ctrl-c-hook' for more information.")
18378 (defvar org-metaright-hook nil
18379 "Hook for functions attaching themselves to `M-right'.
18380 See `org-ctrl-c-ctrl-c-hook' for more information.")
18381 (defvar org-metaup-hook nil
18382 "Hook for functions attaching themselves to `M-up'.
18383 See `org-ctrl-c-ctrl-c-hook' for more information.")
18384 (defvar org-metadown-hook nil
18385 "Hook for functions attaching themselves to `M-down'.
18386 See `org-ctrl-c-ctrl-c-hook' for more information.")
18387 (defvar org-shiftmetaleft-hook nil
18388 "Hook for functions attaching themselves to `M-S-left'.
18389 See `org-ctrl-c-ctrl-c-hook' for more information.")
18390 (defvar org-shiftmetaright-hook nil
18391 "Hook for functions attaching themselves to `M-S-right'.
18392 See `org-ctrl-c-ctrl-c-hook' for more information.")
18393 (defvar org-shiftmetaup-hook nil
18394 "Hook for functions attaching themselves to `M-S-up'.
18395 See `org-ctrl-c-ctrl-c-hook' for more information.")
18396 (defvar org-shiftmetadown-hook nil
18397 "Hook for functions attaching themselves to `M-S-down'.
18398 See `org-ctrl-c-ctrl-c-hook' for more information.")
18399 (defvar org-metareturn-hook nil
18400 "Hook for functions attaching themselves to `M-RET'.
18401 See `org-ctrl-c-ctrl-c-hook' for more information.")
18402 (defvar org-shiftup-hook nil
18403 "Hook for functions attaching themselves to `S-up'.
18404 See `org-ctrl-c-ctrl-c-hook' for more information.")
18405 (defvar org-shiftup-final-hook nil
18406 "Hook for functions attaching themselves to `S-up'.
18407 This one runs after all other options except shift-select have been excluded.
18408 See `org-ctrl-c-ctrl-c-hook' for more information.")
18409 (defvar org-shiftdown-hook nil
18410 "Hook for functions attaching themselves to `S-down'.
18411 See `org-ctrl-c-ctrl-c-hook' for more information.")
18412 (defvar org-shiftdown-final-hook nil
18413 "Hook for functions attaching themselves to `S-down'.
18414 This one runs after all other options except shift-select have been excluded.
18415 See `org-ctrl-c-ctrl-c-hook' for more information.")
18416 (defvar org-shiftleft-hook nil
18417 "Hook for functions attaching themselves to `S-left'.
18418 See `org-ctrl-c-ctrl-c-hook' for more information.")
18419 (defvar org-shiftleft-final-hook nil
18420 "Hook for functions attaching themselves to `S-left'.
18421 This one runs after all other options except shift-select have been excluded.
18422 See `org-ctrl-c-ctrl-c-hook' for more information.")
18423 (defvar org-shiftright-hook nil
18424 "Hook for functions attaching themselves to `S-right'.
18425 See `org-ctrl-c-ctrl-c-hook' for more information.")
18426 (defvar org-shiftright-final-hook nil
18427 "Hook for functions attaching themselves to `S-right'.
18428 This one runs after all other options except shift-select have been excluded.
18429 See `org-ctrl-c-ctrl-c-hook' for more information.")
18431 (defun org-modifier-cursor-error ()
18432 "Throw an error, a modified cursor command was applied in wrong context."
18433 (error "This command is active in special context like tables, headlines or items"))
18435 (defun org-shiftselect-error ()
18436 "Throw an error because Shift-Cursor command was applied in wrong context."
18437 (if (and (boundp 'shift-select-mode) shift-select-mode)
18438 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18439 (error "This command works only in special context like headlines or timestamps")))
18441 (defun org-call-for-shift-select (cmd)
18442 (let ((this-command-keys-shift-translated t))
18443 (call-interactively cmd)))
18445 (defun org-shifttab (&optional arg)
18446 "Global visibility cycling or move to previous table field.
18447 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18448 on context.
18449 See the individual commands for more information."
18450 (interactive "P")
18451 (cond
18452 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18453 ((integerp arg)
18454 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18455 (message "Content view to level: %d" arg)
18456 (org-content (prefix-numeric-value arg2))
18457 (setq org-cycle-global-status 'overview)))
18458 (t (call-interactively 'org-global-cycle))))
18460 (defun org-shiftmetaleft ()
18461 "Promote subtree or delete table column.
18462 Calls `org-promote-subtree', `org-outdent-item-tree', or
18463 `org-table-delete-column', depending on context. See the
18464 individual commands for more information."
18465 (interactive)
18466 (cond
18467 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18468 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18469 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18470 ((if (not (org-region-active-p)) (org-at-item-p)
18471 (save-excursion (goto-char (region-beginning))
18472 (org-at-item-p)))
18473 (call-interactively 'org-outdent-item-tree))
18474 (t (org-modifier-cursor-error))))
18476 (defun org-shiftmetaright ()
18477 "Demote subtree or insert table column.
18478 Calls `org-demote-subtree', `org-indent-item-tree', or
18479 `org-table-insert-column', depending on context. See the
18480 individual commands for more information."
18481 (interactive)
18482 (cond
18483 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18484 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18485 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18486 ((if (not (org-region-active-p)) (org-at-item-p)
18487 (save-excursion (goto-char (region-beginning))
18488 (org-at-item-p)))
18489 (call-interactively 'org-indent-item-tree))
18490 (t (org-modifier-cursor-error))))
18492 (defun org-shiftmetaup (&optional arg)
18493 "Move subtree up or kill table row.
18494 Calls `org-move-subtree-up' or `org-table-kill-row' or
18495 `org-move-item-up' or `org-timestamp-up', depending on context.
18496 See the individual commands for more information."
18497 (interactive "P")
18498 (cond
18499 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18500 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18501 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18502 ((org-at-item-p) (call-interactively 'org-move-item-up))
18503 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18504 (call-interactively 'org-timestamp-up)))
18505 (t (org-modifier-cursor-error))))
18507 (defun org-shiftmetadown (&optional arg)
18508 "Move subtree down or insert table row.
18509 Calls `org-move-subtree-down' or `org-table-insert-row' or
18510 `org-move-item-down' or `org-timestamp-up', depending on context.
18511 See the individual commands for more information."
18512 (interactive "P")
18513 (cond
18514 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18515 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18516 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18517 ((org-at-item-p) (call-interactively 'org-move-item-down))
18518 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18519 (call-interactively 'org-timestamp-down)))
18520 (t (org-modifier-cursor-error))))
18522 (defsubst org-hidden-tree-error ()
18523 (error
18524 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18526 (defun org-metaleft (&optional arg)
18527 "Promote heading or move table column to left.
18528 Calls `org-do-promote' or `org-table-move-column', depending on context.
18529 With no specific context, calls the Emacs default `backward-word'.
18530 See the individual commands for more information."
18531 (interactive "P")
18532 (cond
18533 ((run-hook-with-args-until-success 'org-metaleft-hook))
18534 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18535 ((org-with-limited-levels
18536 (or (org-at-heading-p)
18537 (and (org-region-active-p)
18538 (save-excursion
18539 (goto-char (region-beginning))
18540 (org-at-heading-p)))))
18541 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18542 (call-interactively 'org-do-promote))
18543 ;; At an inline task.
18544 ((org-at-heading-p)
18545 (call-interactively 'org-inlinetask-promote))
18546 ((or (org-at-item-p)
18547 (and (org-region-active-p)
18548 (save-excursion
18549 (goto-char (region-beginning))
18550 (org-at-item-p))))
18551 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18552 (call-interactively 'org-outdent-item))
18553 (t (call-interactively 'backward-word))))
18555 (defun org-metaright (&optional arg)
18556 "Demote a subtree, a list item or move table column to right.
18557 In front of a drawer or a block keyword, indent it correctly.
18558 With no specific context, calls the Emacs default `forward-word'.
18559 See the individual commands for more information."
18560 (interactive "P")
18561 (cond
18562 ((run-hook-with-args-until-success 'org-metaright-hook))
18563 ((org-at-table-p) (call-interactively 'org-table-move-column))
18564 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18565 ((org-at-block-p) (call-interactively 'org-indent-block))
18566 ((org-with-limited-levels
18567 (or (org-at-heading-p)
18568 (and (org-region-active-p)
18569 (save-excursion
18570 (goto-char (region-beginning))
18571 (org-at-heading-p)))))
18572 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18573 (call-interactively 'org-do-demote))
18574 ;; At an inline task.
18575 ((org-at-heading-p)
18576 (call-interactively 'org-inlinetask-demote))
18577 ((or (org-at-item-p)
18578 (and (org-region-active-p)
18579 (save-excursion
18580 (goto-char (region-beginning))
18581 (org-at-item-p))))
18582 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18583 (call-interactively 'org-indent-item))
18584 (t (call-interactively 'forward-word))))
18586 (defun org-check-for-hidden (what)
18587 "Check if there are hidden headlines/items in the current visual line.
18588 WHAT can be either `headlines' or `items'. If the current line is
18589 an outline or item heading and it has a folded subtree below it,
18590 this function returns t, nil otherwise."
18591 (let ((re (cond
18592 ((eq what 'headlines) org-outline-regexp-bol)
18593 ((eq what 'items) (org-item-beginning-re))
18594 (t (error "This should not happen"))))
18595 beg end)
18596 (save-excursion
18597 (catch 'exit
18598 (unless (org-region-active-p)
18599 (setq beg (point-at-bol))
18600 (beginning-of-line 2)
18601 (while (and (not (eobp)) ;; this is like `next-line'
18602 (get-char-property (1- (point)) 'invisible))
18603 (beginning-of-line 2))
18604 (setq end (point))
18605 (goto-char beg)
18606 (goto-char (point-at-eol))
18607 (setq end (max end (point)))
18608 (while (re-search-forward re end t)
18609 (if (get-char-property (match-beginning 0) 'invisible)
18610 (throw 'exit t))))
18611 nil))))
18613 (defun org-metaup (&optional arg)
18614 "Move subtree up or move table row up.
18615 Calls `org-move-subtree-up' or `org-table-move-row' or
18616 `org-move-item-up', depending on context. See the individual commands
18617 for more information."
18618 (interactive "P")
18619 (cond
18620 ((run-hook-with-args-until-success 'org-metaup-hook))
18621 ((org-region-active-p)
18622 (let* ((a (min (region-beginning) (region-end)))
18623 (b (1- (max (region-beginning) (region-end))))
18624 (c (save-excursion (goto-char a)
18625 (move-beginning-of-line 0)))
18626 (d (save-excursion (goto-char a)
18627 (move-end-of-line 0) (point))))
18628 (transpose-regions a b c d)
18629 (goto-char c)))
18630 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18631 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18632 ((org-at-item-p) (call-interactively 'org-move-item-up))
18633 (t (org-element-drag-backward))))
18635 (defun org-metadown (&optional arg)
18636 "Move subtree down or move table row down.
18637 Calls `org-move-subtree-down' or `org-table-move-row' or
18638 `org-move-item-down', depending on context. See the individual
18639 commands for more information."
18640 (interactive "P")
18641 (cond
18642 ((run-hook-with-args-until-success 'org-metadown-hook))
18643 ((org-region-active-p)
18644 (let* ((a (min (region-beginning) (region-end)))
18645 (b (max (region-beginning) (region-end)))
18646 (c (save-excursion (goto-char b)
18647 (move-beginning-of-line 1)))
18648 (d (save-excursion (goto-char b)
18649 (move-end-of-line 1) (1+ (point)))))
18650 (transpose-regions a b c d)
18651 (goto-char d)))
18652 ((org-at-table-p) (call-interactively 'org-table-move-row))
18653 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18654 ((org-at-item-p) (call-interactively 'org-move-item-down))
18655 (t (org-element-drag-forward))))
18657 (defun org-shiftup (&optional arg)
18658 "Increase item in timestamp or increase priority of current headline.
18659 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18660 depending on context. See the individual commands for more information."
18661 (interactive "P")
18662 (cond
18663 ((run-hook-with-args-until-success 'org-shiftup-hook))
18664 ((and org-support-shift-select (org-region-active-p))
18665 (org-call-for-shift-select 'previous-line))
18666 ((org-at-timestamp-p t)
18667 (call-interactively (if org-edit-timestamp-down-means-later
18668 'org-timestamp-down 'org-timestamp-up)))
18669 ((and (not (eq org-support-shift-select 'always))
18670 org-enable-priority-commands
18671 (org-at-heading-p))
18672 (call-interactively 'org-priority-up))
18673 ((and (not org-support-shift-select) (org-at-item-p))
18674 (call-interactively 'org-previous-item))
18675 ((org-clocktable-try-shift 'up arg))
18676 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18677 (org-support-shift-select
18678 (org-call-for-shift-select 'previous-line))
18679 (t (org-shiftselect-error))))
18681 (defun org-shiftdown (&optional arg)
18682 "Decrease item in timestamp or decrease priority of current headline.
18683 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18684 depending on context. See the individual commands for more information."
18685 (interactive "P")
18686 (cond
18687 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18688 ((and org-support-shift-select (org-region-active-p))
18689 (org-call-for-shift-select 'next-line))
18690 ((org-at-timestamp-p t)
18691 (call-interactively (if org-edit-timestamp-down-means-later
18692 'org-timestamp-up 'org-timestamp-down)))
18693 ((and (not (eq org-support-shift-select 'always))
18694 org-enable-priority-commands
18695 (org-at-heading-p))
18696 (call-interactively 'org-priority-down))
18697 ((and (not org-support-shift-select) (org-at-item-p))
18698 (call-interactively 'org-next-item))
18699 ((org-clocktable-try-shift 'down arg))
18700 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18701 (org-support-shift-select
18702 (org-call-for-shift-select 'next-line))
18703 (t (org-shiftselect-error))))
18705 (defun org-shiftright (&optional arg)
18706 "Cycle the thing at point or in the current line, depending on context.
18707 Depending on context, this does one of the following:
18709 - switch a timestamp at point one day into the future
18710 - on a headline, switch to the next TODO keyword.
18711 - on an item, switch entire list to the next bullet type
18712 - on a property line, switch to the next allowed value
18713 - on a clocktable definition line, move time block into the future"
18714 (interactive "P")
18715 (cond
18716 ((run-hook-with-args-until-success 'org-shiftright-hook))
18717 ((and org-support-shift-select (org-region-active-p))
18718 (org-call-for-shift-select 'forward-char))
18719 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18720 ((and (not (eq org-support-shift-select 'always))
18721 (org-at-heading-p))
18722 (let ((org-inhibit-logging
18723 (not org-treat-S-cursor-todo-selection-as-state-change))
18724 (org-inhibit-blocking
18725 (not org-treat-S-cursor-todo-selection-as-state-change)))
18726 (org-call-with-arg 'org-todo 'right)))
18727 ((or (and org-support-shift-select
18728 (not (eq org-support-shift-select 'always))
18729 (org-at-item-bullet-p))
18730 (and (not org-support-shift-select) (org-at-item-p)))
18731 (org-call-with-arg 'org-cycle-list-bullet nil))
18732 ((and (not (eq org-support-shift-select 'always))
18733 (org-at-property-p))
18734 (call-interactively 'org-property-next-allowed-value))
18735 ((org-clocktable-try-shift 'right arg))
18736 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18737 (org-support-shift-select
18738 (org-call-for-shift-select 'forward-char))
18739 (t (org-shiftselect-error))))
18741 (defun org-shiftleft (&optional arg)
18742 "Cycle the thing at point or in the current line, depending on context.
18743 Depending on context, this does one of the following:
18745 - switch a timestamp at point one day into the past
18746 - on a headline, switch to the previous TODO keyword.
18747 - on an item, switch entire list to the previous bullet type
18748 - on a property line, switch to the previous allowed value
18749 - on a clocktable definition line, move time block into the past"
18750 (interactive "P")
18751 (cond
18752 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18753 ((and org-support-shift-select (org-region-active-p))
18754 (org-call-for-shift-select 'backward-char))
18755 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18756 ((and (not (eq org-support-shift-select 'always))
18757 (org-at-heading-p))
18758 (let ((org-inhibit-logging
18759 (not org-treat-S-cursor-todo-selection-as-state-change))
18760 (org-inhibit-blocking
18761 (not org-treat-S-cursor-todo-selection-as-state-change)))
18762 (org-call-with-arg 'org-todo 'left)))
18763 ((or (and org-support-shift-select
18764 (not (eq org-support-shift-select 'always))
18765 (org-at-item-bullet-p))
18766 (and (not org-support-shift-select) (org-at-item-p)))
18767 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18768 ((and (not (eq org-support-shift-select 'always))
18769 (org-at-property-p))
18770 (call-interactively 'org-property-previous-allowed-value))
18771 ((org-clocktable-try-shift 'left arg))
18772 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18773 (org-support-shift-select
18774 (org-call-for-shift-select 'backward-char))
18775 (t (org-shiftselect-error))))
18777 (defun org-shiftcontrolright ()
18778 "Switch to next TODO set."
18779 (interactive)
18780 (cond
18781 ((and org-support-shift-select (org-region-active-p))
18782 (org-call-for-shift-select 'forward-word))
18783 ((and (not (eq org-support-shift-select 'always))
18784 (org-at-heading-p))
18785 (org-call-with-arg 'org-todo 'nextset))
18786 (org-support-shift-select
18787 (org-call-for-shift-select 'forward-word))
18788 (t (org-shiftselect-error))))
18790 (defun org-shiftcontrolleft ()
18791 "Switch to previous TODO set."
18792 (interactive)
18793 (cond
18794 ((and org-support-shift-select (org-region-active-p))
18795 (org-call-for-shift-select 'backward-word))
18796 ((and (not (eq org-support-shift-select 'always))
18797 (org-at-heading-p))
18798 (org-call-with-arg 'org-todo 'previousset))
18799 (org-support-shift-select
18800 (org-call-for-shift-select 'backward-word))
18801 (t (org-shiftselect-error))))
18803 (defun org-shiftcontrolup ()
18804 "Change timestamps synchronously up in CLOCK log lines."
18805 (interactive)
18806 (cond ((and (not org-support-shift-select)
18807 (org-at-clock-log-p)
18808 (org-at-timestamp-p t))
18809 (org-clock-timestamps-up))
18810 (t (org-shiftselect-error))))
18812 (defun org-shiftcontroldown ()
18813 "Change timestamps synchronously down in CLOCK log lines."
18814 (interactive)
18815 (cond ((and (not org-support-shift-select)
18816 (org-at-clock-log-p)
18817 (org-at-timestamp-p t))
18818 (org-clock-timestamps-down))
18819 (t (org-shiftselect-error))))
18821 (defun org-ctrl-c-ret ()
18822 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18823 (interactive)
18824 (cond
18825 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18826 (t (call-interactively 'org-insert-heading))))
18828 (defun org-find-visible ()
18829 (let ((s (point)))
18830 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18831 (get-char-property s 'invisible)))
18833 (defun org-find-invisible ()
18834 (let ((s (point)))
18835 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18836 (not (get-char-property s 'invisible))))
18839 (defun org-copy-visible (beg end)
18840 "Copy the visible parts of the region."
18841 (interactive "r")
18842 (let (snippets s)
18843 (save-excursion
18844 (save-restriction
18845 (narrow-to-region beg end)
18846 (setq s (goto-char (point-min)))
18847 (while (not (= (point) (point-max)))
18848 (goto-char (org-find-invisible))
18849 (push (buffer-substring s (point)) snippets)
18850 (setq s (goto-char (org-find-visible))))))
18851 (kill-new (apply 'concat (nreverse snippets)))))
18853 (defun org-copy-special ()
18854 "Copy region in table or copy current subtree.
18855 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18856 See the individual commands for more information."
18857 (interactive)
18858 (call-interactively
18859 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18861 (defun org-cut-special ()
18862 "Cut region in table or cut current subtree.
18863 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18864 See the individual commands for more information."
18865 (interactive)
18866 (call-interactively
18867 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18869 (defun org-paste-special (arg)
18870 "Paste rectangular region into table, or past subtree relative to level.
18871 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18872 See the individual commands for more information."
18873 (interactive "P")
18874 (if (org-at-table-p)
18875 (org-table-paste-rectangle)
18876 (org-paste-subtree arg)))
18878 (defun org-edit-special (&optional arg)
18879 "Call a special editor for the stuff at point.
18880 When at a table, call the formula editor with `org-table-edit-formulas'.
18881 When at the first line of an src example, call `org-edit-src-code'.
18882 When in an #+include line, visit the include file. Otherwise call
18883 `ffap' to visit the file at point."
18884 (interactive)
18885 ;; possibly prep session before editing source
18886 (when arg
18887 (let* ((info (org-babel-get-src-block-info))
18888 (lang (nth 0 info))
18889 (params (nth 2 info))
18890 (session (cdr (assoc :session params))))
18891 (when (and info session) ;; we are in a source-code block with a session
18892 (funcall
18893 (intern (concat "org-babel-prep-session:" lang)) session params))))
18894 (cond ;; proceed with `org-edit-special'
18895 ((save-excursion
18896 (beginning-of-line 1)
18897 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18898 (find-file (org-trim (match-string 1))))
18899 ((org-edit-src-code))
18900 ((org-edit-fixed-width-region))
18901 ((org-at-table.el-p)
18902 (org-edit-src-code))
18903 ((or (org-at-table-p)
18904 (save-excursion
18905 (beginning-of-line 1)
18906 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18907 (call-interactively 'org-table-edit-formulas))
18908 (t (call-interactively 'ffap))))
18910 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18911 (defun org-ctrl-c-ctrl-c (&optional arg)
18912 "Set tags in headline, or update according to changed information at point.
18914 This command does many different things, depending on context:
18916 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18917 this is what we do.
18919 - If the cursor is on a statistics cookie, update it.
18921 - If the cursor is in a headline, prompt for tags and insert them
18922 into the current line, aligned to `org-tags-column'. When called
18923 with prefix arg, realign all tags in the current buffer.
18925 - If the cursor is in one of the special #+KEYWORD lines, this
18926 triggers scanning the buffer for these lines and updating the
18927 information.
18929 - If the cursor is inside a table, realign the table. This command
18930 works even if the automatic table editor has been turned off.
18932 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18933 the entire table.
18935 - If the cursor is at a footnote reference or definition, jump to
18936 the corresponding definition or references, respectively.
18938 - If the cursor is a the beginning of a dynamic block, update it.
18940 - If the current buffer is a capture buffer, close note and file it.
18942 - If the cursor is on a <<<target>>>, update radio targets and
18943 corresponding links in this buffer.
18945 - If the cursor is on a numbered item in a plain list, renumber the
18946 ordered list.
18948 - If the cursor is on a checkbox, toggle it.
18950 - If the cursor is on a code block, evaluate it. The variable
18951 `org-confirm-babel-evaluate' can be used to control prompting
18952 before code block evaluation, by default every code block
18953 evaluation requires confirmation. Code block evaluation can be
18954 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18955 (interactive "P")
18956 (let ((org-enable-table-editor t))
18957 (cond
18958 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18959 org-occur-highlights
18960 org-latex-fragment-image-overlays)
18961 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18962 (org-remove-occur-highlights)
18963 (org-remove-latex-fragment-image-overlays)
18964 (message "Temporary highlights/overlays removed from current buffer"))
18965 ((and (local-variable-p 'org-finish-function (current-buffer))
18966 (fboundp org-finish-function))
18967 (funcall org-finish-function))
18968 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18969 ((org-in-regexp org-ts-regexp-both)
18970 (org-timestamp-change 0 'day))
18971 ((or (looking-at org-property-start-re)
18972 (org-at-property-p))
18973 (call-interactively 'org-property-action))
18974 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
18975 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18976 (or (org-at-heading-p) (org-at-item-p)))
18977 (call-interactively 'org-update-statistics-cookies))
18978 ((org-at-heading-p) (call-interactively 'org-set-tags))
18979 ((org-at-table.el-p)
18980 (message "Use C-c ' to edit table.el tables"))
18981 ((org-at-table-p)
18982 (org-table-maybe-eval-formula)
18983 (if arg
18984 (call-interactively 'org-table-recalculate)
18985 (org-table-maybe-recalculate-line))
18986 (call-interactively 'org-table-align)
18987 (orgtbl-send-table 'maybe))
18988 ((or (org-footnote-at-reference-p)
18989 (org-footnote-at-definition-p))
18990 (call-interactively 'org-footnote-action))
18991 ((org-at-item-checkbox-p)
18992 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18993 ;; list only if at top item.
18994 (let* ((cbox (match-string 1))
18995 (struct (org-list-struct))
18996 (old-struct (copy-tree struct))
18997 (parents (org-list-parents-alist struct))
18998 (orderedp (org-entry-get nil "ORDERED"))
18999 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19000 block-item)
19001 ;; Use a light version of `org-toggle-checkbox' to avoid
19002 ;; computing list structure twice.
19003 (let ((new-box (cond
19004 ((equal arg '(16)) "[-]")
19005 ((equal arg '(4)) nil)
19006 ((equal "[X]" cbox) "[ ]")
19007 (t "[X]"))))
19008 (if (and firstp arg)
19009 ;; If at first item of sub-list, remove check-box from
19010 ;; every item at the same level.
19011 (mapc
19012 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19013 (org-list-get-all-items
19014 (point-at-bol) struct (org-list-prevs-alist struct)))
19015 (org-list-set-checkbox (point-at-bol) struct new-box)))
19016 ;; Replicate `org-list-write-struct', while grabbing a return
19017 ;; value from `org-list-struct-fix-box'.
19018 (org-list-struct-fix-ind struct parents 2)
19019 (org-list-struct-fix-item-end struct)
19020 (let ((prevs (org-list-prevs-alist struct)))
19021 (org-list-struct-fix-bul struct prevs)
19022 (org-list-struct-fix-ind struct parents)
19023 (setq block-item
19024 (org-list-struct-fix-box struct parents prevs orderedp)))
19025 (org-list-struct-apply-struct struct old-struct)
19026 (org-update-checkbox-count-maybe)
19027 (when block-item
19028 (message
19029 "Checkboxes were removed due to unchecked box at line %d"
19030 (org-current-line block-item)))
19031 (when firstp (org-list-send-list 'maybe))))
19032 ((org-at-item-p)
19033 ;; Cursor at an item: repair list. Do checkbox related actions
19034 ;; only if function was called with an argument. Send list only
19035 ;; if at top item.
19036 (let* ((struct (org-list-struct))
19037 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19038 old-struct)
19039 (when arg
19040 (setq old-struct (copy-tree struct))
19041 (if firstp
19042 ;; If at first item of sub-list, add check-box to every
19043 ;; item at the same level.
19044 (mapc
19045 (lambda (pos)
19046 (unless (org-list-get-checkbox pos struct)
19047 (org-list-set-checkbox pos struct "[ ]")))
19048 (org-list-get-all-items
19049 (point-at-bol) struct (org-list-prevs-alist struct)))
19050 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19051 (org-list-write-struct
19052 struct (org-list-parents-alist struct) old-struct)
19053 (when arg (org-update-checkbox-count-maybe))
19054 (when firstp (org-list-send-list 'maybe))))
19055 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19056 ;; Dynamic block
19057 (beginning-of-line 1)
19058 (save-excursion (org-update-dblock)))
19059 ((save-excursion
19060 (let ((case-fold-search t))
19061 (beginning-of-line 1)
19062 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19063 (cond
19064 ((or (equal (match-string 1) "TBLFM")
19065 (equal (match-string 1) "tblfm"))
19066 ;; Recalculate the table before this line
19067 (save-excursion
19068 (beginning-of-line 1)
19069 (skip-chars-backward " \r\n\t")
19070 (if (org-at-table-p)
19071 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19073 (let ((org-inhibit-startup-visibility-stuff t)
19074 (org-startup-align-all-tables nil))
19075 (when (boundp 'org-table-coordinate-overlays)
19076 (mapc 'delete-overlay org-table-coordinate-overlays)
19077 (setq org-table-coordinate-overlays nil))
19078 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19079 (message "Local setup has been refreshed"))))
19080 ((org-clock-update-time-maybe))
19082 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19083 (error "C-c C-c can do nothing useful at this location"))))))
19085 (defun org-mode-restart ()
19086 "Restart Org-mode, to scan again for special lines.
19087 Also updates the keyword regular expressions."
19088 (interactive)
19089 (org-mode)
19090 (message "Org-mode restarted"))
19092 (defun org-kill-note-or-show-branches ()
19093 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19094 (interactive)
19095 (if (not org-finish-function)
19096 (progn
19097 (hide-subtree)
19098 (call-interactively 'show-branches))
19099 (let ((org-note-abort t))
19100 (funcall org-finish-function))))
19102 (defun org-return (&optional indent)
19103 "Goto next table row or insert a newline.
19104 Calls `org-table-next-row' or `newline', depending on context.
19105 See the individual commands for more information."
19106 (interactive)
19107 (let (org-ts-what)
19108 (cond
19109 ((or (bobp) (org-in-src-block-p))
19110 (if indent (newline-and-indent) (newline)))
19111 ((org-at-table-p)
19112 (org-table-justify-field-maybe)
19113 (call-interactively 'org-table-next-row))
19114 ;; when `newline-and-indent' is called within a list, make sure
19115 ;; text moved stays inside the item.
19116 ((and (org-in-item-p) indent)
19117 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19118 (progn
19119 (save-match-data (newline))
19120 (org-indent-line-to (length (match-string 0))))
19121 (let ((ind (org-get-indentation)))
19122 (newline)
19123 (if (org-looking-back org-list-end-re)
19124 (org-indent-line)
19125 (org-indent-line-to ind)))))
19126 ((and org-return-follows-link
19127 (org-at-timestamp-p t)
19128 (not (eq org-ts-what 'after)))
19129 (org-follow-timestamp-link))
19130 ((and org-return-follows-link
19131 (let ((tprop (get-text-property (point) 'face)))
19132 (or (eq tprop 'org-link)
19133 (and (listp tprop) (memq 'org-link tprop)))))
19134 (call-interactively 'org-open-at-point))
19135 ((and (org-at-heading-p)
19136 (looking-at
19137 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19138 (org-show-entry)
19139 (end-of-line 1)
19140 (newline))
19141 (t (if indent (newline-and-indent) (newline))))))
19143 (defun org-return-indent ()
19144 "Goto next table row or insert a newline and indent.
19145 Calls `org-table-next-row' or `newline-and-indent', depending on
19146 context. See the individual commands for more information."
19147 (interactive)
19148 (org-return t))
19150 (defun org-ctrl-c-star ()
19151 "Compute table, or change heading status of lines.
19152 Calls `org-table-recalculate' or `org-toggle-heading',
19153 depending on context."
19154 (interactive)
19155 (cond
19156 ((org-at-table-p)
19157 (call-interactively 'org-table-recalculate))
19159 ;; Convert all lines in region to list items
19160 (call-interactively 'org-toggle-heading))))
19162 (defun org-ctrl-c-minus ()
19163 "Insert separator line in table or modify bullet status of line.
19164 Also turns a plain line or a region of lines into list items.
19165 Calls `org-table-insert-hline', `org-toggle-item', or
19166 `org-cycle-list-bullet', depending on context."
19167 (interactive)
19168 (cond
19169 ((org-at-table-p)
19170 (call-interactively 'org-table-insert-hline))
19171 ((org-region-active-p)
19172 (call-interactively 'org-toggle-item))
19173 ((org-in-item-p)
19174 (call-interactively 'org-cycle-list-bullet))
19176 (call-interactively 'org-toggle-item))))
19178 (defun org-toggle-item (arg)
19179 "Convert headings or normal lines to items, items to normal lines.
19180 If there is no active region, only the current line is considered.
19182 If the first non blank line in the region is an headline, convert
19183 all headlines to items, shifting text accordingly.
19185 If it is an item, convert all items to normal lines.
19187 If it is normal text, change region into an item. With a prefix
19188 argument ARG, change each line in region into an item."
19189 (interactive "P")
19190 (let ((shift-text
19191 (function
19192 ;; Shift text in current section to IND, from point to END.
19193 ;; The function leaves point to END line.
19194 (lambda (ind end)
19195 (let ((min-i 1000) (end (copy-marker end)))
19196 ;; First determine the minimum indentation (MIN-I) of
19197 ;; the text.
19198 (save-excursion
19199 (catch 'exit
19200 (while (< (point) end)
19201 (let ((i (org-get-indentation)))
19202 (cond
19203 ;; Skip blank lines and inline tasks.
19204 ((looking-at "^[ \t]*$"))
19205 ((looking-at org-outline-regexp-bol))
19206 ;; We can't find less than 0 indentation.
19207 ((zerop i) (throw 'exit (setq min-i 0)))
19208 ((< i min-i) (setq min-i i))))
19209 (forward-line))))
19210 ;; Then indent each line so that a line indented to
19211 ;; MIN-I becomes indented to IND. Ignore blank lines
19212 ;; and inline tasks in the process.
19213 (let ((delta (- ind min-i)))
19214 (while (< (point) end)
19215 (unless (or (looking-at "^[ \t]*$")
19216 (looking-at org-outline-regexp-bol))
19217 (org-indent-line-to (+ (org-get-indentation) delta)))
19218 (forward-line)))))))
19219 (skip-blanks
19220 (function
19221 ;; Return beginning of first non-blank line, starting from
19222 ;; line at POS.
19223 (lambda (pos)
19224 (save-excursion
19225 (goto-char pos)
19226 (skip-chars-forward " \r\t\n")
19227 (point-at-bol)))))
19228 beg end)
19229 ;; Determine boundaries of changes.
19230 (if (org-region-active-p)
19231 (setq beg (funcall skip-blanks (region-beginning))
19232 end (copy-marker (region-end)))
19233 (setq beg (funcall skip-blanks (point-at-bol))
19234 end (copy-marker (point-at-eol))))
19235 ;; Depending on the starting line, choose an action on the text
19236 ;; between BEG and END.
19237 (org-with-limited-levels
19238 (save-excursion
19239 (goto-char beg)
19240 (cond
19241 ;; Case 1. Start at an item: de-itemize. Note that it only
19242 ;; happens when a region is active: `org-ctrl-c-minus'
19243 ;; would call `org-cycle-list-bullet' otherwise.
19244 ((org-at-item-p)
19245 (while (< (point) end)
19246 (when (org-at-item-p)
19247 (skip-chars-forward " \t")
19248 (delete-region (point) (match-end 0)))
19249 (forward-line)))
19250 ;; Case 2. Start at an heading: convert to items.
19251 ((org-at-heading-p)
19252 (let* ((bul (org-list-bullet-string "-"))
19253 (bul-len (length bul))
19254 ;; Indentation of the first heading. It should be
19255 ;; relative to the indentation of its parent, if any.
19256 (start-ind (save-excursion
19257 (cond
19258 ((not org-adapt-indentation) 0)
19259 ((not (outline-previous-heading)) 0)
19260 (t (length (match-string 0))))))
19261 ;; Level of first heading. Further headings will be
19262 ;; compared to it to determine hierarchy in the list.
19263 (ref-level (org-reduced-level (org-outline-level))))
19264 (while (< (point) end)
19265 (let* ((level (org-reduced-level (org-outline-level)))
19266 (delta (max 0 (- level ref-level))))
19267 ;; If current headline is less indented than the first
19268 ;; one, set it as reference, in order to preserve
19269 ;; subtrees.
19270 (when (< level ref-level) (setq ref-level level))
19271 (replace-match bul t t)
19272 (org-indent-line-to (+ start-ind (* delta bul-len)))
19273 ;; Ensure all text down to END (or SECTION-END) belongs
19274 ;; to the newly created item.
19275 (let ((section-end (save-excursion
19276 (or (outline-next-heading) (point)))))
19277 (forward-line)
19278 (funcall shift-text
19279 (+ start-ind (* (1+ delta) bul-len))
19280 (min end section-end)))))))
19281 ;; Case 3. Normal line with ARG: turn each non-item line into
19282 ;; an item.
19283 (arg
19284 (while (< (point) end)
19285 (unless (or (org-at-heading-p) (org-at-item-p))
19286 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19287 (replace-match
19288 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19289 (forward-line)))
19290 ;; Case 4. Normal line without ARG: make the first line of
19291 ;; region an item, and shift indentation of others
19292 ;; lines to set them as item's body.
19293 (t (let* ((bul (org-list-bullet-string "-"))
19294 (bul-len (length bul))
19295 (ref-ind (org-get-indentation)))
19296 (skip-chars-forward " \t")
19297 (insert bul)
19298 (forward-line)
19299 (while (< (point) end)
19300 ;; Ensure that lines less indented than first one
19301 ;; still get included in item body.
19302 (funcall shift-text
19303 (+ ref-ind bul-len)
19304 (min end (save-excursion (or (outline-next-heading)
19305 (point)))))
19306 (forward-line)))))))))
19308 (defun org-toggle-heading (&optional nstars)
19309 "Convert headings to normal text, or items or text to headings.
19310 If there is no active region, only the current line is considered.
19312 With a \\[universal-argument] prefix, convert the whole list at
19313 point into heading.
19315 In a region:
19317 - If the first non blank line is an headline, remove the stars
19318 from all headlines in the region.
19320 - If it is a normal line turn each and every normal line (i.e. not an
19321 heading or an item) in the region into a heading.
19323 - If it is a plain list item, turn all plain list items into headings.
19325 When converting a line into a heading, the number of stars is chosen
19326 such that the lines become children of the current entry. However,
19327 when a prefix argument is given, its value determines the number of
19328 stars to add."
19329 (interactive "P")
19330 (let ((skip-blanks
19331 (function
19332 ;; Return beginning of first non-blank line, starting from
19333 ;; line at POS.
19334 (lambda (pos)
19335 (save-excursion
19336 (goto-char pos)
19337 (while (org-at-comment-p) (forward-line))
19338 (skip-chars-forward " \r\t\n")
19339 (point-at-bol)))))
19340 beg end toggled)
19341 ;; Determine boundaries of changes. If a universal prefix has
19342 ;; been given, put the list in a region. If region ends at a bol,
19343 ;; do not consider the last line to be in the region.
19345 (when (and current-prefix-arg (org-at-item-p))
19346 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19347 (org-element-mark-element))
19349 (if (org-region-active-p)
19350 (setq beg (funcall skip-blanks (region-beginning))
19351 end (copy-marker (save-excursion
19352 (goto-char (region-end))
19353 (if (bolp) (point) (point-at-eol)))))
19354 (setq beg (funcall skip-blanks (point-at-bol))
19355 end (copy-marker (point-at-eol))))
19356 ;; Ensure inline tasks don't count as headings.
19357 (org-with-limited-levels
19358 (save-excursion
19359 (goto-char beg)
19360 (cond
19361 ;; Case 1. Started at an heading: de-star headings.
19362 ((org-at-heading-p)
19363 (while (< (point) end)
19364 (when (org-at-heading-p t)
19365 (looking-at org-outline-regexp) (replace-match "")
19366 (setq toggled t))
19367 (forward-line)))
19368 ;; Case 2. Started at an item: change items into headlines.
19369 ;; One star will be added by `org-list-to-subtree'.
19370 ((org-at-item-p)
19371 (let* ((stars (make-string
19372 (if nstars
19373 ;; subtract the star that will be added again by
19374 ;; `org-list-to-subtree'
19375 (1- (prefix-numeric-value current-prefix-arg))
19376 (or (org-current-level) 0))
19377 ?*))
19378 (add-stars
19379 (cond (nstars "") ; stars from prefix only
19380 ((equal stars "") "") ; before first heading
19381 (org-odd-levels-only "*") ; inside heading, odd
19382 (t "")))) ; inside heading, oddeven
19383 (while (< (point) end)
19384 (when (org-at-item-p)
19385 ;; Pay attention to cases when region ends before list.
19386 (let* ((struct (org-list-struct))
19387 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19388 (save-restriction
19389 (narrow-to-region (point) list-end)
19390 (insert
19391 (org-list-to-subtree
19392 (org-list-parse-list t)
19393 '(:istart (concat stars add-stars (funcall get-stars depth))
19394 :icount (concat stars add-stars (funcall get-stars depth)))))))
19395 (setq toggled t))
19396 (forward-line))))
19397 ;; Case 3. Started at normal text: make every line an heading,
19398 ;; skipping headlines and items.
19399 (t (let* ((stars (make-string
19400 (if nstars
19401 (prefix-numeric-value current-prefix-arg)
19402 (or (org-current-level) 0))
19403 ?*))
19404 (add-stars
19405 (cond (nstars "") ; stars from prefix only
19406 ((equal stars "") "*") ; before first heading
19407 (org-odd-levels-only "**") ; inside heading, odd
19408 (t "*"))) ; inside heading, oddeven
19409 (rpl (concat stars add-stars " ")))
19410 (while (< (point) end)
19411 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19412 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19413 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19414 (forward-line)))))))
19415 (unless toggled (message "Cannot toggle heading from here"))))
19417 (defun org-meta-return (&optional arg)
19418 "Insert a new heading or wrap a region in a table.
19419 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19420 See the individual commands for more information."
19421 (interactive "P")
19422 (cond
19423 ((run-hook-with-args-until-success 'org-metareturn-hook))
19424 ((or (org-at-drawer-p) (org-at-property-p))
19425 (newline-and-indent))
19426 ((org-at-table-p)
19427 (call-interactively 'org-table-wrap-region))
19428 (t (call-interactively 'org-insert-heading))))
19430 ;;; Menu entries
19432 ;; Define the Org-mode menus
19433 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19434 '("Tbl"
19435 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19436 ["Next Field" org-cycle (org-at-table-p)]
19437 ["Previous Field" org-shifttab (org-at-table-p)]
19438 ["Next Row" org-return (org-at-table-p)]
19439 "--"
19440 ["Blank Field" org-table-blank-field (org-at-table-p)]
19441 ["Edit Field" org-table-edit-field (org-at-table-p)]
19442 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19443 "--"
19444 ("Column"
19445 ["Move Column Left" org-metaleft (org-at-table-p)]
19446 ["Move Column Right" org-metaright (org-at-table-p)]
19447 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19448 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19449 ("Row"
19450 ["Move Row Up" org-metaup (org-at-table-p)]
19451 ["Move Row Down" org-metadown (org-at-table-p)]
19452 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19453 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19454 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19455 "--"
19456 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19457 ("Rectangle"
19458 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19459 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19460 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19461 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19462 "--"
19463 ("Calculate"
19464 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19465 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19466 ["Edit Formulas" org-edit-special (org-at-table-p)]
19467 "--"
19468 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19469 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19470 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19471 "--"
19472 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19473 "--"
19474 ["Sum Column/Rectangle" org-table-sum
19475 (or (org-at-table-p) (org-region-active-p))]
19476 ["Which Column?" org-table-current-column (org-at-table-p)])
19477 ["Debug Formulas"
19478 org-table-toggle-formula-debugger
19479 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19480 ["Show Col/Row Numbers"
19481 org-table-toggle-coordinate-overlays
19482 :style toggle
19483 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19484 "--"
19485 ["Create" org-table-create (and (not (org-at-table-p))
19486 org-enable-table-editor)]
19487 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19488 ["Import from File" org-table-import (not (org-at-table-p))]
19489 ["Export to File" org-table-export (org-at-table-p)]
19490 "--"
19491 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19493 (easy-menu-define org-org-menu org-mode-map "Org menu"
19494 '("Org"
19495 ("Show/Hide"
19496 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19497 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19498 ["Sparse Tree..." org-sparse-tree t]
19499 ["Reveal Context" org-reveal t]
19500 ["Show All" show-all t]
19501 "--"
19502 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19503 "--"
19504 ["New Heading" org-insert-heading t]
19505 ("Navigate Headings"
19506 ["Up" outline-up-heading t]
19507 ["Next" outline-next-visible-heading t]
19508 ["Previous" outline-previous-visible-heading t]
19509 ["Next Same Level" outline-forward-same-level t]
19510 ["Previous Same Level" outline-backward-same-level t]
19511 "--"
19512 ["Jump" org-goto t])
19513 ("Edit Structure"
19514 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19515 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19516 "--"
19517 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19518 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19519 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19520 "--"
19521 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19522 "--"
19523 ["Copy visible text" org-copy-visible t]
19524 "--"
19525 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19526 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19527 ["Demote Heading" org-metaright (not (org-at-table-p))]
19528 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19529 "--"
19530 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19531 "--"
19532 ["Convert to odd levels" org-convert-to-odd-levels t]
19533 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19534 ("Editing"
19535 ["Emphasis..." org-emphasize t]
19536 ["Edit Source Example" org-edit-special t]
19537 "--"
19538 ["Footnote new/jump" org-footnote-action t]
19539 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19540 ("Archive"
19541 ["Archive (default method)" org-archive-subtree-default t]
19542 "--"
19543 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19544 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19545 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19547 "--"
19548 ("Hyperlinks"
19549 ["Store Link (Global)" org-store-link t]
19550 ["Find existing link to here" org-occur-link-in-agenda-files t]
19551 ["Insert Link" org-insert-link t]
19552 ["Follow Link" org-open-at-point t]
19553 "--"
19554 ["Next link" org-next-link t]
19555 ["Previous link" org-previous-link t]
19556 "--"
19557 ["Descriptive Links"
19558 org-toggle-link-display
19559 :style radio
19560 :selected org-descriptive-links
19562 ["Literal Links"
19563 org-toggle-link-display
19564 :style radio
19565 :selected (not org-descriptive-links)])
19566 "--"
19567 ("TODO Lists"
19568 ["TODO/DONE/-" org-todo t]
19569 ("Select keyword"
19570 ["Next keyword" org-shiftright (org-at-heading-p)]
19571 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19572 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19573 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19574 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19575 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19576 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19577 "--"
19578 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19579 :selected org-enforce-todo-dependencies :style toggle :active t]
19580 "Settings for tree at point"
19581 ["Do Children sequentially" org-toggle-ordered-property :style radio
19582 :selected (org-entry-get nil "ORDERED")
19583 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19584 ["Do Children parallel" org-toggle-ordered-property :style radio
19585 :selected (not (org-entry-get nil "ORDERED"))
19586 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19587 "--"
19588 ["Set Priority" org-priority t]
19589 ["Priority Up" org-shiftup t]
19590 ["Priority Down" org-shiftdown t]
19591 "--"
19592 ["Get news from all feeds" org-feed-update-all t]
19593 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19594 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19595 ("TAGS and Properties"
19596 ["Set Tags" org-set-tags-command t]
19597 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19598 "--"
19599 ["Set property" org-set-property t]
19600 ["Column view of properties" org-columns t]
19601 ["Insert Column View DBlock" org-insert-columns-dblock t])
19602 ("Dates and Scheduling"
19603 ["Timestamp" org-time-stamp t]
19604 ["Timestamp (inactive)" org-time-stamp-inactive t]
19605 ("Change Date"
19606 ["1 Day Later" org-shiftright t]
19607 ["1 Day Earlier" org-shiftleft t]
19608 ["1 ... Later" org-shiftup t]
19609 ["1 ... Earlier" org-shiftdown t])
19610 ["Compute Time Range" org-evaluate-time-range t]
19611 ["Schedule Item" org-schedule t]
19612 ["Deadline" org-deadline t]
19613 "--"
19614 ["Custom time format" org-toggle-time-stamp-overlays
19615 :style radio :selected org-display-custom-times]
19616 "--"
19617 ["Goto Calendar" org-goto-calendar t]
19618 ["Date from Calendar" org-date-from-calendar t]
19619 "--"
19620 ["Start/Restart Timer" org-timer-start t]
19621 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19622 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19623 ["Insert Timer String" org-timer t]
19624 ["Insert Timer Item" org-timer-item t])
19625 ("Logging work"
19626 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19627 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19628 ["Clock out" org-clock-out t]
19629 ["Clock cancel" org-clock-cancel t]
19630 "--"
19631 ["Mark as default task" org-clock-mark-default-task t]
19632 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19633 ["Goto running clock" org-clock-goto t]
19634 "--"
19635 ["Display times" org-clock-display t]
19636 ["Create clock table" org-clock-report t]
19637 "--"
19638 ["Record DONE time"
19639 (progn (setq org-log-done (not org-log-done))
19640 (message "Switching to %s will %s record a timestamp"
19641 (car org-done-keywords)
19642 (if org-log-done "automatically" "not")))
19643 :style toggle :selected org-log-done])
19644 "--"
19645 ["Agenda Command..." org-agenda t]
19646 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19647 ("File List for Agenda")
19648 ("Special views current file"
19649 ["TODO Tree" org-show-todo-tree t]
19650 ["Check Deadlines" org-check-deadlines t]
19651 ["Timeline" org-timeline t]
19652 ["Tags/Property tree" org-match-sparse-tree t])
19653 "--"
19654 ["Export/Publish..." org-export t]
19655 ("LaTeX"
19656 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19657 :selected org-cdlatex-mode]
19658 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19659 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19660 ["Modify math symbol" org-cdlatex-math-modify
19661 (org-inside-LaTeX-fragment-p)]
19662 ["Insert citation" org-reftex-citation t]
19663 "--"
19664 ["Template for BEAMER" (progn (require 'org-beamer)
19665 (org-insert-beamer-options-template)) t])
19666 "--"
19667 ("MobileOrg"
19668 ["Push Files and Views" org-mobile-push t]
19669 ["Get Captured and Flagged" org-mobile-pull t]
19670 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19671 "--"
19672 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19673 "--"
19674 ("Documentation"
19675 ["Show Version" org-version t]
19676 ["Info Documentation" org-info t])
19677 ("Customize"
19678 ["Browse Org Group" org-customize t]
19679 "--"
19680 ["Expand This Menu" org-create-customize-menu
19681 (fboundp 'customize-menu-create)])
19682 ["Send bug report" org-submit-bug-report t]
19683 "--"
19684 ("Refresh/Reload"
19685 ["Refresh setup current buffer" org-mode-restart t]
19686 ["Reload Org (after update)" org-reload t]
19687 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19690 (defun org-info (&optional node)
19691 "Read documentation for Org-mode in the info system.
19692 With optional NODE, go directly to that node."
19693 (interactive)
19694 (info (format "(org)%s" (or node ""))))
19696 ;;;###autoload
19697 (defun org-submit-bug-report ()
19698 "Submit a bug report on Org-mode via mail.
19700 Don't hesitate to report any problems or inaccurate documentation.
19702 If you don't have setup sending mail from (X)Emacs, please copy the
19703 output buffer into your mail program, as it gives us important
19704 information about your Org-mode version and configuration."
19705 (interactive)
19706 (require 'reporter)
19707 (org-load-modules-maybe)
19708 (org-require-autoloaded-modules)
19709 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19710 (reporter-submit-bug-report
19711 "emacs-orgmode@gnu.org"
19712 (org-version nil 'full)
19713 (let (list)
19714 (save-window-excursion
19715 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19716 (delete-other-windows)
19717 (erase-buffer)
19718 (insert "You are about to submit a bug report to the Org-mode mailing list.
19720 We would like to add your full Org-mode and Outline configuration to the
19721 bug report. This greatly simplifies the work of the maintainer and
19722 other experts on the mailing list.
19724 HOWEVER, some variables you have customized may contain private
19725 information. The names of customers, colleagues, or friends, might
19726 appear in the form of file names, tags, todo states, or search strings.
19727 If you answer yes to the prompt, you might want to check and remove
19728 such private information before sending the email.")
19729 (add-text-properties (point-min) (point-max) '(face org-warning))
19730 (when (yes-or-no-p "Include your Org-mode configuration ")
19731 (mapatoms
19732 (lambda (v)
19733 (and (boundp v)
19734 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19735 (or (and (symbol-value v)
19736 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19737 (and
19738 (get v 'custom-type) (get v 'standard-value)
19739 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19740 (push v list)))))
19741 (kill-buffer (get-buffer "*Warn about privacy*"))
19742 list))
19743 nil nil
19744 "Remember to cover the basics, that is, what you expected to happen and
19745 what in fact did happen. You don't know how to make a good report? See
19747 http://orgmode.org/manual/Feedback.html#Feedback
19749 Your bug report will be posted to the Org-mode mailing list.
19750 ------------------------------------------------------------------------")
19751 (save-excursion
19752 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19753 (replace-match "\\1Bug: \\3 [\\2]")))))
19756 (defun org-install-agenda-files-menu ()
19757 (let ((bl (buffer-list)))
19758 (save-excursion
19759 (while bl
19760 (set-buffer (pop bl))
19761 (if (derived-mode-p 'org-mode) (setq bl nil)))
19762 (when (derived-mode-p 'org-mode)
19763 (easy-menu-change
19764 '("Org") "File List for Agenda"
19765 (append
19766 (list
19767 ["Edit File List" (org-edit-agenda-file-list) t]
19768 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19769 ["Remove Current File from List" org-remove-file t]
19770 ["Cycle through agenda files" org-cycle-agenda-files t]
19771 ["Occur in all agenda files" org-occur-in-agenda-files t]
19772 "--")
19773 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19775 ;;;; Documentation
19777 ;;;###autoload
19778 (defun org-require-autoloaded-modules ()
19779 (interactive)
19780 (mapc 'require
19781 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19782 org-docbook org-exp org-html org-icalendar
19783 org-id org-latex
19784 org-publish org-remember org-table
19785 org-timer org-xoxo)))
19787 ;;;###autoload
19788 (defun org-reload (&optional uncompiled)
19789 "Reload all org lisp files.
19790 With prefix arg UNCOMPILED, load the uncompiled versions."
19791 (interactive "P")
19792 (require 'find-func)
19793 (let* ((file-re "^org\\(-.*\\)?\\.el")
19794 (dir-org (file-name-directory (org-find-library-dir "org")))
19795 (dir-org-contrib (ignore-errors
19796 (file-name-directory
19797 (org-find-library-dir "org-contribdir"))))
19798 (babel-files
19799 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19800 (append (list nil "comint" "eval" "exp" "keys"
19801 "lob" "ref" "table" "tangle")
19802 (delq nil
19803 (mapcar
19804 (lambda (lang)
19805 (when (cdr lang) (symbol-name (car lang))))
19806 org-babel-load-languages)))))
19807 (files
19808 (append babel-files
19809 (and dir-org-contrib
19810 (directory-files dir-org-contrib t file-re))
19811 (directory-files dir-org t file-re)))
19812 (remove-re (concat (if (featurep 'xemacs)
19813 "org-colview" "org-colview-xemacs")
19814 "\\'")))
19815 (setq files (mapcar 'file-name-sans-extension files))
19816 (setq files (mapcar
19817 (lambda (x) (if (string-match remove-re x) nil x))
19818 files))
19819 (setq files (delq nil files))
19820 (mapc
19821 (lambda (f)
19822 (when (featurep (intern (file-name-nondirectory f)))
19823 (if (and (not uncompiled)
19824 (file-exists-p (concat f ".elc")))
19825 (load (concat f ".elc") nil nil 'nosuffix)
19826 (load (concat f ".el") nil nil 'nosuffix))))
19827 files)
19828 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19829 (org-version nil 'full 'message))
19831 ;;;###autoload
19832 (defun org-customize ()
19833 "Call the customize function with org as argument."
19834 (interactive)
19835 (org-load-modules-maybe)
19836 (org-require-autoloaded-modules)
19837 (customize-browse 'org))
19839 (defun org-create-customize-menu ()
19840 "Create a full customization menu for Org-mode, insert it into the menu."
19841 (interactive)
19842 (org-load-modules-maybe)
19843 (org-require-autoloaded-modules)
19844 (if (fboundp 'customize-menu-create)
19845 (progn
19846 (easy-menu-change
19847 '("Org") "Customize"
19848 `(["Browse Org group" org-customize t]
19849 "--"
19850 ,(customize-menu-create 'org)
19851 ["Set" Custom-set t]
19852 ["Save" Custom-save t]
19853 ["Reset to Current" Custom-reset-current t]
19854 ["Reset to Saved" Custom-reset-saved t]
19855 ["Reset to Standard Settings" Custom-reset-standard t]))
19856 (message "\"Org\"-menu now contains full customization menu"))
19857 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19859 ;;;; Miscellaneous stuff
19861 ;;; Generally useful functions
19863 (defun org-get-at-bol (property)
19864 "Get text property PROPERTY at beginning of line."
19865 (get-text-property (point-at-bol) property))
19867 (defun org-find-text-property-in-string (prop s)
19868 "Return the first non-nil value of property PROP in string S."
19869 (or (get-text-property 0 prop s)
19870 (get-text-property (or (next-single-property-change 0 prop s) 0)
19871 prop s)))
19873 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19874 "Display the given MESSAGE as a warning."
19875 (if (fboundp 'display-warning)
19876 (display-warning 'org message
19877 (if (featurep 'xemacs) 'warning :warning))
19878 (let ((buf (get-buffer-create "*Org warnings*")))
19879 (with-current-buffer buf
19880 (goto-char (point-max))
19881 (insert "Warning (Org): " message)
19882 (unless (bolp)
19883 (newline)))
19884 (display-buffer buf)
19885 (sit-for 0))))
19887 (defun org-eval (form)
19888 "Eval FORM and return result."
19889 (condition-case error
19890 (eval form)
19891 (error (format "%%![Error: %s]" error))))
19893 (defun org-in-clocktable-p ()
19894 "Check if the cursor is in a clocktable."
19895 (let ((pos (point)) start)
19896 (save-excursion
19897 (end-of-line 1)
19898 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19899 (setq start (match-beginning 0))
19900 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19901 (>= (match-end 0) pos)
19902 start))))
19904 (defun org-in-commented-line ()
19905 "Is point in a line starting with `#'?"
19906 (equal (char-after (point-at-bol)) ?#))
19908 (defun org-in-indented-comment-line ()
19909 "Is point in a line starting with `#' after some white space?"
19910 (save-excursion
19911 (save-match-data
19912 (goto-char (point-at-bol))
19913 (looking-at "[ \t]*#"))))
19915 (defun org-in-verbatim-emphasis ()
19916 (save-match-data
19917 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19919 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19920 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19921 (if (and marker (marker-buffer marker)
19922 (buffer-live-p (marker-buffer marker)))
19923 (progn
19924 (org-pop-to-buffer-same-window (marker-buffer marker))
19925 (if (or (> marker (point-max)) (< marker (point-min)))
19926 (widen))
19927 (goto-char marker)
19928 (org-show-context 'org-goto))
19929 (if bookmark
19930 (bookmark-jump bookmark)
19931 (error "Cannot find location"))))
19933 (defun org-quote-csv-field (s)
19934 "Quote field for inclusion in CSV material."
19935 (if (string-match "[\",]" s)
19936 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19939 (defun org-force-self-insert (N)
19940 "Needed to enforce self-insert under remapping."
19941 (interactive "p")
19942 (self-insert-command N))
19944 (defun org-string-width (s)
19945 "Compute width of string, ignoring invisible characters.
19946 This ignores character with invisibility property `org-link', and also
19947 characters with property `org-cwidth', because these will become invisible
19948 upon the next fontification round."
19949 (let (b l)
19950 (when (or (eq t buffer-invisibility-spec)
19951 (assq 'org-link buffer-invisibility-spec))
19952 (while (setq b (text-property-any 0 (length s)
19953 'invisible 'org-link s))
19954 (setq s (concat (substring s 0 b)
19955 (substring s (or (next-single-property-change
19956 b 'invisible s) (length s)))))))
19957 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19958 (setq s (concat (substring s 0 b)
19959 (substring s (or (next-single-property-change
19960 b 'org-cwidth s) (length s))))))
19961 (setq l (string-width s) b -1)
19962 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19963 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19966 (defun org-shorten-string (s maxlength)
19967 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19968 If the string is shorter or has length MAXLENGTH, just return the
19969 original string. If it is longer, the functions finds a space in the
19970 string, breaks this string off at that locations and adds three dots
19971 as ellipsis. Including the ellipsis, the string will not be longer
19972 than MAXLENGTH. If finding a good breaking point in the string does
19973 not work, the string is just chopped off in the middle of a word
19974 if necessary."
19975 (if (<= (length s) maxlength)
19977 (let* ((n (max (- maxlength 4) 1))
19978 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19979 (if (string-match re s)
19980 (concat (match-string 1 s) "...")
19981 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19983 (defun org-get-indentation (&optional line)
19984 "Get the indentation of the current line, interpreting tabs.
19985 When LINE is given, assume it represents a line and compute its indentation."
19986 (if line
19987 (if (string-match "^ *" (org-remove-tabs line))
19988 (match-end 0))
19989 (save-excursion
19990 (beginning-of-line 1)
19991 (skip-chars-forward " \t")
19992 (current-column))))
19994 (defun org-get-string-indentation (s)
19995 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19996 (let ((n -1) (i 0) (w tab-width) c)
19997 (catch 'exit
19998 (while (< (setq n (1+ n)) (length s))
19999 (setq c (aref s n))
20000 (cond ((= c ?\ ) (setq i (1+ i)))
20001 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20002 (t (throw 'exit t)))))
20005 (defun org-remove-tabs (s &optional width)
20006 "Replace tabulators in S with spaces.
20007 Assumes that s is a single line, starting in column 0."
20008 (setq width (or width tab-width))
20009 (while (string-match "\t" s)
20010 (setq s (replace-match
20011 (make-string
20012 (- (* width (/ (+ (match-beginning 0) width) width))
20013 (match-beginning 0)) ?\ )
20014 t t s)))
20017 (defun org-fix-indentation (line ind)
20018 "Fix indentation in LINE.
20019 IND is a cons cell with target and minimum indentation.
20020 If the current indentation in LINE is smaller than the minimum,
20021 leave it alone. If it is larger than ind, set it to the target."
20022 (let* ((l (org-remove-tabs line))
20023 (i (org-get-indentation l))
20024 (i1 (car ind)) (i2 (cdr ind)))
20025 (if (>= i i2) (setq l (substring line i2)))
20026 (if (> i1 0)
20027 (concat (make-string i1 ?\ ) l)
20028 l)))
20030 (defun org-remove-indentation (code &optional n)
20031 "Remove the maximum common indentation from the lines in CODE.
20032 N may optionally be the number of spaces to remove."
20033 (with-temp-buffer
20034 (insert code)
20035 (org-do-remove-indentation n)
20036 (buffer-string)))
20038 (defun org-do-remove-indentation (&optional n)
20039 "Remove the maximum common indentation from the buffer."
20040 (untabify (point-min) (point-max))
20041 (let ((min 10000) re)
20042 (if n
20043 (setq min n)
20044 (goto-char (point-min))
20045 (while (re-search-forward "^ *[^ \n]" nil t)
20046 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20047 (unless (or (= min 0) (= min 10000))
20048 (setq re (format "^ \\{%d\\}" min))
20049 (goto-char (point-min))
20050 (while (re-search-forward re nil t)
20051 (replace-match "")
20052 (end-of-line 1))
20053 min)))
20055 (defun org-fill-template (template alist)
20056 "Find each %key of ALIST in TEMPLATE and replace it."
20057 (let ((case-fold-search nil)
20058 entry key value)
20059 (setq alist (sort (copy-sequence alist)
20060 (lambda (a b) (< (length (car a)) (length (car b))))))
20061 (while (setq entry (pop alist))
20062 (setq template
20063 (replace-regexp-in-string
20064 (concat "%" (regexp-quote (car entry)))
20065 (cdr entry) template t t)))
20066 template))
20068 (defun org-base-buffer (buffer)
20069 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20070 (if (not buffer)
20071 buffer
20072 (or (buffer-base-buffer buffer)
20073 buffer)))
20075 (defun org-trim (s)
20076 "Remove whitespace at beginning and end of string."
20077 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20078 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20081 (defun org-wrap (string &optional width lines)
20082 "Wrap string to either a number of lines, or a width in characters.
20083 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20084 that costs. If there is a word longer than WIDTH, the text is actually
20085 wrapped to the length of that word.
20086 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20087 many lines, whatever width that takes.
20088 The return value is a list of lines, without newlines at the end."
20089 (let* ((words (org-split-string string "[ \t\n]+"))
20090 (maxword (apply 'max (mapcar 'org-string-width words)))
20091 w ll)
20092 (cond (width
20093 (org-do-wrap words (max maxword width)))
20094 (lines
20095 (setq w maxword)
20096 (setq ll (org-do-wrap words maxword))
20097 (if (<= (length ll) lines)
20099 (setq ll words)
20100 (while (> (length ll) lines)
20101 (setq w (1+ w))
20102 (setq ll (org-do-wrap words w)))
20103 ll))
20104 (t (error "Cannot wrap this")))))
20106 (defun org-do-wrap (words width)
20107 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20108 (let (lines line)
20109 (while words
20110 (setq line (pop words))
20111 (while (and words (< (+ (length line) (length (car words))) width))
20112 (setq line (concat line " " (pop words))))
20113 (setq lines (push line lines)))
20114 (nreverse lines)))
20116 (defun org-split-string (string &optional separators)
20117 "Splits STRING into substrings at SEPARATORS.
20118 No empty strings are returned if there are matches at the beginning
20119 and end of string."
20120 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20121 (start 0)
20122 notfirst
20123 (list nil))
20124 (while (and (string-match rexp string
20125 (if (and notfirst
20126 (= start (match-beginning 0))
20127 (< start (length string)))
20128 (1+ start) start))
20129 (< (match-beginning 0) (length string)))
20130 (setq notfirst t)
20131 (or (eq (match-beginning 0) 0)
20132 (and (eq (match-beginning 0) (match-end 0))
20133 (eq (match-beginning 0) start))
20134 (setq list
20135 (cons (substring string start (match-beginning 0))
20136 list)))
20137 (setq start (match-end 0)))
20138 (or (eq start (length string))
20139 (setq list
20140 (cons (substring string start)
20141 list)))
20142 (nreverse list)))
20144 (defun org-quote-vert (s)
20145 "Replace \"|\" with \"\\vert\"."
20146 (while (string-match "|" s)
20147 (setq s (replace-match "\\vert" t t s)))
20150 (defun org-uuidgen-p (s)
20151 "Is S an ID created by UUIDGEN?"
20152 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20154 (defun org-in-src-block-p nil
20155 "Whether point is in a code source block."
20156 (let (ov)
20157 (when (setq ov (overlays-at (point)))
20158 (memq 'org-block-background
20159 (overlay-properties
20160 (car ov))))))
20162 (defun org-context ()
20163 "Return a list of contexts of the current cursor position.
20164 If several contexts apply, all are returned.
20165 Each context entry is a list with a symbol naming the context, and
20166 two positions indicating start and end of the context. Possible
20167 contexts are:
20169 :headline anywhere in a headline
20170 :headline-stars on the leading stars in a headline
20171 :todo-keyword on a TODO keyword (including DONE) in a headline
20172 :tags on the TAGS in a headline
20173 :priority on the priority cookie in a headline
20174 :item on the first line of a plain list item
20175 :item-bullet on the bullet/number of a plain list item
20176 :checkbox on the checkbox in a plain list item
20177 :table in an org-mode table
20178 :table-special on a special filed in a table
20179 :table-table in a table.el table
20180 :clocktable in a clocktable
20181 :src-block in a source block
20182 :link on a hyperlink
20183 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20184 :target on a <<target>>
20185 :radio-target on a <<<radio-target>>>
20186 :latex-fragment on a LaTeX fragment
20187 :latex-preview on a LaTeX fragment with overlaid preview image
20189 This function expects the position to be visible because it uses font-lock
20190 faces as a help to recognize the following contexts: :table-special, :link,
20191 and :keyword."
20192 (let* ((f (get-text-property (point) 'face))
20193 (faces (if (listp f) f (list f)))
20194 (case-fold-search t)
20195 (p (point)) clist o)
20196 ;; First the large context
20197 (cond
20198 ((org-at-heading-p t)
20199 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20200 (when (progn
20201 (beginning-of-line 1)
20202 (looking-at org-todo-line-tags-regexp))
20203 (push (org-point-in-group p 1 :headline-stars) clist)
20204 (push (org-point-in-group p 2 :todo-keyword) clist)
20205 (push (org-point-in-group p 4 :tags) clist))
20206 (goto-char p)
20207 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20208 (if (looking-at "\\[#[A-Z0-9]\\]")
20209 (push (org-point-in-group p 0 :priority) clist)))
20211 ((org-at-item-p)
20212 (push (org-point-in-group p 2 :item-bullet) clist)
20213 (push (list :item (point-at-bol)
20214 (save-excursion (org-end-of-item) (point)))
20215 clist)
20216 (and (org-at-item-checkbox-p)
20217 (push (org-point-in-group p 0 :checkbox) clist)))
20219 ((org-at-table-p)
20220 (push (list :table (org-table-begin) (org-table-end)) clist)
20221 (if (memq 'org-formula faces)
20222 (push (list :table-special
20223 (previous-single-property-change p 'face)
20224 (next-single-property-change p 'face)) clist)))
20225 ((org-at-table-p 'any)
20226 (push (list :table-table) clist)))
20227 (goto-char p)
20229 ;; New the "medium" contexts: clocktables, source blocks
20230 (cond ((org-in-clocktable-p)
20231 (push (list :clocktable
20232 (and (or (looking-at "#\\+BEGIN: clocktable")
20233 (search-backward "#+BEGIN: clocktable" nil t))
20234 (match-beginning 0))
20235 (and (re-search-forward "#\\+END:?" nil t)
20236 (match-end 0))) clist))
20237 ((org-in-src-block-p)
20238 (push (list :src-block
20239 (and (or (looking-at "#\\+BEGIN_SRC")
20240 (search-backward "#+BEGIN_SRC" nil t))
20241 (match-beginning 0))
20242 (and (search-forward "#+END_SRC" nil t)
20243 (match-beginning 0))) clist)))
20244 (goto-char p)
20246 ;; Now the small context
20247 (cond
20248 ((org-at-timestamp-p)
20249 (push (org-point-in-group p 0 :timestamp) clist))
20250 ((memq 'org-link faces)
20251 (push (list :link
20252 (previous-single-property-change p 'face)
20253 (next-single-property-change p 'face)) clist))
20254 ((memq 'org-special-keyword faces)
20255 (push (list :keyword
20256 (previous-single-property-change p 'face)
20257 (next-single-property-change p 'face)) clist))
20258 ((org-at-target-p)
20259 (push (org-point-in-group p 0 :target) clist)
20260 (goto-char (1- (match-beginning 0)))
20261 (if (looking-at org-radio-target-regexp)
20262 (push (org-point-in-group p 0 :radio-target) clist))
20263 (goto-char p))
20264 ((setq o (car (delq nil
20265 (mapcar
20266 (lambda (x)
20267 (if (memq x org-latex-fragment-image-overlays) x))
20268 (overlays-at (point))))))
20269 (push (list :latex-fragment
20270 (overlay-start o) (overlay-end o)) clist)
20271 (push (list :latex-preview
20272 (overlay-start o) (overlay-end o)) clist))
20273 ((org-inside-LaTeX-fragment-p)
20274 ;; FIXME: positions wrong.
20275 (push (list :latex-fragment (point) (point)) clist)))
20277 (setq clist (nreverse (delq nil clist)))
20278 clist))
20280 ;; FIXME: Compare with at-regexp-p Do we need both?
20281 (defun org-in-regexp (re &optional nlines visually)
20282 "Check if point is inside a match of regexp.
20283 Normally only the current line is checked, but you can include NLINES extra
20284 lines both before and after point into the search.
20285 If VISUALLY is set, require that the cursor is not after the match but
20286 really on, so that the block visually is on the match."
20287 (catch 'exit
20288 (let ((pos (point))
20289 (eol (point-at-eol (+ 1 (or nlines 0))))
20290 (inc (if visually 1 0)))
20291 (save-excursion
20292 (beginning-of-line (- 1 (or nlines 0)))
20293 (while (re-search-forward re eol t)
20294 (if (and (<= (match-beginning 0) pos)
20295 (>= (+ inc (match-end 0)) pos))
20296 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20298 (defun org-at-regexp-p (regexp)
20299 "Is point inside a match of REGEXP in the current line?"
20300 (catch 'exit
20301 (save-excursion
20302 (let ((pos (point)) (end (point-at-eol)))
20303 (beginning-of-line 1)
20304 (while (re-search-forward regexp end t)
20305 (if (and (<= (match-beginning 0) pos)
20306 (>= (match-end 0) pos))
20307 (throw 'exit t)))
20308 nil))))
20310 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20311 "Non-nil when point is between matches of START-RE and END-RE.
20313 Also return a non-nil value when point is on one of the matches.
20315 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20316 buffer positions. Default values are the positions of headlines
20317 surrounding the point.
20319 The functions returns a cons cell whose car (resp. cdr) is the
20320 position before START-RE (resp. after END-RE)."
20321 (save-match-data
20322 (let ((pos (point))
20323 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20324 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20325 beg end)
20326 (save-excursion
20327 ;; Point is on a block when on START-RE or if START-RE can be
20328 ;; found before it...
20329 (and (or (org-at-regexp-p start-re)
20330 (re-search-backward start-re limit-up t))
20331 (setq beg (match-beginning 0))
20332 ;; ... and END-RE after it...
20333 (goto-char (match-end 0))
20334 (re-search-forward end-re limit-down t)
20335 (> (setq end (match-end 0)) pos)
20336 ;; ... without another START-RE in-between.
20337 (goto-char (match-beginning 0))
20338 (not (re-search-backward start-re (1+ beg) t))
20339 ;; Return value.
20340 (cons beg end))))))
20342 (defun org-in-block-p (names)
20343 "Non-nil when point belongs to a block whose name belongs to NAMES.
20345 NAMES is a list of strings containing names of blocks.
20347 Return first block name matched, or nil. Beware that in case of
20348 nested blocks, the returned name may not belong to the closest
20349 block from point."
20350 (save-match-data
20351 (catch 'exit
20352 (let ((case-fold-search t)
20353 (lim-up (save-excursion (outline-previous-heading)))
20354 (lim-down (save-excursion (outline-next-heading))))
20355 (mapc (lambda (name)
20356 (let ((n (regexp-quote name)))
20357 (when (org-between-regexps-p
20358 (concat "^[ \t]*#\\+begin_" n)
20359 (concat "^[ \t]*#\\+end_" n)
20360 lim-up lim-down)
20361 (throw 'exit n))))
20362 names))
20363 nil)))
20365 (defun org-occur-in-agenda-files (regexp &optional nlines)
20366 "Call `multi-occur' with buffers for all agenda files."
20367 (interactive "sOrg-files matching: \np")
20368 (let* ((files (org-agenda-files))
20369 (tnames (mapcar 'file-truename files))
20370 (extra org-agenda-text-search-extra-files)
20372 (when (eq (car extra) 'agenda-archives)
20373 (setq extra (cdr extra))
20374 (setq files (org-add-archive-files files)))
20375 (while (setq f (pop extra))
20376 (unless (member (file-truename f) tnames)
20377 (add-to-list 'files f 'append)
20378 (add-to-list 'tnames (file-truename f) 'append)))
20379 (multi-occur
20380 (mapcar (lambda (x)
20381 (with-current-buffer
20382 (or (get-file-buffer x) (find-file-noselect x))
20383 (widen)
20384 (current-buffer)))
20385 files)
20386 regexp)))
20388 (if (boundp 'occur-mode-find-occurrence-hook)
20389 ;; Emacs 23
20390 (add-hook 'occur-mode-find-occurrence-hook
20391 (lambda ()
20392 (when (derived-mode-p 'org-mode)
20393 (org-reveal))))
20394 ;; Emacs 22
20395 (defadvice occur-mode-goto-occurrence
20396 (after org-occur-reveal activate)
20397 (and (derived-mode-p 'org-mode) (org-reveal)))
20398 (defadvice occur-mode-goto-occurrence-other-window
20399 (after org-occur-reveal activate)
20400 (and (derived-mode-p 'org-mode) (org-reveal)))
20401 (defadvice occur-mode-display-occurrence
20402 (after org-occur-reveal activate)
20403 (when (derived-mode-p 'org-mode)
20404 (let ((pos (occur-mode-find-occurrence)))
20405 (with-current-buffer (marker-buffer pos)
20406 (save-excursion
20407 (goto-char pos)
20408 (org-reveal)))))))
20410 (defun org-occur-link-in-agenda-files ()
20411 "Create a link and search for it in the agendas.
20412 The link is not stored in `org-stored-links', it is just created
20413 for the search purpose."
20414 (interactive)
20415 (let ((link (condition-case nil
20416 (org-store-link nil)
20417 (error "Unable to create a link to here"))))
20418 (org-occur-in-agenda-files (regexp-quote link))))
20420 (defun org-uniquify (list)
20421 "Remove duplicate elements from LIST."
20422 (let (res)
20423 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20424 res))
20426 (defun org-delete-all (elts list)
20427 "Remove all elements in ELTS from LIST."
20428 (while elts
20429 (setq list (delete (pop elts) list)))
20430 list)
20432 (defun org-count (cl-item cl-seq)
20433 "Count the number of occurrences of ITEM in SEQ.
20434 Taken from `count' in cl-seq.el with all keyword arguments removed."
20435 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20436 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20437 (while (< cl-start cl-end)
20438 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20439 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20440 (setq cl-start (1+ cl-start)))
20441 cl-count))
20443 (defun org-remove-if (predicate seq)
20444 "Remove everything from SEQ that fulfills PREDICATE."
20445 (let (res e)
20446 (while seq
20447 (setq e (pop seq))
20448 (if (not (funcall predicate e)) (push e res)))
20449 (nreverse res)))
20451 (defun org-remove-if-not (predicate seq)
20452 "Remove everything from SEQ that does not fulfill PREDICATE."
20453 (let (res e)
20454 (while seq
20455 (setq e (pop seq))
20456 (if (funcall predicate e) (push e res)))
20457 (nreverse res)))
20459 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20460 "Reduce two-argument FUNCTION across SEQ.
20461 Taken from `reduce' in cl-seq.el with all keyword arguments but
20462 \":initial-value\" removed."
20463 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20464 (cadr (memq :initial-value cl-keys)))
20465 (cl-seq (pop cl-seq))
20466 (t (funcall cl-func)))))
20467 (while cl-seq
20468 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20469 cl-accum))
20471 (defun org-back-over-empty-lines ()
20472 "Move backwards over whitespace, to the beginning of the first empty line.
20473 Returns the number of empty lines passed."
20474 (let ((pos (point)))
20475 (if (cdr (assoc 'heading org-blank-before-new-entry))
20476 (skip-chars-backward " \t\n\r")
20477 (unless (eobp)
20478 (forward-line -1)))
20479 (beginning-of-line 2)
20480 (goto-char (min (point) pos))
20481 (count-lines (point) pos)))
20483 (defun org-skip-whitespace ()
20484 (skip-chars-forward " \t\n\r"))
20486 (defun org-point-in-group (point group &optional context)
20487 "Check if POINT is in match-group GROUP.
20488 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20489 match. If the match group does not exist or point is not inside it,
20490 return nil."
20491 (and (match-beginning group)
20492 (>= point (match-beginning group))
20493 (<= point (match-end group))
20494 (if context
20495 (list context (match-beginning group) (match-end group))
20496 t)))
20498 (defun org-switch-to-buffer-other-window (&rest args)
20499 "Switch to buffer in a second window on the current frame.
20500 In particular, do not allow pop-up frames.
20501 Returns the newly created buffer."
20502 (let (pop-up-frames special-display-buffer-names special-display-regexps
20503 special-display-function)
20504 (apply 'switch-to-buffer-other-window args)))
20506 (defun org-combine-plists (&rest plists)
20507 "Create a single property list from all plists in PLISTS.
20508 The process starts by copying the first list, and then setting properties
20509 from the other lists. Settings in the last list are the most significant
20510 ones and overrule settings in the other lists."
20511 (let ((rtn (copy-sequence (pop plists)))
20512 p v ls)
20513 (while plists
20514 (setq ls (pop plists))
20515 (while ls
20516 (setq p (pop ls) v (pop ls))
20517 (setq rtn (plist-put rtn p v))))
20518 rtn))
20520 (defun org-replace-escapes (string table)
20521 "Replace %-escapes in STRING with values in TABLE.
20522 TABLE is an association list with keys like \"%a\" and string values.
20523 The sequences in STRING may contain normal field width and padding information,
20524 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20525 so values can contain further %-escapes if they are define later in TABLE."
20526 (let ((tbl (copy-alist table))
20527 (case-fold-search nil)
20528 (pchg 0)
20529 e re rpl)
20530 (while (setq e (pop tbl))
20531 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20532 (when (and (cdr e) (string-match re (cdr e)))
20533 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20534 (safe "SREF"))
20535 (add-text-properties 0 3 (list 'sref sref) safe)
20536 (setcdr e (replace-match safe t t (cdr e)))))
20537 (while (string-match re string)
20538 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20539 (cdr e)))
20540 (setq string (replace-match rpl t t string))))
20541 (while (setq pchg (next-property-change pchg string))
20542 (let ((sref (get-text-property pchg 'sref string)))
20543 (when (and sref (string-match "SREF" string pchg))
20544 (setq string (replace-match sref t t string)))))
20545 string))
20547 (defun org-sublist (list start end)
20548 "Return a section of LIST, from START to END.
20549 Counting starts at 1."
20550 (let (rtn (c start))
20551 (setq list (nthcdr (1- start) list))
20552 (while (and list (<= c end))
20553 (push (pop list) rtn)
20554 (setq c (1+ c)))
20555 (nreverse rtn)))
20557 (defun org-find-base-buffer-visiting (file)
20558 "Like `find-buffer-visiting' but always return the base buffer and
20559 not an indirect buffer."
20560 (let ((buf (or (get-file-buffer file)
20561 (find-buffer-visiting file))))
20562 (if buf
20563 (or (buffer-base-buffer buf) buf)
20564 nil)))
20566 (defun org-image-file-name-regexp (&optional extensions)
20567 "Return regexp matching the file names of images.
20568 If EXTENSIONS is given, only match these."
20569 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20570 (image-file-name-regexp)
20571 (let ((image-file-name-extensions
20572 (or extensions
20573 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20574 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20575 (concat "\\."
20576 (regexp-opt (nconc (mapcar 'upcase
20577 image-file-name-extensions)
20578 image-file-name-extensions)
20580 "\\'"))))
20582 (defun org-file-image-p (file &optional extensions)
20583 "Return non-nil if FILE is an image."
20584 (save-match-data
20585 (string-match (org-image-file-name-regexp extensions) file)))
20587 (defun org-get-cursor-date ()
20588 "Return the date at cursor in as a time.
20589 This works in the calendar and in the agenda, anywhere else it just
20590 returns the current time."
20591 (let (date day defd)
20592 (cond
20593 ((eq major-mode 'calendar-mode)
20594 (setq date (calendar-cursor-to-date)
20595 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20596 ((eq major-mode 'org-agenda-mode)
20597 (setq day (get-text-property (point) 'day))
20598 (if day
20599 (setq date (calendar-gregorian-from-absolute day)
20600 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20601 (nth 2 date))))))
20602 (or defd (current-time))))
20604 (defvar org-agenda-action-marker (make-marker)
20605 "Marker pointing to the entry for the next agenda action.")
20607 (defun org-mark-entry-for-agenda-action ()
20608 "Mark the current entry as target of an agenda action.
20609 Agenda actions are actions executed from the agenda with the key `k',
20610 which make use of the date at the cursor."
20611 (interactive)
20612 (move-marker org-agenda-action-marker
20613 (save-excursion (org-back-to-heading t) (point))
20614 (current-buffer))
20615 (message
20616 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20618 (defun org-mark-subtree ()
20619 "Mark the current subtree.
20620 This puts point at the start of the current subtree, and mark at the end.
20622 If point is in an inline task, mark that task instead."
20623 (interactive)
20624 (let ((inline-task-p
20625 (and (featurep 'org-inlinetask)
20626 (org-inlinetask-in-task-p)))
20627 (beg))
20628 ;; Get beginning of subtree
20629 (cond
20630 (inline-task-p (org-inlinetask-goto-beginning))
20631 ((org-at-heading-p) (beginning-of-line))
20632 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
20633 (setq beg (point))
20634 ;; Get end of it
20635 (if inline-task-p
20636 (org-inlinetask-goto-end)
20637 (org-end-of-subtree))
20638 ;; Mark zone
20639 (push-mark (point) nil t)
20640 (goto-char beg)))
20642 ;;; Indentation
20644 (defun org-indent-line ()
20645 "Indent line depending on context."
20646 (interactive)
20647 (let* ((pos (point))
20648 (itemp (org-at-item-p))
20649 (case-fold-search t)
20650 (org-drawer-regexp (or org-drawer-regexp "\000"))
20651 (inline-task-p (and (featurep 'org-inlinetask)
20652 (org-inlinetask-in-task-p)))
20653 (inline-re (and inline-task-p
20654 (org-inlinetask-outline-regexp)))
20655 column)
20656 (beginning-of-line 1)
20657 (cond
20658 ;; Headings
20659 ((looking-at org-outline-regexp) (setq column 0))
20660 ;; Included files
20661 ((looking-at "#\\+include:") (setq column 0))
20662 ;; Footnote definition
20663 ((looking-at org-footnote-definition-re) (setq column 0))
20664 ;; Literal examples
20665 ((looking-at "[ \t]*:\\( \\|$\\)")
20666 (setq column (org-get-indentation))) ; do nothing
20667 ;; Lists
20668 ((ignore-errors (goto-char (org-in-item-p)))
20669 (setq column (if itemp
20670 (org-get-indentation)
20671 (org-list-item-body-column (point))))
20672 (goto-char pos))
20673 ;; Drawers
20674 ((and (looking-at "[ \t]*:END:")
20675 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20676 (save-excursion
20677 (goto-char (1- (match-beginning 1)))
20678 (setq column (current-column))))
20679 ;; Special blocks
20680 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20681 (save-excursion
20682 (re-search-backward
20683 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20684 (setq column (org-get-indentation (match-string 0))))
20685 ((and (not (looking-at "[ \t]*#\\+begin_"))
20686 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20687 (save-excursion
20688 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20689 (setq column
20690 (cond ((equal (downcase (match-string 1)) "src")
20691 ;; src blocks: let `org-edit-src-exit' handle them
20692 (org-get-indentation))
20693 ((equal (downcase (match-string 1)) "example")
20694 (max (org-get-indentation)
20695 (org-get-indentation (match-string 0))))
20697 (org-get-indentation (match-string 0))))))
20698 ;; This line has nothing special, look at the previous relevant
20699 ;; line to compute indentation
20701 (beginning-of-line 0)
20702 (while (and (not (bobp))
20703 (not (looking-at org-drawer-regexp))
20704 ;; When point started in an inline task, do not move
20705 ;; above task starting line.
20706 (not (and inline-task-p (looking-at inline-re)))
20707 ;; Skip drawers, blocks, empty lines, verbatim,
20708 ;; comments, tables, footnotes definitions, lists,
20709 ;; inline tasks.
20710 (or (and (looking-at "[ \t]*:END:")
20711 (re-search-backward org-drawer-regexp nil t))
20712 (and (looking-at "[ \t]*#\\+end_")
20713 (re-search-backward "[ \t]*#\\+begin_"nil t))
20714 (looking-at "[ \t]*[\n:#|]")
20715 (looking-at org-footnote-definition-re)
20716 (and (ignore-errors (goto-char (org-in-item-p)))
20717 (goto-char
20718 (org-list-get-top-point (org-list-struct))))
20719 (and (not inline-task-p)
20720 (featurep 'org-inlinetask)
20721 (org-inlinetask-in-task-p)
20722 (or (org-inlinetask-goto-beginning) t))))
20723 (beginning-of-line 0))
20724 (cond
20725 ;; There was an heading above.
20726 ((looking-at "\\*+[ \t]+")
20727 (if (not org-adapt-indentation)
20728 (setq column 0)
20729 (goto-char (match-end 0))
20730 (setq column (current-column))))
20731 ;; A drawer had started and is unfinished
20732 ((looking-at org-drawer-regexp)
20733 (goto-char (1- (match-beginning 1)))
20734 (setq column (current-column)))
20735 ;; Else, nothing noticeable found: get indentation and go on.
20736 (t (setq column (org-get-indentation))))))
20737 ;; Now apply indentation and move cursor accordingly
20738 (goto-char pos)
20739 (if (<= (current-column) (current-indentation))
20740 (org-indent-line-to column)
20741 (save-excursion (org-indent-line-to column)))
20742 ;; Special polishing for properties, see `org-property-format'
20743 (setq column (current-column))
20744 (beginning-of-line 1)
20745 (if (looking-at
20746 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20747 (replace-match (concat (match-string 1)
20748 (format org-property-format
20749 (match-string 2) (match-string 3)))
20750 t t))
20751 (org-move-to-column column)
20752 (when (and orgstruct-is-++ (eq pos (point)))
20753 (org-let org-fb-vars
20754 '(indent-according-to-mode)))))
20756 (defun org-indent-drawer ()
20757 "Indent the drawer at point."
20758 (interactive)
20759 (let ((p (point))
20760 (e (and (save-excursion (re-search-forward ":END:" nil t))
20761 (match-end 0)))
20762 (folded
20763 (save-excursion
20764 (end-of-line)
20765 (when (overlays-at (point))
20766 (member 'invisible (overlay-properties
20767 (car (overlays-at (point)))))))))
20768 (when folded (org-cycle))
20769 (indent-for-tab-command)
20770 (while (and (move-beginning-of-line 2) (< (point) e))
20771 (indent-for-tab-command))
20772 (goto-char p)
20773 (when folded (org-cycle)))
20774 (message "Drawer at point indented"))
20776 (defun org-indent-block ()
20777 "Indent the block at point."
20778 (interactive)
20779 (let ((p (point))
20780 (case-fold-search t)
20781 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20782 (match-end 0)))
20783 (folded
20784 (save-excursion
20785 (end-of-line)
20786 (when (overlays-at (point))
20787 (member 'invisible (overlay-properties
20788 (car (overlays-at (point)))))))))
20789 (when folded (org-cycle))
20790 (indent-for-tab-command)
20791 (while (and (move-beginning-of-line 2) (< (point) e))
20792 (indent-for-tab-command))
20793 (goto-char p)
20794 (when folded (org-cycle)))
20795 (message "Block at point indented"))
20797 (defun org-indent-region (start end)
20798 "Indent region."
20799 (interactive "r")
20800 (save-excursion
20801 (let ((line-end (org-current-line end)))
20802 (goto-char start)
20803 (while (< (org-current-line) line-end)
20804 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20805 (t (call-interactively 'org-indent-line)))
20806 (move-beginning-of-line 2)))))
20809 ;;; Filling
20811 ;; We use our own fill-paragraph and auto-fill functions. These
20812 ;; functions will shadow `fill-prefix' (computed internally with
20813 ;; `org-fill-context-prefix') and pass through to
20814 ;; `fill-region-as-paragraph' and `do-auto-fill' as appropriate.
20816 (defun org-set-autofill-regexps ()
20817 (interactive)
20818 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20819 ;; Prevent auto-fill from inserting unwanted new items.
20820 (when (boundp 'fill-nobreak-predicate)
20821 (org-set-local
20822 'fill-nobreak-predicate
20823 (org-uniquify
20824 (append fill-nobreak-predicate
20825 '(org-fill-item-nobreak-p org-fill-line-break-nobreak-p)))))
20826 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20827 (org-set-local 'align-mode-rules-list
20828 '((org-in-buffer-settings
20829 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20830 (modes . '(org-mode))))))
20832 (defun org-fill-item-nobreak-p ()
20833 "Non-nil when a line break at point would insert a new item."
20834 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20836 (defun org-fill-line-break-nobreak-p ()
20837 "Non-nil when a line break at point would create an Org line break."
20838 (save-excursion
20839 (skip-chars-backward "[ \t]")
20840 (skip-chars-backward "\\\\")
20841 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20843 (defun org-fill-context-prefix (p)
20844 "Compute a fill prefix for the line at point P.
20845 Return fill prefix, as a string, or nil if current line isn't
20846 meant to be filled."
20847 (save-excursion
20848 (goto-char p)
20849 (beginning-of-line)
20850 (let* ((element (org-element-at-point))
20851 (type (org-element-type element))
20852 (post-affiliated
20853 (progn
20854 (goto-char (org-element-property :begin element))
20855 (while (looking-at org-element--affiliated-re) (forward-line))
20856 (point))))
20857 (unless (< p post-affiliated)
20858 (case type
20859 (comment (looking-at "[ \t]*# ?") (match-string 0))
20860 ((item plain-list)
20861 (make-string (org-list-item-body-column
20862 (org-element-property :begin element))
20863 ? ))
20864 (paragraph
20865 ;; Fill prefix is usually the same as the current line,
20866 ;; except if the paragraph is at the beginning of an item.
20867 (let ((parent (org-element-property :parent element)))
20868 (cond ((eq (org-element-type parent) 'item)
20869 (make-string (org-list-item-body-column
20870 (org-element-property :begin parent))
20871 ? ))
20872 ((looking-at "\\s-+") (match-string 0))
20873 (t ""))))
20874 ((comment-block verse-block)
20875 ;; Only fill contents if P is within block boundaries.
20876 (let* ((cbeg (save-excursion (goto-char post-affiliated)
20877 (forward-line)
20878 (point)))
20879 (cend (save-excursion
20880 (goto-char (org-element-property :end element))
20881 (skip-chars-backward " \r\t\n")
20882 (line-beginning-position))))
20883 (when (and (>= p cbeg) (< p cend))
20884 (if (looking-at "\\s-+") (match-string 0) "")))))))))
20886 (defun org-fill-paragraph (&optional justify)
20887 "Fill element at point, when applicable.
20889 This function only applies to comment blocks, comments, example
20890 blocks, paragraphs and verse blocks. Also, as a special case,
20891 re-align table when point is at one.
20893 If JUSTIFY is non-nil (interactively, with prefix argument),
20894 justify as well. If `sentence-end-double-space' is non-nil, then
20895 period followed by one space does not end a sentence, so don't
20896 break a line there. The variable `fill-column' controls the
20897 width for filling.
20899 For convenience, when point is at a plain list, an item or
20900 a footnote definition, try to fill the first paragraph within."
20901 (save-excursion
20902 ;; Move to end of line in order to get the first paragraph within
20903 ;; a plain list or a footnote definition.
20904 (end-of-line)
20905 (let ((element (org-element-at-point)))
20906 ;; First check if point is in a blank line at the beginning of the
20907 ;; buffer. In that case, ignore filling.
20908 (if (< (point) (org-element-property :begin element)) t
20909 (case (org-element-type element)
20910 ;; Align Org tables, leave table.el tables as-is.
20911 (table-row (org-table-align) t)
20912 (table
20913 (when (eq (org-element-property :type element) 'org)
20914 (org-table-align))
20916 ;; Elements that may contain `line-break' type objects.
20917 ((paragraph verse-block)
20918 (let ((beg (org-element-property :contents-begin element))
20919 (end (org-element-property :contents-end element))
20920 (type (org-element-type element)))
20921 ;; Do nothing if point is at an affiliated keyword or at
20922 ;; verse block markers.
20923 (if (or (< (point) beg)
20924 (and (eq type 'verse-block) (>= (point) end)))
20926 ;; At a verse block, first narrow to current "paragraph"
20927 ;; and set current element to that paragraph.
20928 (save-restriction
20929 (when (eq type 'verse-block)
20930 (narrow-to-region beg end)
20931 (save-excursion
20932 (let ((bol-pos (point-at-bol)))
20933 (re-search-backward
20934 org-element-paragraph-separate nil 'm)
20935 (unless (or (bobp) (= (point-at-bol) bol-pos))
20936 (forward-line))
20937 (setq element (org-element-paragraph-parser end)
20938 beg (org-element-property :contents-begin element)
20939 end (org-element-property
20940 :contents-end element)))))
20941 ;; Fill paragraph, taking line breaks into consideration.
20942 ;; For that, slice the paragraph using line breaks as
20943 ;; separators, and fill the parts in reverse order to
20944 ;; avoid messing with markers.
20945 (save-excursion
20946 (goto-char end)
20947 (mapc
20948 (lambda (pos)
20949 (let ((fill-prefix (org-fill-context-prefix pos)))
20950 (fill-region-as-paragraph pos (point) justify))
20951 (goto-char pos))
20952 ;; Find the list of ending positions for line breaks
20953 ;; in the current paragraph. Add paragraph beginning
20954 ;; to include first slice.
20955 (nreverse
20956 (cons beg
20957 (org-element-map
20958 (org-element--parse-objects
20959 beg end nil org-element-all-objects)
20960 'line-break
20961 (lambda (lb) (org-element-property :end lb))))))))
20962 t)))
20963 ;; Contents of `comment-block' type elements should be filled as
20964 ;; plain text.
20965 (comment-block
20966 (let ((fill-prefix (org-fill-context-prefix (point))))
20967 (save-excursion
20968 (fill-region-as-paragraph
20969 (progn
20970 (goto-char (org-element-property :begin element))
20971 (while (looking-at org-element--affiliated-re) (forward-line))
20972 (forward-line)
20973 (point))
20974 (progn
20975 (goto-char (org-element-property :end element))
20976 (skip-chars-backward " \r\t\n")
20977 (line-beginning-position))
20978 justify))) t)
20979 ;; Fill comments, indented or not.
20980 (comment
20981 (let ((fill-prefix (org-fill-context-prefix (point))))
20982 (save-excursion
20983 (fill-region-as-paragraph
20984 (progn
20985 (goto-char (org-element-property :begin element))
20986 (while (looking-at org-element--affiliated-re) (forward-line))
20987 (point))
20988 (progn
20989 (goto-char (org-element-property :end element))
20990 (skip-chars-backward " \r\t\n")
20991 (line-end-position))))))
20992 ;; Ignore every other element.
20993 (otherwise t))))))
20995 (defun org-auto-fill-function ()
20996 "Auto-fill function."
20997 ;; Check if auto-filling is meaningful before computing fill prefix.
20998 (let ((fc (current-fill-column)))
20999 (when (and fc (> (current-column) fc))
21000 (let ((fill-prefix (org-fill-context-prefix (point))))
21001 (when fill-prefix (do-auto-fill))))))
21004 ;;; Comments
21006 ;; Since difference between comments and keywords is subtle, we cannot
21007 ;; trust `comment-only-p' when applying `comment-dwim'. Hence, both
21008 ;; `comment-region-function' and `uncomment-region-function' point to
21009 ;; `org-comment-or-uncomment-region', which can tell when region only
21010 ;; contains comments or not.
21012 (defun org-insert-comment ()
21013 "Insert an empty comment above current line.
21014 If the line is empty, insert comment at its beginning."
21015 (beginning-of-line)
21016 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21017 (org-indent-line)
21018 (insert "# "))
21020 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21021 "Comment or uncomment each non-blank line in the region.
21022 Uncomment each non-blank line between BEG and END if it only
21023 contains commented lines. Otherwise, comment them."
21024 (save-excursion
21025 (goto-char beg)
21026 (skip-chars-forward " \r\t\n" end)
21027 (beginning-of-line)
21028 (let ((uncommentp
21029 ;; UNCOMMENTP is non-nil when every non blank line between
21030 ;; BEG and END is a comment.
21031 (save-excursion
21032 (while (progn (and (not (eobp))
21033 (let ((element (org-element-at-point)))
21034 (and (eq (org-element-type element) 'comment)
21035 (goto-char (org-element-property
21036 :end element)))))))
21037 (>= (point) end)))
21038 ;; Remove or adding comment markers is going to change end
21039 ;; position so make it a marker.
21040 (end (copy-marker end)))
21041 (while (< (point) end)
21042 (unless (looking-at "\\s-*$")
21043 (if (not uncommentp) (progn (back-to-indentation) (insert "# "))
21044 ;; Only comments and blank lines in region: uncomment it.
21045 (looking-at "[ \t]*\\(# ?\\)")
21046 (replace-match "" nil nil nil 1)))
21047 (forward-line))
21048 (set-marker end nil))))
21051 ;;; Other stuff.
21053 (defun org-toggle-fixed-width-section (arg)
21054 "Toggle the fixed-width export.
21055 If there is no active region, the QUOTE keyword at the current headline is
21056 inserted or removed. When present, it causes the text between this headline
21057 and the next to be exported as fixed-width text, and unmodified.
21058 If there is an active region, this command adds or removes a colon as the
21059 first character of this line. If the first character of a line is a colon,
21060 this line is also exported in fixed-width font."
21061 (interactive "P")
21062 (let* ((cc 0)
21063 (regionp (org-region-active-p))
21064 (beg (if regionp (region-beginning) (point)))
21065 (end (if regionp (region-end)))
21066 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21067 (case-fold-search nil)
21068 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21069 off)
21070 (if regionp
21071 (save-excursion
21072 (goto-char beg)
21073 (setq cc (current-column))
21074 (beginning-of-line 1)
21075 (setq off (looking-at re))
21076 (while (> nlines 0)
21077 (setq nlines (1- nlines))
21078 (beginning-of-line 1)
21079 (cond
21080 (arg
21081 (org-move-to-column cc t)
21082 (insert ": \n")
21083 (forward-line -1))
21084 ((and off (looking-at re))
21085 (replace-match "" t t nil 1))
21086 ((not off) (org-move-to-column cc t) (insert ": ")))
21087 (forward-line 1)))
21088 (save-excursion
21089 (org-back-to-heading)
21090 (cond
21091 ((looking-at (format org-heading-keyword-regexp-format
21092 org-quote-string))
21093 (goto-char (match-end 1))
21094 (looking-at (concat " +" org-quote-string))
21095 (replace-match "" t t)
21096 (when (eolp) (insert " ")))
21097 ((looking-at org-outline-regexp)
21098 (goto-char (match-end 0))
21099 (insert org-quote-string " ")))))))
21101 (defun org-reftex-citation ()
21102 "Use reftex-citation to insert a citation into the buffer.
21103 This looks for a line like
21105 #+BIBLIOGRAPHY: foo plain option:-d
21107 and derives from it that foo.bib is the bibliography file relevant
21108 for this document. It then installs the necessary environment for RefTeX
21109 to work in this buffer and calls `reftex-citation' to insert a citation
21110 into the buffer.
21112 Export of such citations to both LaTeX and HTML is handled by the contributed
21113 package org-exp-bibtex by Taru Karttunen."
21114 (interactive)
21115 (let ((reftex-docstruct-symbol 'rds)
21116 (reftex-cite-format "\\cite{%l}")
21117 rds bib)
21118 (save-excursion
21119 (save-restriction
21120 (widen)
21121 (let ((case-fold-search t)
21122 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21123 (if (not (save-excursion
21124 (or (re-search-forward re nil t)
21125 (re-search-backward re nil t))))
21126 (error "No bibliography defined in file")
21127 (setq bib (concat (match-string 1) ".bib")
21128 rds (list (list 'bib bib)))))))
21129 (call-interactively 'reftex-citation)))
21131 ;;;; Functions extending outline functionality
21133 (defun org-beginning-of-line (&optional arg)
21134 "Go to the beginning of the current line. If that is invisible, continue
21135 to a visible line beginning. This makes the function of C-a more intuitive.
21136 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21137 first attempt, and only move to after the tags when the cursor is already
21138 beyond the end of the headline."
21139 (interactive "P")
21140 (let ((pos (point))
21141 (special (if (consp org-special-ctrl-a/e)
21142 (car org-special-ctrl-a/e)
21143 org-special-ctrl-a/e))
21144 refpos)
21145 (if (org-bound-and-true-p line-move-visual)
21146 (beginning-of-visual-line 1)
21147 (beginning-of-line 1))
21148 (if (and arg (fboundp 'move-beginning-of-line))
21149 (call-interactively 'move-beginning-of-line)
21150 (if (bobp)
21152 (backward-char 1)
21153 (if (org-truely-invisible-p)
21154 (while (and (not (bobp)) (org-truely-invisible-p))
21155 (backward-char 1)
21156 (beginning-of-line 1))
21157 (forward-char 1))))
21158 (when special
21159 (cond
21160 ((and (looking-at org-complex-heading-regexp)
21161 (= (char-after (match-end 1)) ?\ ))
21162 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21163 (point-at-eol)))
21164 (goto-char
21165 (if (eq special t)
21166 (cond ((> pos refpos) refpos)
21167 ((= pos (point)) refpos)
21168 (t (point)))
21169 (cond ((> pos (point)) (point))
21170 ((not (eq last-command this-command)) (point))
21171 (t refpos)))))
21172 ((org-at-item-p)
21173 ;; Being at an item and not looking at an the item means point
21174 ;; was previously moved to beginning of a visual line, which
21175 ;; doesn't contain the item. Therefore, do nothing special,
21176 ;; just stay here.
21177 (when (looking-at org-list-full-item-re)
21178 ;; Set special position at first white space character after
21179 ;; bullet, and check-box, if any.
21180 (let ((after-bullet
21181 (let ((box (match-end 3)))
21182 (if (not box) (match-end 1)
21183 (let ((after (char-after box)))
21184 (if (and after (= after ? )) (1+ box) box))))))
21185 ;; Special case: Move point to special position when
21186 ;; currently after it or at beginning of line.
21187 (if (eq special t)
21188 (when (or (> pos after-bullet) (= (point) pos))
21189 (goto-char after-bullet))
21190 ;; Reversed case: Move point to special position when
21191 ;; point was already at beginning of line and command is
21192 ;; repeated.
21193 (when (and (= (point) pos) (eq last-command this-command))
21194 (goto-char after-bullet))))))))
21195 (org-no-warnings
21196 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21198 (defun org-end-of-line (&optional arg)
21199 "Go to the end of the line.
21200 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21201 first attempt, and only move to after the tags when the cursor is already
21202 beyond the end of the headline."
21203 (interactive "P")
21204 (let ((special (if (consp org-special-ctrl-a/e)
21205 (cdr org-special-ctrl-a/e)
21206 org-special-ctrl-a/e)))
21207 (cond
21208 ((or (not special) arg
21209 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21210 (call-interactively
21211 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21212 ((fboundp 'move-end-of-line) 'move-end-of-line)
21213 (t 'end-of-line))))
21214 ((org-at-heading-p)
21215 (let ((pos (point)))
21216 (beginning-of-line 1)
21217 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21218 (if (eq special t)
21219 (if (or (< pos (match-beginning 1))
21220 (= pos (match-end 0)))
21221 (goto-char (match-beginning 1))
21222 (goto-char (match-end 0)))
21223 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21224 (goto-char (match-end 0))
21225 (goto-char (match-beginning 1))))
21226 (call-interactively (if (fboundp 'move-end-of-line)
21227 'move-end-of-line
21228 'end-of-line)))))
21229 ((org-at-drawer-p)
21230 (move-end-of-line 1)
21231 (when (overlays-at (1- (point))) (backward-char 1)))
21232 ;; At an item: Move before any hidden text.
21233 (t (call-interactively
21234 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21235 ((fboundp 'move-end-of-line) 'move-end-of-line)
21236 (t 'end-of-line)))))
21237 (org-no-warnings
21238 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21240 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21241 (define-key org-mode-map "\C-e" 'org-end-of-line)
21243 (defun org-backward-sentence (&optional arg)
21244 "Go to beginning of sentence, or beginning of table field.
21245 This will call `backward-sentence' or `org-table-beginning-of-field',
21246 depending on context."
21247 (interactive "P")
21248 (cond
21249 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21250 (t (call-interactively 'backward-sentence))))
21252 (defun org-forward-sentence (&optional arg)
21253 "Go to end of sentence, or end of table field.
21254 This will call `forward-sentence' or `org-table-end-of-field',
21255 depending on context."
21256 (interactive "P")
21257 (cond
21258 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21259 (t (call-interactively 'forward-sentence))))
21261 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21262 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21264 (defun org-kill-line (&optional arg)
21265 "Kill line, to tags or end of line."
21266 (interactive "P")
21267 (cond
21268 ((or (not org-special-ctrl-k)
21269 (bolp)
21270 (not (org-at-heading-p)))
21271 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21272 org-ctrl-k-protect-subtree)
21273 (if (or (eq org-ctrl-k-protect-subtree 'error)
21274 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21275 (error "C-k aborted - would kill hidden subtree")))
21276 (call-interactively
21277 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21278 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21279 (kill-region (point) (match-beginning 1))
21280 (org-set-tags nil t))
21281 (t (kill-region (point) (point-at-eol)))))
21283 (define-key org-mode-map "\C-k" 'org-kill-line)
21285 (defun org-yank (&optional arg)
21286 "Yank. If the kill is a subtree, treat it specially.
21287 This command will look at the current kill and check if is a single
21288 subtree, or a series of subtrees[1]. If it passes the test, and if the
21289 cursor is at the beginning of a line or after the stars of a currently
21290 empty headline, then the yank is handled specially. How exactly depends
21291 on the value of the following variables, both set by default.
21293 org-yank-folded-subtrees
21294 When set, the subtree(s) will be folded after insertion, but only
21295 if doing so would now swallow text after the yanked text.
21297 org-yank-adjusted-subtrees
21298 When set, the subtree will be promoted or demoted in order to
21299 fit into the local outline tree structure, which means that the level
21300 will be adjusted so that it becomes the smaller one of the two
21301 *visible* surrounding headings.
21303 Any prefix to this command will cause `yank' to be called directly with
21304 no special treatment. In particular, a simple \\[universal-argument] prefix \
21305 will just
21306 plainly yank the text as it is.
21308 \[1] The test checks if the first non-white line is a heading
21309 and if there are no other headings with fewer stars."
21310 (interactive "P")
21311 (org-yank-generic 'yank arg))
21313 (defun org-yank-generic (command arg)
21314 "Perform some yank-like command.
21316 This function implements the behavior described in the `org-yank'
21317 documentation. However, it has been generalized to work for any
21318 interactive command with similar behavior."
21320 ;; pretend to be command COMMAND
21321 (setq this-command command)
21323 (if arg
21324 (call-interactively command)
21326 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21327 (and (org-kill-is-subtree-p)
21328 (or (bolp)
21329 (and (looking-at "[ \t]*$")
21330 (string-match
21331 "\\`\\*+\\'"
21332 (buffer-substring (point-at-bol) (point)))))))
21333 swallowp)
21334 (cond
21335 ((and subtreep org-yank-folded-subtrees)
21336 (let ((beg (point))
21337 end)
21338 (if (and subtreep org-yank-adjusted-subtrees)
21339 (org-paste-subtree nil nil 'for-yank)
21340 (call-interactively command))
21342 (setq end (point))
21343 (goto-char beg)
21344 (when (and (bolp) subtreep
21345 (not (setq swallowp
21346 (org-yank-folding-would-swallow-text beg end))))
21347 (org-with-limited-levels
21348 (or (looking-at org-outline-regexp)
21349 (re-search-forward org-outline-regexp-bol end t))
21350 (while (and (< (point) end) (looking-at org-outline-regexp))
21351 (hide-subtree)
21352 (org-cycle-show-empty-lines 'folded)
21353 (condition-case nil
21354 (outline-forward-same-level 1)
21355 (error (goto-char end))))))
21356 (when swallowp
21357 (message
21358 "Inserted text not folded because that would swallow text"))
21360 (goto-char end)
21361 (skip-chars-forward " \t\n\r")
21362 (beginning-of-line 1)
21363 (push-mark beg 'nomsg)))
21364 ((and subtreep org-yank-adjusted-subtrees)
21365 (let ((beg (point-at-bol)))
21366 (org-paste-subtree nil nil 'for-yank)
21367 (push-mark beg 'nomsg)))
21369 (call-interactively command))))))
21371 (defun org-yank-folding-would-swallow-text (beg end)
21372 "Would hide-subtree at BEG swallow any text after END?"
21373 (let (level)
21374 (org-with-limited-levels
21375 (save-excursion
21376 (goto-char beg)
21377 (when (or (looking-at org-outline-regexp)
21378 (re-search-forward org-outline-regexp-bol end t))
21379 (setq level (org-outline-level)))
21380 (goto-char end)
21381 (skip-chars-forward " \t\r\n\v\f")
21382 (if (or (eobp)
21383 (and (bolp) (looking-at org-outline-regexp)
21384 (<= (org-outline-level) level)))
21385 nil ; Nothing would be swallowed
21386 t))))) ; something would swallow
21388 (define-key org-mode-map "\C-y" 'org-yank)
21390 (defun org-truely-invisible-p ()
21391 "Check if point is at a character currently not visible.
21392 This version does not only check the character property, but also
21393 `visible-mode'."
21394 ;; Early versions of noutline don't have `outline-invisible-p'.
21395 (if (org-bound-and-true-p visible-mode)
21397 (outline-invisible-p)))
21399 (defun org-invisible-p2 ()
21400 "Check if point is at a character currently not visible."
21401 (save-excursion
21402 (if (and (eolp) (not (bobp))) (backward-char 1))
21403 ;; Early versions of noutline don't have `outline-invisible-p'.
21404 (outline-invisible-p)))
21406 (defun org-back-to-heading (&optional invisible-ok)
21407 "Call `outline-back-to-heading', but provide a better error message."
21408 (condition-case nil
21409 (outline-back-to-heading invisible-ok)
21410 (error (error "Before first headline at position %d in buffer %s"
21411 (point) (current-buffer)))))
21413 (defun org-beginning-of-defun ()
21414 "Go to the beginning of the subtree, i.e. back to the heading."
21415 (org-back-to-heading))
21416 (defun org-end-of-defun ()
21417 "Go to the end of the subtree."
21418 (org-end-of-subtree nil t))
21420 (defun org-before-first-heading-p ()
21421 "Before first heading?"
21422 (save-excursion
21423 (end-of-line)
21424 (null (re-search-backward org-outline-regexp-bol nil t))))
21426 (defun org-at-heading-p (&optional ignored)
21427 (outline-on-heading-p t))
21428 ;; Compatibility alias with Org versions < 7.8.03
21429 (defalias 'org-on-heading-p 'org-at-heading-p)
21431 (defun org-at-comment-p nil
21432 "Is cursor in a line starting with a # character?"
21433 (save-excursion
21434 (beginning-of-line)
21435 (looking-at "^#")))
21437 (defun org-at-drawer-p nil
21438 "Is cursor at a drawer keyword?"
21439 (save-excursion
21440 (move-beginning-of-line 1)
21441 (looking-at org-drawer-regexp)))
21443 (defun org-at-block-p nil
21444 "Is cursor at a block keyword?"
21445 (save-excursion
21446 (move-beginning-of-line 1)
21447 (looking-at org-block-regexp)))
21449 (defun org-point-at-end-of-empty-headline ()
21450 "If point is at the end of an empty headline, return t, else nil.
21451 If the heading only contains a TODO keyword, it is still still considered
21452 empty."
21453 (and (looking-at "[ \t]*$")
21454 (when org-todo-line-regexp
21455 (save-excursion
21456 (beginning-of-line 1)
21457 (let ((case-fold-search nil))
21458 (looking-at org-todo-line-regexp)
21459 (string= (match-string 3) ""))))))
21461 (defun org-at-heading-or-item-p ()
21462 (or (org-at-heading-p) (org-at-item-p)))
21464 (defun org-at-target-p ()
21465 (or (org-in-regexp org-radio-target-regexp)
21466 (org-in-regexp org-target-regexp)))
21467 ;; Compatibility alias with Org versions < 7.8.03
21468 (defalias 'org-on-target-p 'org-at-target-p)
21470 (defun org-up-heading-all (arg)
21471 "Move to the heading line of which the present line is a subheading.
21472 This function considers both visible and invisible heading lines.
21473 With argument, move up ARG levels."
21474 (if (fboundp 'outline-up-heading-all)
21475 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21476 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21478 (defun org-up-heading-safe ()
21479 "Move to the heading line of which the present line is a subheading.
21480 This version will not throw an error. It will return the level of the
21481 headline found, or nil if no higher level is found.
21483 Also, this function will be a lot faster than `outline-up-heading',
21484 because it relies on stars being the outline starters. This can really
21485 make a significant difference in outlines with very many siblings."
21486 (let (start-level re)
21487 (org-back-to-heading t)
21488 (setq start-level (funcall outline-level))
21489 (if (equal start-level 1)
21491 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21492 (if (re-search-backward re nil t)
21493 (funcall outline-level)))))
21495 (defun org-first-sibling-p ()
21496 "Is this heading the first child of its parents?"
21497 (interactive)
21498 (let ((re org-outline-regexp-bol)
21499 level l)
21500 (unless (org-at-heading-p t)
21501 (error "Not at a heading"))
21502 (setq level (funcall outline-level))
21503 (save-excursion
21504 (if (not (re-search-backward re nil t))
21506 (setq l (funcall outline-level))
21507 (< l level)))))
21509 (defun org-goto-sibling (&optional previous)
21510 "Goto the next sibling, even if it is invisible.
21511 When PREVIOUS is set, go to the previous sibling instead. Returns t
21512 when a sibling was found. When none is found, return nil and don't
21513 move point."
21514 (let ((fun (if previous 're-search-backward 're-search-forward))
21515 (pos (point))
21516 (re org-outline-regexp-bol)
21517 level l)
21518 (when (condition-case nil (org-back-to-heading t) (error nil))
21519 (setq level (funcall outline-level))
21520 (catch 'exit
21521 (or previous (forward-char 1))
21522 (while (funcall fun re nil t)
21523 (setq l (funcall outline-level))
21524 (when (< l level) (goto-char pos) (throw 'exit nil))
21525 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21526 (goto-char pos)
21527 nil))))
21529 (defun org-show-siblings ()
21530 "Show all siblings of the current headline."
21531 (save-excursion
21532 (while (org-goto-sibling) (org-flag-heading nil)))
21533 (save-excursion
21534 (while (org-goto-sibling 'previous)
21535 (org-flag-heading nil))))
21537 (defun org-goto-first-child ()
21538 "Goto the first child, even if it is invisible.
21539 Return t when a child was found. Otherwise don't move point and
21540 return nil."
21541 (let (level (pos (point)) (re org-outline-regexp-bol))
21542 (when (condition-case nil (org-back-to-heading t) (error nil))
21543 (setq level (outline-level))
21544 (forward-char 1)
21545 (if (and (re-search-forward re nil t) (> (outline-level) level))
21546 (progn (goto-char (match-beginning 0)) t)
21547 (goto-char pos) nil))))
21549 (defun org-show-hidden-entry ()
21550 "Show an entry where even the heading is hidden."
21551 (save-excursion
21552 (org-show-entry)))
21554 (defun org-flag-heading (flag &optional entry)
21555 "Flag the current heading. FLAG non-nil means make invisible.
21556 When ENTRY is non-nil, show the entire entry."
21557 (save-excursion
21558 (org-back-to-heading t)
21559 ;; Check if we should show the entire entry
21560 (if entry
21561 (progn
21562 (org-show-entry)
21563 (save-excursion
21564 (and (outline-next-heading)
21565 (org-flag-heading nil))))
21566 (outline-flag-region (max (point-min) (1- (point)))
21567 (save-excursion (outline-end-of-heading) (point))
21568 flag))))
21570 (defun org-get-next-sibling ()
21571 "Move to next heading of the same level, and return point.
21572 If there is no such heading, return nil.
21573 This is like outline-next-sibling, but invisible headings are ok."
21574 (let ((level (funcall outline-level)))
21575 (outline-next-heading)
21576 (while (and (not (eobp)) (> (funcall outline-level) level))
21577 (outline-next-heading))
21578 (if (or (eobp) (< (funcall outline-level) level))
21580 (point))))
21582 (defun org-get-last-sibling ()
21583 "Move to previous heading of the same level, and return point.
21584 If there is no such heading, return nil."
21585 (let ((opoint (point))
21586 (level (funcall outline-level)))
21587 (outline-previous-heading)
21588 (when (and (/= (point) opoint) (outline-on-heading-p t))
21589 (while (and (> (funcall outline-level) level)
21590 (not (bobp)))
21591 (outline-previous-heading))
21592 (if (< (funcall outline-level) level)
21594 (point)))))
21596 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21597 ;; This contains an exact copy of the original function, but it uses
21598 ;; `org-back-to-heading', to make it work also in invisible
21599 ;; trees. And is uses an invisible-OK argument.
21600 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21601 ;; Furthermore, when used inside Org, finding the end of a large subtree
21602 ;; with many children and grandchildren etc, this can be much faster
21603 ;; than the outline version.
21604 (org-back-to-heading invisible-OK)
21605 (let ((first t)
21606 (level (funcall outline-level)))
21607 (if (and (derived-mode-p 'org-mode) (< level 1000))
21608 ;; A true heading (not a plain list item), in Org-mode
21609 ;; This means we can easily find the end by looking
21610 ;; only for the right number of stars. Using a regexp to do
21611 ;; this is so much faster than using a Lisp loop.
21612 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21613 (forward-char 1)
21614 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21615 ;; something else, do it the slow way
21616 (while (and (not (eobp))
21617 (or first (> (funcall outline-level) level)))
21618 (setq first nil)
21619 (outline-next-heading)))
21620 (unless to-heading
21621 (if (memq (preceding-char) '(?\n ?\^M))
21622 (progn
21623 ;; Go to end of line before heading
21624 (forward-char -1)
21625 (if (memq (preceding-char) '(?\n ?\^M))
21626 ;; leave blank line before heading
21627 (forward-char -1))))))
21628 (point))
21630 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21631 "Use Org version in org-mode, for dramatic speed-up."
21632 (if (derived-mode-p 'org-mode)
21633 (progn
21634 (org-end-of-subtree nil t)
21635 (unless (eobp) (backward-char 1)))
21636 ad-do-it))
21638 (defun org-end-of-meta-data-and-drawers ()
21639 "Jump to the first text after meta data and drawers in the current entry.
21640 This will move over empty lines, lines with planning time stamps,
21641 clocking lines, and drawers."
21642 (org-back-to-heading t)
21643 (let ((end (save-excursion (outline-next-heading) (point)))
21644 (re (concat "\\(" org-drawer-regexp "\\)"
21645 "\\|" "[ \t]*" org-keyword-time-regexp)))
21646 (forward-line 1)
21647 (while (re-search-forward re end t)
21648 (if (not (match-end 1))
21649 ;; empty or planning line
21650 (forward-line 1)
21651 ;; a drawer, find the end
21652 (re-search-forward "^[ \t]*:END:" end 'move)
21653 (forward-line 1)))
21654 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21655 (point)))
21657 (defun org-forward-same-level (arg &optional invisible-ok)
21658 "Move forward to the arg'th subheading at same level as this one.
21659 Stop at the first and last subheadings of a superior heading.
21660 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
21661 it wil also look at invisible ones."
21662 (interactive "p")
21663 (org-back-to-heading invisible-ok)
21664 (org-at-heading-p)
21665 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21666 (re (format "^\\*\\{1,%d\\} " level))
21668 (forward-char 1)
21669 (while (> arg 0)
21670 (while (and (re-search-forward re nil 'move)
21671 (setq l (- (match-end 0) (match-beginning 0) 1))
21672 (= l level)
21673 (not invisible-ok)
21674 (progn (backward-char 1) (outline-invisible-p)))
21675 (if (< l level) (setq arg 1)))
21676 (setq arg (1- arg)))
21677 (beginning-of-line 1)))
21679 (defun org-backward-same-level (arg &optional invisible-ok)
21680 "Move backward to the arg'th subheading at same level as this one.
21681 Stop at the first and last subheadings of a superior heading."
21682 (interactive "p")
21683 (org-back-to-heading)
21684 (org-at-heading-p)
21685 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21686 (re (format "^\\*\\{1,%d\\} " level))
21688 (while (> arg 0)
21689 (while (and (re-search-backward re nil 'move)
21690 (setq l (- (match-end 0) (match-beginning 0) 1))
21691 (= l level)
21692 (not invisible-ok)
21693 (outline-invisible-p))
21694 (if (< l level) (setq arg 1)))
21695 (setq arg (1- arg)))))
21697 (defun org-show-subtree ()
21698 "Show everything after this heading at deeper levels."
21699 (interactive)
21700 (outline-flag-region
21701 (point)
21702 (save-excursion
21703 (org-end-of-subtree t t))
21704 nil))
21706 (defun org-show-entry ()
21707 "Show the body directly following this heading.
21708 Show the heading too, if it is currently invisible."
21709 (interactive)
21710 (save-excursion
21711 (condition-case nil
21712 (progn
21713 (org-back-to-heading t)
21714 (outline-flag-region
21715 (max (point-min) (1- (point)))
21716 (save-excursion
21717 (if (re-search-forward
21718 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
21719 (match-beginning 1)
21720 (point-max)))
21721 nil)
21722 (org-cycle-hide-drawers 'children))
21723 (error nil))))
21725 (defun org-make-options-regexp (kwds &optional extra)
21726 "Make a regular expression for keyword lines."
21727 (concat
21729 "#?[ \t]*\\+\\("
21730 (mapconcat 'regexp-quote kwds "\\|")
21731 (if extra (concat "\\|" extra))
21732 "\\):[ \t]*"
21733 "\\(.*\\)"))
21735 ;; Make isearch reveal the necessary context
21736 (defun org-isearch-end ()
21737 "Reveal context after isearch exits."
21738 (when isearch-success ; only if search was successful
21739 (if (featurep 'xemacs)
21740 ;; Under XEmacs, the hook is run in the correct place,
21741 ;; we directly show the context.
21742 (org-show-context 'isearch)
21743 ;; In Emacs the hook runs *before* restoring the overlays.
21744 ;; So we have to use a one-time post-command-hook to do this.
21745 ;; (Emacs 22 has a special variable, see function `org-mode')
21746 (unless (and (boundp 'isearch-mode-end-hook-quit)
21747 isearch-mode-end-hook-quit)
21748 ;; Only when the isearch was not quitted.
21749 (org-add-hook 'post-command-hook 'org-isearch-post-command
21750 'append 'local)))))
21752 (defun org-isearch-post-command ()
21753 "Remove self from hook, and show context."
21754 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21755 (org-show-context 'isearch))
21758 ;;;; Integration with and fixes for other packages
21760 ;;; Imenu support
21762 (defvar org-imenu-markers nil
21763 "All markers currently used by Imenu.")
21764 (make-variable-buffer-local 'org-imenu-markers)
21766 (defun org-imenu-new-marker (&optional pos)
21767 "Return a new marker for use by Imenu, and remember the marker."
21768 (let ((m (make-marker)))
21769 (move-marker m (or pos (point)))
21770 (push m org-imenu-markers)
21773 (defun org-imenu-get-tree ()
21774 "Produce the index for Imenu."
21775 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
21776 (setq org-imenu-markers nil)
21777 (let* ((n org-imenu-depth)
21778 (re (concat "^" (org-get-limited-outline-regexp)))
21779 (subs (make-vector (1+ n) nil))
21780 (last-level 0)
21781 m level head)
21782 (save-excursion
21783 (save-restriction
21784 (widen)
21785 (goto-char (point-max))
21786 (while (re-search-backward re nil t)
21787 (setq level (org-reduced-level (funcall outline-level)))
21788 (when (and (<= level n)
21789 (looking-at org-complex-heading-regexp))
21790 (setq head (org-link-display-format
21791 (org-match-string-no-properties 4))
21792 m (org-imenu-new-marker))
21793 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
21794 (if (>= level last-level)
21795 (push (cons head m) (aref subs level))
21796 (push (cons head (aref subs (1+ level))) (aref subs level))
21797 (loop for i from (1+ level) to n do (aset subs i nil)))
21798 (setq last-level level)))))
21799 (aref subs 1)))
21801 (eval-after-load "imenu"
21802 '(progn
21803 (add-hook 'imenu-after-jump-hook
21804 (lambda ()
21805 (if (derived-mode-p 'org-mode)
21806 (org-show-context 'org-goto))))))
21808 (defun org-link-display-format (link)
21809 "Replace a link with either the description, or the link target
21810 if no description is present"
21811 (save-match-data
21812 (if (string-match org-bracket-link-analytic-regexp link)
21813 (replace-match (if (match-end 5)
21814 (match-string 5 link)
21815 (concat (match-string 1 link)
21816 (match-string 3 link)))
21817 nil t link)
21818 link)))
21820 (defun org-toggle-link-display ()
21821 "Toggle the literal or descriptive display of links."
21822 (interactive)
21823 (if org-descriptive-links
21824 (progn (org-remove-from-invisibility-spec '(org-link))
21825 (org-restart-font-lock)
21826 (setq org-descriptive-links nil))
21827 (progn (add-to-invisibility-spec '(org-link))
21828 (org-restart-font-lock)
21829 (setq org-descriptive-links t))))
21831 ;; Speedbar support
21833 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
21834 "Overlay marking the agenda restriction line in speedbar.")
21835 (overlay-put org-speedbar-restriction-lock-overlay
21836 'face 'org-agenda-restriction-lock)
21837 (overlay-put org-speedbar-restriction-lock-overlay
21838 'help-echo "Agendas are currently limited to this item.")
21839 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21841 (defun org-speedbar-set-agenda-restriction ()
21842 "Restrict future agenda commands to the location at point in speedbar.
21843 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
21844 (interactive)
21845 (require 'org-agenda)
21846 (let (p m tp np dir txt)
21847 (cond
21848 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21849 'org-imenu t))
21850 (setq m (get-text-property p 'org-imenu-marker))
21851 (with-current-buffer (marker-buffer m)
21852 (goto-char m)
21853 (org-agenda-set-restriction-lock 'subtree)))
21854 ((setq p (text-property-any (point-at-bol) (point-at-eol)
21855 'speedbar-function 'speedbar-find-file))
21856 (setq tp (previous-single-property-change
21857 (1+ p) 'speedbar-function)
21858 np (next-single-property-change
21859 tp 'speedbar-function)
21860 dir (speedbar-line-directory)
21861 txt (buffer-substring-no-properties (or tp (point-min))
21862 (or np (point-max))))
21863 (with-current-buffer (find-file-noselect
21864 (let ((default-directory dir))
21865 (expand-file-name txt)))
21866 (unless (derived-mode-p 'org-mode)
21867 (error "Cannot restrict to non-Org-mode file"))
21868 (org-agenda-set-restriction-lock 'file)))
21869 (t (error "Don't know how to restrict Org-mode's agenda")))
21870 (move-overlay org-speedbar-restriction-lock-overlay
21871 (point-at-bol) (point-at-eol))
21872 (setq current-prefix-arg nil)
21873 (org-agenda-maybe-redo)))
21875 (eval-after-load "speedbar"
21876 '(progn
21877 (speedbar-add-supported-extension ".org")
21878 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21879 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21880 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21881 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21882 (add-hook 'speedbar-visiting-tag-hook
21883 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
21885 ;;; Fixes and Hacks for problems with other packages
21887 ;; Make flyspell not check words in links, to not mess up our keymap
21888 (defun org-mode-flyspell-verify ()
21889 "Don't let flyspell put overlays at active buttons, or on
21890 {todo,all-time,additional-option-like}-keywords."
21891 (let ((pos (max (1- (point)) (point-min)))
21892 (word (thing-at-point 'word)))
21893 (and (not (get-text-property pos 'keymap))
21894 (not (get-text-property pos 'org-no-flyspell))
21895 (not (member word org-todo-keywords-1))
21896 (not (member word org-all-time-keywords))
21897 (not (member word org-options-keywords))
21898 (not (member word (mapcar 'car org-startup-options)))
21899 (not (member word org-additional-option-like-keywords-for-flyspell)))))
21901 (defun org-remove-flyspell-overlays-in (beg end)
21902 "Remove flyspell overlays in region."
21903 (and (org-bound-and-true-p flyspell-mode)
21904 (fboundp 'flyspell-delete-region-overlays)
21905 (flyspell-delete-region-overlays beg end))
21906 (add-text-properties beg end '(org-no-flyspell t)))
21908 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21909 (eval-after-load "bookmark"
21910 '(if (boundp 'bookmark-after-jump-hook)
21911 ;; We can use the hook
21912 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21913 ;; Hook not available, use advice
21914 (defadvice bookmark-jump (after org-make-visible activate)
21915 "Make the position visible."
21916 (org-bookmark-jump-unhide))))
21918 ;; Make sure saveplace shows the location if it was hidden
21919 (eval-after-load "saveplace"
21920 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21921 "Make the position visible."
21922 (org-bookmark-jump-unhide)))
21924 ;; Make sure ecb shows the location if it was hidden
21925 (eval-after-load "ecb"
21926 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21927 "Make hierarchy visible when jumping into location from ECB tree buffer."
21928 (if (derived-mode-p 'org-mode)
21929 (org-show-context))))
21931 (defun org-bookmark-jump-unhide ()
21932 "Unhide the current position, to show the bookmark location."
21933 (and (derived-mode-p 'org-mode)
21934 (or (outline-invisible-p)
21935 (save-excursion (goto-char (max (point-min) (1- (point))))
21936 (outline-invisible-p)))
21937 (org-show-context 'bookmark-jump)))
21939 ;; Make session.el ignore our circular variable
21940 (eval-after-load "session"
21941 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21943 ;;;; Experimental code
21945 (defun org-closed-in-range ()
21946 "Sparse tree of items closed in a certain time range.
21947 Still experimental, may disappear in the future."
21948 (interactive)
21949 ;; Get the time interval from the user.
21950 (let* ((time1 (org-float-time
21951 (org-read-date nil 'to-time nil "Starting date: ")))
21952 (time2 (org-float-time
21953 (org-read-date nil 'to-time nil "End date:")))
21954 ;; callback function
21955 (callback (lambda ()
21956 (let ((time
21957 (org-float-time
21958 (apply 'encode-time
21959 (org-parse-time-string
21960 (match-string 1))))))
21961 ;; check if time in interval
21962 (and (>= time time1) (<= time time2))))))
21963 ;; make tree, check each match with the callback
21964 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21966 ;;;; Finish up
21968 (provide 'org)
21970 (run-hooks 'org-load-hook)
21972 ;;; org.el ends here